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_streaming_tools(&self) -> bool {
284 true
285 }
286
287 fn supports_tool_choice(&self, _choice: LanguageModelToolChoice) -> bool {
288 self.model.supports_tools()
289 }
290
291 fn supports_images(&self) -> bool {
292 self.model.supports_images()
293 }
294
295 fn telemetry_id(&self) -> String {
296 format!("mistral/{}", self.model.id())
297 }
298
299 fn max_token_count(&self) -> u64 {
300 self.model.max_token_count()
301 }
302
303 fn max_output_tokens(&self) -> Option<u64> {
304 self.model.max_output_tokens()
305 }
306
307 fn count_tokens(
308 &self,
309 request: LanguageModelRequest,
310 cx: &App,
311 ) -> BoxFuture<'static, Result<u64>> {
312 cx.background_spawn(async move {
313 let messages = request
314 .messages
315 .into_iter()
316 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
317 role: match message.role {
318 Role::User => "user".into(),
319 Role::Assistant => "assistant".into(),
320 Role::System => "system".into(),
321 },
322 content: Some(message.string_contents()),
323 name: None,
324 function_call: None,
325 })
326 .collect::<Vec<_>>();
327
328 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages).map(|tokens| tokens as u64)
329 })
330 .boxed()
331 }
332
333 fn stream_completion(
334 &self,
335 request: LanguageModelRequest,
336 cx: &AsyncApp,
337 ) -> BoxFuture<
338 'static,
339 Result<
340 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
341 LanguageModelCompletionError,
342 >,
343 > {
344 let (request, affinity) =
345 into_mistral(request, self.model.clone(), self.max_output_tokens());
346 let stream = self.stream_completion(request, affinity, cx);
347
348 async move {
349 let stream = stream.await?;
350 let mapper = MistralEventMapper::new();
351 Ok(mapper.map_stream(stream).boxed())
352 }
353 .boxed()
354 }
355}
356
357pub fn into_mistral(
358 request: LanguageModelRequest,
359 model: mistral::Model,
360 max_output_tokens: Option<u64>,
361) -> (mistral::Request, Option<String>) {
362 let stream = true;
363
364 let mut messages = Vec::new();
365 for message in &request.messages {
366 match message.role {
367 Role::User => {
368 let mut message_content = mistral::MessageContent::empty();
369 for content in &message.content {
370 match content {
371 MessageContent::Text(text) => {
372 message_content
373 .push_part(mistral::MessagePart::Text { text: text.clone() });
374 }
375 MessageContent::Image(image_content) => {
376 if model.supports_images() {
377 message_content.push_part(mistral::MessagePart::ImageUrl {
378 image_url: image_content.to_base64_url(),
379 });
380 }
381 }
382 MessageContent::Thinking { text, .. } => {
383 if model.supports_thinking() {
384 message_content.push_part(mistral::MessagePart::Thinking {
385 thinking: vec![mistral::ThinkingPart::Text {
386 text: text.clone(),
387 }],
388 });
389 }
390 }
391 MessageContent::RedactedThinking(_) => {}
392 MessageContent::ToolUse(_) => {
393 // Tool use is not supported in User messages for Mistral
394 }
395 MessageContent::ToolResult(tool_result) => {
396 let tool_content = match &tool_result.content {
397 LanguageModelToolResultContent::Text(text) => text.to_string(),
398 LanguageModelToolResultContent::Image(_) => {
399 "[Tool responded with an image, but Zed doesn't support these in Mistral models yet]".to_string()
400 }
401 };
402 messages.push(mistral::RequestMessage::Tool {
403 content: tool_content,
404 tool_call_id: tool_result.tool_use_id.to_string(),
405 });
406 }
407 }
408 }
409 if !matches!(message_content, mistral::MessageContent::Plain { ref content } if content.is_empty())
410 {
411 messages.push(mistral::RequestMessage::User {
412 content: message_content,
413 });
414 }
415 }
416 Role::Assistant => {
417 for content in &message.content {
418 match content {
419 MessageContent::Text(text) if text.is_empty() => {
420 // Mistral API returns a 400 if there's neither content nor tool_calls
421 }
422 MessageContent::Text(text) => {
423 messages.push(mistral::RequestMessage::Assistant {
424 content: Some(mistral::MessageContent::Plain {
425 content: text.clone(),
426 }),
427 tool_calls: Vec::new(),
428 });
429 }
430 MessageContent::Thinking { text, .. } => {
431 if model.supports_thinking() {
432 messages.push(mistral::RequestMessage::Assistant {
433 content: Some(mistral::MessageContent::Multipart {
434 content: vec![mistral::MessagePart::Thinking {
435 thinking: vec![mistral::ThinkingPart::Text {
436 text: text.clone(),
437 }],
438 }],
439 }),
440 tool_calls: Vec::new(),
441 });
442 }
443 }
444 MessageContent::RedactedThinking(_) => {}
445 MessageContent::Image(_) => {}
446 MessageContent::ToolUse(tool_use) => {
447 let tool_call = mistral::ToolCall {
448 id: tool_use.id.to_string(),
449 content: mistral::ToolCallContent::Function {
450 function: mistral::FunctionContent {
451 name: tool_use.name.to_string(),
452 arguments: serde_json::to_string(&tool_use.input)
453 .unwrap_or_default(),
454 },
455 },
456 };
457
458 if let Some(mistral::RequestMessage::Assistant { tool_calls, .. }) =
459 messages.last_mut()
460 {
461 tool_calls.push(tool_call);
462 } else {
463 messages.push(mistral::RequestMessage::Assistant {
464 content: None,
465 tool_calls: vec![tool_call],
466 });
467 }
468 }
469 MessageContent::ToolResult(_) => {
470 // Tool results are not supported in Assistant messages
471 }
472 }
473 }
474 }
475 Role::System => {
476 for content in &message.content {
477 match content {
478 MessageContent::Text(text) => {
479 messages.push(mistral::RequestMessage::System {
480 content: mistral::MessageContent::Plain {
481 content: text.clone(),
482 },
483 });
484 }
485 MessageContent::Thinking { text, .. } => {
486 if model.supports_thinking() {
487 messages.push(mistral::RequestMessage::System {
488 content: mistral::MessageContent::Multipart {
489 content: vec![mistral::MessagePart::Thinking {
490 thinking: vec![mistral::ThinkingPart::Text {
491 text: text.clone(),
492 }],
493 }],
494 },
495 });
496 }
497 }
498 MessageContent::RedactedThinking(_) => {}
499 MessageContent::Image(_)
500 | MessageContent::ToolUse(_)
501 | MessageContent::ToolResult(_) => {
502 // Images and tools are not supported in System messages
503 }
504 }
505 }
506 }
507 }
508 }
509
510 (
511 mistral::Request {
512 model: model.id().to_string(),
513 messages,
514 stream,
515 max_tokens: max_output_tokens,
516 temperature: request.temperature,
517 response_format: None,
518 tool_choice: match request.tool_choice {
519 Some(LanguageModelToolChoice::Auto) if !request.tools.is_empty() => {
520 Some(mistral::ToolChoice::Auto)
521 }
522 Some(LanguageModelToolChoice::Any) if !request.tools.is_empty() => {
523 Some(mistral::ToolChoice::Any)
524 }
525 Some(LanguageModelToolChoice::None) => Some(mistral::ToolChoice::None),
526 _ if !request.tools.is_empty() => Some(mistral::ToolChoice::Auto),
527 _ => None,
528 },
529 parallel_tool_calls: if !request.tools.is_empty() {
530 Some(false)
531 } else {
532 None
533 },
534 tools: request
535 .tools
536 .into_iter()
537 .map(|tool| mistral::ToolDefinition::Function {
538 function: mistral::FunctionDefinition {
539 name: tool.name,
540 description: Some(tool.description),
541 parameters: Some(tool.input_schema),
542 },
543 })
544 .collect(),
545 },
546 request.thread_id,
547 )
548}
549
550pub struct MistralEventMapper {
551 tool_calls_by_index: HashMap<usize, RawToolCall>,
552}
553
554impl MistralEventMapper {
555 pub fn new() -> Self {
556 Self {
557 tool_calls_by_index: HashMap::default(),
558 }
559 }
560
561 pub fn map_stream(
562 mut self,
563 events: Pin<Box<dyn Send + Stream<Item = Result<StreamResponse>>>>,
564 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
565 {
566 events.flat_map(move |event| {
567 futures::stream::iter(match event {
568 Ok(event) => self.map_event(event),
569 Err(error) => vec![Err(LanguageModelCompletionError::from(error))],
570 })
571 })
572 }
573
574 pub fn map_event(
575 &mut self,
576 event: mistral::StreamResponse,
577 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
578 let Some(choice) = event.choices.first() else {
579 return vec![Err(LanguageModelCompletionError::from(anyhow!(
580 "Response contained no choices"
581 )))];
582 };
583
584 let mut events = Vec::new();
585 if let Some(content) = choice.delta.content.as_ref() {
586 match content {
587 mistral::MessageContentDelta::Text(text) => {
588 events.push(Ok(LanguageModelCompletionEvent::Text(text.clone())));
589 }
590 mistral::MessageContentDelta::Parts(parts) => {
591 for part in parts {
592 match part {
593 mistral::MessagePart::Text { text } => {
594 events.push(Ok(LanguageModelCompletionEvent::Text(text.clone())));
595 }
596 mistral::MessagePart::Thinking { thinking } => {
597 for tp in thinking.iter().cloned() {
598 match tp {
599 mistral::ThinkingPart::Text { text } => {
600 events.push(Ok(
601 LanguageModelCompletionEvent::Thinking {
602 text,
603 signature: None,
604 },
605 ));
606 }
607 }
608 }
609 }
610 mistral::MessagePart::ImageUrl { .. } => {
611 // We currently don't emit a separate event for images in responses.
612 }
613 }
614 }
615 }
616 }
617 }
618
619 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
620 for tool_call in tool_calls {
621 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
622
623 if let Some(tool_id) = tool_call.id.clone() {
624 entry.id = tool_id;
625 }
626
627 if let Some(function) = tool_call.function.as_ref() {
628 if let Some(name) = function.name.clone() {
629 entry.name = name;
630 }
631
632 if let Some(arguments) = function.arguments.clone() {
633 entry.arguments.push_str(&arguments);
634 }
635 }
636
637 if !entry.id.is_empty() && !entry.name.is_empty() {
638 if let Ok(input) = serde_json::from_str::<serde_json::Value>(
639 &partial_json_fixer::fix_json(&entry.arguments),
640 ) {
641 events.push(Ok(LanguageModelCompletionEvent::ToolUse(
642 LanguageModelToolUse {
643 id: entry.id.clone().into(),
644 name: entry.name.as_str().into(),
645 is_input_complete: false,
646 input,
647 raw_input: entry.arguments.clone(),
648 thought_signature: None,
649 },
650 )));
651 }
652 }
653 }
654 }
655
656 if let Some(usage) = event.usage {
657 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
658 input_tokens: usage.prompt_tokens,
659 output_tokens: usage.completion_tokens,
660 cache_creation_input_tokens: 0,
661 cache_read_input_tokens: 0,
662 })));
663 }
664
665 if let Some(finish_reason) = choice.finish_reason.as_deref() {
666 match finish_reason {
667 "stop" => {
668 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
669 }
670 "tool_calls" => {
671 events.extend(self.process_tool_calls());
672 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
673 }
674 unexpected => {
675 log::error!("Unexpected Mistral stop_reason: {unexpected:?}");
676 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
677 }
678 }
679 }
680
681 events
682 }
683
684 fn process_tool_calls(
685 &mut self,
686 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
687 let mut results = Vec::new();
688
689 for (_, tool_call) in self.tool_calls_by_index.drain() {
690 if tool_call.id.is_empty() || tool_call.name.is_empty() {
691 results.push(Err(LanguageModelCompletionError::from(anyhow!(
692 "Received incomplete tool call: missing id or name"
693 ))));
694 continue;
695 }
696
697 match parse_tool_arguments(&tool_call.arguments) {
698 Ok(input) => results.push(Ok(LanguageModelCompletionEvent::ToolUse(
699 LanguageModelToolUse {
700 id: tool_call.id.into(),
701 name: tool_call.name.into(),
702 is_input_complete: true,
703 input,
704 raw_input: tool_call.arguments,
705 thought_signature: None,
706 },
707 ))),
708 Err(error) => {
709 results.push(Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
710 id: tool_call.id.into(),
711 tool_name: tool_call.name.into(),
712 raw_input: tool_call.arguments.into(),
713 json_parse_error: error.to_string(),
714 }))
715 }
716 }
717 }
718
719 results
720 }
721}
722
723#[derive(Default)]
724struct RawToolCall {
725 id: String,
726 name: String,
727 arguments: String,
728}
729
730struct ConfigurationView {
731 api_key_editor: Entity<InputField>,
732 state: Entity<State>,
733 load_credentials_task: Option<Task<()>>,
734}
735
736impl ConfigurationView {
737 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
738 let api_key_editor =
739 cx.new(|cx| InputField::new(window, cx, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
740
741 cx.observe(&state, |_, _, cx| {
742 cx.notify();
743 })
744 .detach();
745
746 let load_credentials_task = Some(cx.spawn_in(window, {
747 let state = state.clone();
748 async move |this, cx| {
749 if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
750 // We don't log an error, because "not signed in" is also an error.
751 let _ = task.await;
752 }
753
754 this.update(cx, |this, cx| {
755 this.load_credentials_task = None;
756 cx.notify();
757 })
758 .log_err();
759 }
760 }));
761
762 Self {
763 api_key_editor,
764 state,
765 load_credentials_task,
766 }
767 }
768
769 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
770 let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
771 if api_key.is_empty() {
772 return;
773 }
774
775 // url changes can cause the editor to be displayed again
776 self.api_key_editor
777 .update(cx, |editor, cx| editor.set_text("", window, cx));
778
779 let state = self.state.clone();
780 cx.spawn_in(window, async move |_, cx| {
781 state
782 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
783 .await
784 })
785 .detach_and_log_err(cx);
786 }
787
788 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
789 self.api_key_editor
790 .update(cx, |editor, cx| editor.set_text("", window, cx));
791
792 let state = self.state.clone();
793 cx.spawn_in(window, async move |_, cx| {
794 state
795 .update(cx, |state, cx| state.set_api_key(None, cx))
796 .await
797 })
798 .detach_and_log_err(cx);
799 }
800
801 fn should_render_api_key_editor(&self, cx: &mut Context<Self>) -> bool {
802 !self.state.read(cx).is_authenticated()
803 }
804}
805
806impl Render for ConfigurationView {
807 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
808 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
809 let configured_card_label = if env_var_set {
810 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
811 } else {
812 let api_url = MistralLanguageModelProvider::api_url(cx);
813 if api_url == MISTRAL_API_URL {
814 "API key configured".to_string()
815 } else {
816 format!("API key configured for {}", api_url)
817 }
818 };
819
820 if self.load_credentials_task.is_some() {
821 div().child(Label::new("Loading credentials...")).into_any()
822 } else if self.should_render_api_key_editor(cx) {
823 v_flex()
824 .size_full()
825 .on_action(cx.listener(Self::save_api_key))
826 .child(Label::new("To use Zed's agent with Mistral, you need to add an API key. Follow these steps:"))
827 .child(
828 List::new()
829 .child(
830 ListBulletItem::new("")
831 .child(Label::new("Create one by visiting"))
832 .child(ButtonLink::new("Mistral's console", "https://console.mistral.ai/api-keys"))
833 )
834 .child(
835 ListBulletItem::new("Ensure your Mistral account has credits")
836 )
837 .child(
838 ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
839 ),
840 )
841 .child(self.api_key_editor.clone())
842 .child(
843 Label::new(
844 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
845 )
846 .size(LabelSize::Small).color(Color::Muted),
847 )
848 .into_any()
849 } else {
850 v_flex()
851 .size_full()
852 .gap_1()
853 .child(
854 ConfiguredApiCard::new(configured_card_label)
855 .disabled(env_var_set)
856 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
857 .when(env_var_set, |this| {
858 this.tooltip_label(format!(
859 "To reset your API key, \
860 unset the {API_KEY_ENV_VAR_NAME} environment variable."
861 ))
862 }),
863 )
864 .into_any()
865 }
866 }
867}
868
869#[cfg(test)]
870mod tests {
871 use super::*;
872 use language_model::{LanguageModelImage, LanguageModelRequestMessage, MessageContent};
873
874 #[test]
875 fn test_into_mistral_basic_conversion() {
876 let request = LanguageModelRequest {
877 messages: vec![
878 LanguageModelRequestMessage {
879 role: Role::System,
880 content: vec![MessageContent::Text("System prompt".into())],
881 cache: false,
882 reasoning_details: None,
883 },
884 LanguageModelRequestMessage {
885 role: Role::User,
886 content: vec![MessageContent::Text("Hello".into())],
887 cache: false,
888 reasoning_details: None,
889 },
890 // should skip empty assistant messages
891 LanguageModelRequestMessage {
892 role: Role::Assistant,
893 content: vec![MessageContent::Text("".into())],
894 cache: false,
895 reasoning_details: None,
896 },
897 ],
898 temperature: Some(0.5),
899 tools: vec![],
900 tool_choice: None,
901 thread_id: Some("abcdef".into()),
902 prompt_id: None,
903 intent: None,
904 stop: vec![],
905 thinking_allowed: true,
906 thinking_effort: None,
907 speed: Default::default(),
908 };
909
910 let (mistral_request, affinity) =
911 into_mistral(request, mistral::Model::MistralSmallLatest, None);
912
913 assert_eq!(mistral_request.model, "mistral-small-latest");
914 assert_eq!(mistral_request.temperature, Some(0.5));
915 assert_eq!(mistral_request.messages.len(), 2);
916 assert!(mistral_request.stream);
917 assert_eq!(affinity, Some("abcdef".into()));
918 }
919
920 #[test]
921 fn test_into_mistral_with_image() {
922 let request = LanguageModelRequest {
923 messages: vec![LanguageModelRequestMessage {
924 role: Role::User,
925 content: vec![
926 MessageContent::Text("What's in this image?".into()),
927 MessageContent::Image(LanguageModelImage {
928 source: "base64data".into(),
929 size: None,
930 }),
931 ],
932 cache: false,
933 reasoning_details: None,
934 }],
935 tools: vec![],
936 tool_choice: None,
937 temperature: None,
938 thread_id: None,
939 prompt_id: None,
940 intent: None,
941 stop: vec![],
942 thinking_allowed: true,
943 thinking_effort: None,
944 speed: None,
945 };
946
947 let (mistral_request, _) = into_mistral(request, mistral::Model::Pixtral12BLatest, None);
948
949 assert_eq!(mistral_request.messages.len(), 1);
950 assert!(matches!(
951 &mistral_request.messages[0],
952 mistral::RequestMessage::User {
953 content: mistral::MessageContent::Multipart { .. }
954 }
955 ));
956
957 if let mistral::RequestMessage::User {
958 content: mistral::MessageContent::Multipart { content },
959 } = &mistral_request.messages[0]
960 {
961 assert_eq!(content.len(), 2);
962 assert!(matches!(
963 &content[0],
964 mistral::MessagePart::Text { text } if text == "What's in this image?"
965 ));
966 assert!(matches!(
967 &content[1],
968 mistral::MessagePart::ImageUrl { image_url } if image_url.starts_with("data:image/png;base64,")
969 ));
970 }
971 }
972}