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