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