mistral.rs

  1use anyhow::{Result, anyhow};
  2use collections::BTreeMap;
  3
  4use futures::{FutureExt, Stream, StreamExt, future, future::BoxFuture, stream::BoxStream};
  5use gpui::{AnyView, App, AsyncApp, Context, Entity, Global, SharedString, Task, Window};
  6use http_client::HttpClient;
  7use language_model::{
  8    ApiKeyState, AuthenticateError, EnvVar, LanguageModel, LanguageModelCompletionError,
  9    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
 10    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
 11    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
 12    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
 13};
 14pub use mistral::{CODESTRAL_API_URL, MISTRAL_API_URL, StreamResponse};
 15pub use settings::MistralAvailableModel as AvailableModel;
 16use settings::{Settings, SettingsStore};
 17use std::collections::HashMap;
 18use std::pin::Pin;
 19use std::str::FromStr;
 20use std::sync::{Arc, LazyLock, OnceLock};
 21use strum::IntoEnumIterator;
 22use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 23use ui_input::InputField;
 24use util::ResultExt;
 25
 26const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("mistral");
 27const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Mistral");
 28
 29const API_KEY_ENV_VAR_NAME: &str = "MISTRAL_API_KEY";
 30static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
 31
 32const CODESTRAL_API_KEY_ENV_VAR_NAME: &str = "CODESTRAL_API_KEY";
 33static CODESTRAL_API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(CODESTRAL_API_KEY_ENV_VAR_NAME);
 34static CODESTRAL_API_KEY: OnceLock<Entity<ApiKeyState>> = OnceLock::new();
 35
 36#[derive(Default, Clone, Debug, PartialEq)]
 37pub struct MistralSettings {
 38    pub api_url: String,
 39    pub available_models: Vec<AvailableModel>,
 40}
 41
 42pub struct MistralLanguageModelProvider {
 43    http_client: Arc<dyn HttpClient>,
 44    pub state: Entity<State>,
 45}
 46
 47pub struct State {
 48    api_key_state: ApiKeyState,
 49    codestral_api_key_state: Entity<ApiKeyState>,
 50}
 51
 52pub fn codestral_api_key(cx: &mut App) -> Entity<ApiKeyState> {
 53    return CODESTRAL_API_KEY
 54        .get_or_init(|| {
 55            cx.new(|_| {
 56                ApiKeyState::new(CODESTRAL_API_URL.into(), CODESTRAL_API_KEY_ENV_VAR.clone())
 57            })
 58        })
 59        .clone();
 60}
 61
 62impl State {
 63    fn is_authenticated(&self) -> bool {
 64        self.api_key_state.has_key()
 65    }
 66
 67    fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
 68        let api_url = MistralLanguageModelProvider::api_url(cx);
 69        self.api_key_state
 70            .store(api_url, api_key, |this| &mut this.api_key_state, cx)
 71    }
 72
 73    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 74        let api_url = MistralLanguageModelProvider::api_url(cx);
 75        self.api_key_state
 76            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
 77    }
 78
 79    fn authenticate_codestral(
 80        &mut self,
 81        cx: &mut Context<Self>,
 82    ) -> Task<Result<(), AuthenticateError>> {
 83        self.codestral_api_key_state.update(cx, |state, cx| {
 84            state.load_if_needed(CODESTRAL_API_URL.into(), |state| state, cx)
 85        })
 86    }
 87}
 88
 89struct GlobalMistralLanguageModelProvider(Arc<MistralLanguageModelProvider>);
 90
 91impl Global for GlobalMistralLanguageModelProvider {}
 92
 93impl MistralLanguageModelProvider {
 94    pub fn try_global(cx: &App) -> Option<&Arc<MistralLanguageModelProvider>> {
 95        cx.try_global::<GlobalMistralLanguageModelProvider>()
 96            .map(|this| &this.0)
 97    }
 98
 99    pub fn global(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Arc<Self> {
100        if let Some(this) = cx.try_global::<GlobalMistralLanguageModelProvider>() {
101            return this.0.clone();
102        }
103        let state = cx.new(|cx| {
104            cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
105                let api_url = Self::api_url(cx);
106                this.api_key_state
107                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
108                cx.notify();
109            })
110            .detach();
111            State {
112                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
113                codestral_api_key_state: codestral_api_key(cx),
114            }
115        });
116
117        let this = Arc::new(Self { http_client, state });
118        cx.set_global(GlobalMistralLanguageModelProvider(this));
119        cx.global::<GlobalMistralLanguageModelProvider>().0.clone()
120    }
121
122    pub fn load_codestral_api_key(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
123        self.state
124            .update(cx, |state, cx| state.authenticate_codestral(cx))
125    }
126
127    pub fn codestral_api_key(&self, url: &str, cx: &App) -> Option<Arc<str>> {
128        self.state
129            .read(cx)
130            .codestral_api_key_state
131            .read(cx)
132            .key(url)
133    }
134
135    fn create_language_model(&self, model: mistral::Model) -> Arc<dyn LanguageModel> {
136        Arc::new(MistralLanguageModel {
137            id: LanguageModelId::from(model.id().to_string()),
138            model,
139            state: self.state.clone(),
140            http_client: self.http_client.clone(),
141            request_limiter: RateLimiter::new(4),
142        })
143    }
144
145    fn settings(cx: &App) -> &MistralSettings {
146        &crate::AllLanguageModelSettings::get_global(cx).mistral
147    }
148
149    pub fn api_url(cx: &App) -> SharedString {
150        let api_url = &Self::settings(cx).api_url;
151        if api_url.is_empty() {
152            mistral::MISTRAL_API_URL.into()
153        } else {
154            SharedString::new(api_url.as_str())
155        }
156    }
157}
158
159impl LanguageModelProviderState for MistralLanguageModelProvider {
160    type ObservableEntity = State;
161
162    fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
163        Some(self.state.clone())
164    }
165}
166
167impl LanguageModelProvider for MistralLanguageModelProvider {
168    fn id(&self) -> LanguageModelProviderId {
169        PROVIDER_ID
170    }
171
172    fn name(&self) -> LanguageModelProviderName {
173        PROVIDER_NAME
174    }
175
176    fn icon(&self) -> IconName {
177        IconName::AiMistral
178    }
179
180    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
181        Some(self.create_language_model(mistral::Model::default()))
182    }
183
184    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
185        Some(self.create_language_model(mistral::Model::default_fast()))
186    }
187
188    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
189        let mut models = BTreeMap::default();
190
191        // Add base models from mistral::Model::iter()
192        for model in mistral::Model::iter() {
193            if !matches!(model, mistral::Model::Custom { .. }) {
194                models.insert(model.id().to_string(), model);
195            }
196        }
197
198        // Override with available models from settings
199        for model in &Self::settings(cx).available_models {
200            models.insert(
201                model.name.clone(),
202                mistral::Model::Custom {
203                    name: model.name.clone(),
204                    display_name: model.display_name.clone(),
205                    max_tokens: model.max_tokens,
206                    max_output_tokens: model.max_output_tokens,
207                    max_completion_tokens: model.max_completion_tokens,
208                    supports_tools: model.supports_tools,
209                    supports_images: model.supports_images,
210                    supports_thinking: model.supports_thinking,
211                },
212            );
213        }
214
215        models
216            .into_values()
217            .map(|model| {
218                Arc::new(MistralLanguageModel {
219                    id: LanguageModelId::from(model.id().to_string()),
220                    model,
221                    state: self.state.clone(),
222                    http_client: self.http_client.clone(),
223                    request_limiter: RateLimiter::new(4),
224                }) as Arc<dyn LanguageModel>
225            })
226            .collect()
227    }
228
229    fn is_authenticated(&self, cx: &App) -> bool {
230        self.state.read(cx).is_authenticated()
231    }
232
233    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
234        self.state.update(cx, |state, cx| state.authenticate(cx))
235    }
236
237    fn configuration_view(
238        &self,
239        _target_agent: language_model::ConfigurationViewTargetAgent,
240        window: &mut Window,
241        cx: &mut App,
242    ) -> AnyView {
243        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
244            .into()
245    }
246
247    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
248        self.state
249            .update(cx, |state, cx| state.set_api_key(None, cx))
250    }
251}
252
253pub struct MistralLanguageModel {
254    id: LanguageModelId,
255    model: mistral::Model,
256    state: Entity<State>,
257    http_client: Arc<dyn HttpClient>,
258    request_limiter: RateLimiter,
259}
260
261impl MistralLanguageModel {
262    fn stream_completion(
263        &self,
264        request: mistral::Request,
265        cx: &AsyncApp,
266    ) -> BoxFuture<
267        'static,
268        Result<futures::stream::BoxStream<'static, Result<mistral::StreamResponse>>>,
269    > {
270        let http_client = self.http_client.clone();
271
272        let Ok((api_key, api_url)) = self.state.read_with(cx, |state, cx| {
273            let api_url = MistralLanguageModelProvider::api_url(cx);
274            (state.api_key_state.key(&api_url), api_url)
275        }) else {
276            return future::ready(Err(anyhow!("App state dropped"))).boxed();
277        };
278
279        let future = self.request_limiter.stream(async move {
280            let Some(api_key) = api_key else {
281                return Err(LanguageModelCompletionError::NoApiKey {
282                    provider: PROVIDER_NAME,
283                });
284            };
285            let request =
286                mistral::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
287            let response = request.await?;
288            Ok(response)
289        });
290
291        async move { Ok(future.await?.boxed()) }.boxed()
292    }
293}
294
295impl LanguageModel for MistralLanguageModel {
296    fn id(&self) -> LanguageModelId {
297        self.id.clone()
298    }
299
300    fn name(&self) -> LanguageModelName {
301        LanguageModelName::from(self.model.display_name().to_string())
302    }
303
304    fn provider_id(&self) -> LanguageModelProviderId {
305        PROVIDER_ID
306    }
307
308    fn provider_name(&self) -> LanguageModelProviderName {
309        PROVIDER_NAME
310    }
311
312    fn supports_tools(&self) -> bool {
313        self.model.supports_tools()
314    }
315
316    fn supports_tool_choice(&self, _choice: LanguageModelToolChoice) -> bool {
317        self.model.supports_tools()
318    }
319
320    fn supports_images(&self) -> bool {
321        self.model.supports_images()
322    }
323
324    fn telemetry_id(&self) -> String {
325        format!("mistral/{}", self.model.id())
326    }
327
328    fn max_token_count(&self) -> u64 {
329        self.model.max_token_count()
330    }
331
332    fn max_output_tokens(&self) -> Option<u64> {
333        self.model.max_output_tokens()
334    }
335
336    fn count_tokens(
337        &self,
338        request: LanguageModelRequest,
339        cx: &App,
340    ) -> BoxFuture<'static, Result<u64>> {
341        cx.background_spawn(async move {
342            let messages = request
343                .messages
344                .into_iter()
345                .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
346                    role: match message.role {
347                        Role::User => "user".into(),
348                        Role::Assistant => "assistant".into(),
349                        Role::System => "system".into(),
350                    },
351                    content: Some(message.string_contents()),
352                    name: None,
353                    function_call: None,
354                })
355                .collect::<Vec<_>>();
356
357            tiktoken_rs::num_tokens_from_messages("gpt-4", &messages).map(|tokens| tokens as u64)
358        })
359        .boxed()
360    }
361
362    fn stream_completion(
363        &self,
364        request: LanguageModelRequest,
365        cx: &AsyncApp,
366    ) -> BoxFuture<
367        'static,
368        Result<
369            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
370            LanguageModelCompletionError,
371        >,
372    > {
373        let request = into_mistral(request, self.model.clone(), self.max_output_tokens());
374        let stream = self.stream_completion(request, cx);
375
376        async move {
377            let stream = stream.await?;
378            let mapper = MistralEventMapper::new();
379            Ok(mapper.map_stream(stream).boxed())
380        }
381        .boxed()
382    }
383}
384
385pub fn into_mistral(
386    request: LanguageModelRequest,
387    model: mistral::Model,
388    max_output_tokens: Option<u64>,
389) -> mistral::Request {
390    let stream = true;
391
392    let mut messages = Vec::new();
393    for message in &request.messages {
394        match message.role {
395            Role::User => {
396                let mut message_content = mistral::MessageContent::empty();
397                for content in &message.content {
398                    match content {
399                        MessageContent::Text(text) => {
400                            message_content
401                                .push_part(mistral::MessagePart::Text { text: text.clone() });
402                        }
403                        MessageContent::Image(image_content) => {
404                            if model.supports_images() {
405                                message_content.push_part(mistral::MessagePart::ImageUrl {
406                                    image_url: image_content.to_base64_url(),
407                                });
408                            }
409                        }
410                        MessageContent::Thinking { text, .. } => {
411                            if model.supports_thinking() {
412                                message_content.push_part(mistral::MessagePart::Thinking {
413                                    thinking: vec![mistral::ThinkingPart::Text {
414                                        text: text.clone(),
415                                    }],
416                                });
417                            }
418                        }
419                        MessageContent::RedactedThinking(_) => {}
420                        MessageContent::ToolUse(_) => {
421                            // Tool use is not supported in User messages for Mistral
422                        }
423                        MessageContent::ToolResult(tool_result) => {
424                            let tool_content = match &tool_result.content {
425                                LanguageModelToolResultContent::Text(text) => text.to_string(),
426                                LanguageModelToolResultContent::Image(_) => {
427                                    "[Tool responded with an image, but Zed doesn't support these in Mistral models yet]".to_string()
428                                }
429                            };
430                            messages.push(mistral::RequestMessage::Tool {
431                                content: tool_content,
432                                tool_call_id: tool_result.tool_use_id.to_string(),
433                            });
434                        }
435                    }
436                }
437                if !matches!(message_content, mistral::MessageContent::Plain { ref content } if content.is_empty())
438                {
439                    messages.push(mistral::RequestMessage::User {
440                        content: message_content,
441                    });
442                }
443            }
444            Role::Assistant => {
445                for content in &message.content {
446                    match content {
447                        MessageContent::Text(text) => {
448                            messages.push(mistral::RequestMessage::Assistant {
449                                content: Some(mistral::MessageContent::Plain {
450                                    content: text.clone(),
451                                }),
452                                tool_calls: Vec::new(),
453                            });
454                        }
455                        MessageContent::Thinking { text, .. } => {
456                            if model.supports_thinking() {
457                                messages.push(mistral::RequestMessage::Assistant {
458                                    content: Some(mistral::MessageContent::Multipart {
459                                        content: vec![mistral::MessagePart::Thinking {
460                                            thinking: vec![mistral::ThinkingPart::Text {
461                                                text: text.clone(),
462                                            }],
463                                        }],
464                                    }),
465                                    tool_calls: Vec::new(),
466                                });
467                            }
468                        }
469                        MessageContent::RedactedThinking(_) => {}
470                        MessageContent::Image(_) => {}
471                        MessageContent::ToolUse(tool_use) => {
472                            let tool_call = mistral::ToolCall {
473                                id: tool_use.id.to_string(),
474                                content: mistral::ToolCallContent::Function {
475                                    function: mistral::FunctionContent {
476                                        name: tool_use.name.to_string(),
477                                        arguments: serde_json::to_string(&tool_use.input)
478                                            .unwrap_or_default(),
479                                    },
480                                },
481                            };
482
483                            if let Some(mistral::RequestMessage::Assistant { tool_calls, .. }) =
484                                messages.last_mut()
485                            {
486                                tool_calls.push(tool_call);
487                            } else {
488                                messages.push(mistral::RequestMessage::Assistant {
489                                    content: None,
490                                    tool_calls: vec![tool_call],
491                                });
492                            }
493                        }
494                        MessageContent::ToolResult(_) => {
495                            // Tool results are not supported in Assistant messages
496                        }
497                    }
498                }
499            }
500            Role::System => {
501                for content in &message.content {
502                    match content {
503                        MessageContent::Text(text) => {
504                            messages.push(mistral::RequestMessage::System {
505                                content: mistral::MessageContent::Plain {
506                                    content: text.clone(),
507                                },
508                            });
509                        }
510                        MessageContent::Thinking { text, .. } => {
511                            if model.supports_thinking() {
512                                messages.push(mistral::RequestMessage::System {
513                                    content: mistral::MessageContent::Multipart {
514                                        content: vec![mistral::MessagePart::Thinking {
515                                            thinking: vec![mistral::ThinkingPart::Text {
516                                                text: text.clone(),
517                                            }],
518                                        }],
519                                    },
520                                });
521                            }
522                        }
523                        MessageContent::RedactedThinking(_) => {}
524                        MessageContent::Image(_)
525                        | MessageContent::ToolUse(_)
526                        | MessageContent::ToolResult(_) => {
527                            // Images and tools are not supported in System messages
528                        }
529                    }
530                }
531            }
532        }
533    }
534
535    mistral::Request {
536        model: model.id().to_string(),
537        messages,
538        stream,
539        max_tokens: max_output_tokens,
540        temperature: request.temperature,
541        response_format: None,
542        tool_choice: match request.tool_choice {
543            Some(LanguageModelToolChoice::Auto) if !request.tools.is_empty() => {
544                Some(mistral::ToolChoice::Auto)
545            }
546            Some(LanguageModelToolChoice::Any) if !request.tools.is_empty() => {
547                Some(mistral::ToolChoice::Any)
548            }
549            Some(LanguageModelToolChoice::None) => Some(mistral::ToolChoice::None),
550            _ if !request.tools.is_empty() => Some(mistral::ToolChoice::Auto),
551            _ => None,
552        },
553        parallel_tool_calls: if !request.tools.is_empty() {
554            Some(false)
555        } else {
556            None
557        },
558        tools: request
559            .tools
560            .into_iter()
561            .map(|tool| mistral::ToolDefinition::Function {
562                function: mistral::FunctionDefinition {
563                    name: tool.name,
564                    description: Some(tool.description),
565                    parameters: Some(tool.input_schema),
566                },
567            })
568            .collect(),
569    }
570}
571
572pub struct MistralEventMapper {
573    tool_calls_by_index: HashMap<usize, RawToolCall>,
574}
575
576impl MistralEventMapper {
577    pub fn new() -> Self {
578        Self {
579            tool_calls_by_index: HashMap::default(),
580        }
581    }
582
583    pub fn map_stream(
584        mut self,
585        events: Pin<Box<dyn Send + Stream<Item = Result<StreamResponse>>>>,
586    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
587    {
588        events.flat_map(move |event| {
589            futures::stream::iter(match event {
590                Ok(event) => self.map_event(event),
591                Err(error) => vec![Err(LanguageModelCompletionError::from(error))],
592            })
593        })
594    }
595
596    pub fn map_event(
597        &mut self,
598        event: mistral::StreamResponse,
599    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
600        let Some(choice) = event.choices.first() else {
601            return vec![Err(LanguageModelCompletionError::from(anyhow!(
602                "Response contained no choices"
603            )))];
604        };
605
606        let mut events = Vec::new();
607        if let Some(content) = choice.delta.content.as_ref() {
608            match content {
609                mistral::MessageContentDelta::Text(text) => {
610                    events.push(Ok(LanguageModelCompletionEvent::Text(text.clone())));
611                }
612                mistral::MessageContentDelta::Parts(parts) => {
613                    for part in parts {
614                        match part {
615                            mistral::MessagePart::Text { text } => {
616                                events.push(Ok(LanguageModelCompletionEvent::Text(text.clone())));
617                            }
618                            mistral::MessagePart::Thinking { thinking } => {
619                                for tp in thinking.iter().cloned() {
620                                    match tp {
621                                        mistral::ThinkingPart::Text { text } => {
622                                            events.push(Ok(
623                                                LanguageModelCompletionEvent::Thinking {
624                                                    text,
625                                                    signature: None,
626                                                },
627                                            ));
628                                        }
629                                    }
630                                }
631                            }
632                            mistral::MessagePart::ImageUrl { .. } => {
633                                // We currently don't emit a separate event for images in responses.
634                            }
635                        }
636                    }
637                }
638            }
639        }
640
641        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
642            for tool_call in tool_calls {
643                let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
644
645                if let Some(tool_id) = tool_call.id.clone() {
646                    entry.id = tool_id;
647                }
648
649                if let Some(function) = tool_call.function.as_ref() {
650                    if let Some(name) = function.name.clone() {
651                        entry.name = name;
652                    }
653
654                    if let Some(arguments) = function.arguments.clone() {
655                        entry.arguments.push_str(&arguments);
656                    }
657                }
658            }
659        }
660
661        if let Some(usage) = event.usage {
662            events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
663                input_tokens: usage.prompt_tokens,
664                output_tokens: usage.completion_tokens,
665                cache_creation_input_tokens: 0,
666                cache_read_input_tokens: 0,
667            })));
668        }
669
670        if let Some(finish_reason) = choice.finish_reason.as_deref() {
671            match finish_reason {
672                "stop" => {
673                    events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
674                }
675                "tool_calls" => {
676                    events.extend(self.process_tool_calls());
677                    events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
678                }
679                unexpected => {
680                    log::error!("Unexpected Mistral stop_reason: {unexpected:?}");
681                    events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
682                }
683            }
684        }
685
686        events
687    }
688
689    fn process_tool_calls(
690        &mut self,
691    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
692        let mut results = Vec::new();
693
694        for (_, tool_call) in self.tool_calls_by_index.drain() {
695            if tool_call.id.is_empty() || tool_call.name.is_empty() {
696                results.push(Err(LanguageModelCompletionError::from(anyhow!(
697                    "Received incomplete tool call: missing id or name"
698                ))));
699                continue;
700            }
701
702            match serde_json::Value::from_str(&tool_call.arguments) {
703                Ok(input) => results.push(Ok(LanguageModelCompletionEvent::ToolUse(
704                    LanguageModelToolUse {
705                        id: tool_call.id.into(),
706                        name: tool_call.name.into(),
707                        is_input_complete: true,
708                        input,
709                        raw_input: tool_call.arguments,
710                        thought_signature: None,
711                    },
712                ))),
713                Err(error) => {
714                    results.push(Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
715                        id: tool_call.id.into(),
716                        tool_name: tool_call.name.into(),
717                        raw_input: tool_call.arguments.into(),
718                        json_parse_error: error.to_string(),
719                    }))
720                }
721            }
722        }
723
724        results
725    }
726}
727
728#[derive(Default)]
729struct RawToolCall {
730    id: String,
731    name: String,
732    arguments: String,
733}
734
735struct ConfigurationView {
736    api_key_editor: Entity<InputField>,
737    state: Entity<State>,
738    load_credentials_task: Option<Task<()>>,
739}
740
741impl ConfigurationView {
742    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
743        let api_key_editor =
744            cx.new(|cx| InputField::new(window, cx, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
745
746        cx.observe(&state, |_, _, cx| {
747            cx.notify();
748        })
749        .detach();
750
751        let load_credentials_task = Some(cx.spawn_in(window, {
752            let state = state.clone();
753            async move |this, cx| {
754                if let Some(task) = state
755                    .update(cx, |state, cx| state.authenticate(cx))
756                    .log_err()
757                {
758                    // We don't log an error, because "not signed in" is also an error.
759                    let _ = task.await;
760                }
761
762                this.update(cx, |this, cx| {
763                    this.load_credentials_task = None;
764                    cx.notify();
765                })
766                .log_err();
767            }
768        }));
769
770        Self {
771            api_key_editor,
772            state,
773            load_credentials_task,
774        }
775    }
776
777    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
778        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
779        if api_key.is_empty() {
780            return;
781        }
782
783        // url changes can cause the editor to be displayed again
784        self.api_key_editor
785            .update(cx, |editor, cx| editor.set_text("", window, cx));
786
787        let state = self.state.clone();
788        cx.spawn_in(window, async move |_, cx| {
789            state
790                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))?
791                .await
792        })
793        .detach_and_log_err(cx);
794    }
795
796    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
797        self.api_key_editor
798            .update(cx, |editor, cx| editor.set_text("", window, cx));
799
800        let state = self.state.clone();
801        cx.spawn_in(window, async move |_, cx| {
802            state
803                .update(cx, |state, cx| state.set_api_key(None, cx))?
804                .await
805        })
806        .detach_and_log_err(cx);
807    }
808
809    fn should_render_api_key_editor(&self, cx: &mut Context<Self>) -> bool {
810        !self.state.read(cx).is_authenticated()
811    }
812}
813
814impl Render for ConfigurationView {
815    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
816        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
817        let configured_card_label = if env_var_set {
818            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
819        } else {
820            let api_url = MistralLanguageModelProvider::api_url(cx);
821            if api_url == MISTRAL_API_URL {
822                "API key configured".to_string()
823            } else {
824                format!("API key configured for {}", api_url)
825            }
826        };
827
828        if self.load_credentials_task.is_some() {
829            div().child(Label::new("Loading credentials...")).into_any()
830        } else if self.should_render_api_key_editor(cx) {
831            v_flex()
832                .size_full()
833                .on_action(cx.listener(Self::save_api_key))
834                .child(Label::new("To use Zed's agent with Mistral, you need to add an API key. Follow these steps:"))
835                .child(
836                    List::new()
837                        .child(
838                            ListBulletItem::new("")
839                                .child(Label::new("Create one by visiting"))
840                                .child(ButtonLink::new("Mistral's console", "https://console.mistral.ai/api-keys"))
841                        )
842                        .child(
843                            ListBulletItem::new("Ensure your Mistral account has credits")
844                        )
845                        .child(
846                            ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
847                        ),
848                )
849                .child(self.api_key_editor.clone())
850                .child(
851                    Label::new(
852                        format!("You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
853                    )
854                    .size(LabelSize::Small).color(Color::Muted),
855                )
856                .into_any()
857        } else {
858            v_flex()
859                .size_full()
860                .gap_1()
861                .child(
862                    ConfiguredApiCard::new(configured_card_label)
863                        .disabled(env_var_set)
864                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
865                        .when(env_var_set, |this| {
866                            this.tooltip_label(format!(
867                                "To reset your API key, \
868                                unset the {API_KEY_ENV_VAR_NAME} environment variable."
869                            ))
870                        }),
871                )
872                .into_any()
873        }
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    use super::*;
880    use language_model::{LanguageModelImage, LanguageModelRequestMessage, MessageContent};
881
882    #[test]
883    fn test_into_mistral_basic_conversion() {
884        let request = LanguageModelRequest {
885            messages: vec![
886                LanguageModelRequestMessage {
887                    role: Role::System,
888                    content: vec![MessageContent::Text("System prompt".into())],
889                    cache: false,
890                    reasoning_details: None,
891                },
892                LanguageModelRequestMessage {
893                    role: Role::User,
894                    content: vec![MessageContent::Text("Hello".into())],
895                    cache: false,
896                    reasoning_details: None,
897                },
898            ],
899            temperature: Some(0.5),
900            tools: vec![],
901            tool_choice: None,
902            thread_id: None,
903            prompt_id: None,
904            intent: None,
905            mode: None,
906            stop: vec![],
907            thinking_allowed: true,
908        };
909
910        let mistral_request = into_mistral(request, mistral::Model::MistralSmallLatest, None);
911
912        assert_eq!(mistral_request.model, "mistral-small-latest");
913        assert_eq!(mistral_request.temperature, Some(0.5));
914        assert_eq!(mistral_request.messages.len(), 2);
915        assert!(mistral_request.stream);
916    }
917
918    #[test]
919    fn test_into_mistral_with_image() {
920        let request = LanguageModelRequest {
921            messages: vec![LanguageModelRequestMessage {
922                role: Role::User,
923                content: vec![
924                    MessageContent::Text("What's in this image?".into()),
925                    MessageContent::Image(LanguageModelImage {
926                        source: "base64data".into(),
927                        size: Default::default(),
928                    }),
929                ],
930                cache: false,
931                reasoning_details: None,
932            }],
933            tools: vec![],
934            tool_choice: None,
935            temperature: None,
936            thread_id: None,
937            prompt_id: None,
938            intent: None,
939            mode: None,
940            stop: vec![],
941            thinking_allowed: true,
942        };
943
944        let mistral_request = into_mistral(request, mistral::Model::Pixtral12BLatest, None);
945
946        assert_eq!(mistral_request.messages.len(), 1);
947        assert!(matches!(
948            &mistral_request.messages[0],
949            mistral::RequestMessage::User {
950                content: mistral::MessageContent::Multipart { .. }
951            }
952        ));
953
954        if let mistral::RequestMessage::User {
955            content: mistral::MessageContent::Multipart { content },
956        } = &mistral_request.messages[0]
957        {
958            assert_eq!(content.len(), 2);
959            assert!(matches!(
960                &content[0],
961                mistral::MessagePart::Text { text } if text == "What's in this image?"
962            ));
963            assert!(matches!(
964                &content[1],
965                mistral::MessagePart::ImageUrl { image_url } if image_url.starts_with("data:image/png;base64,")
966            ));
967        }
968    }
969}