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