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