1use anyhow::{Context as _, Result, anyhow};
2use collections::BTreeMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{FutureExt, StreamExt, future::BoxFuture};
6use gpui::{
7 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
8};
9use http_client::HttpClient;
10use language_model::{
11 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
12 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
13 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
14 LanguageModelToolChoice, RateLimiter, Role,
15};
16
17use futures::stream::BoxStream;
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize};
20use settings::{Settings, SettingsStore};
21use std::sync::Arc;
22use strum::IntoEnumIterator;
23use theme::ThemeSettings;
24use ui::{Icon, IconName, List, Tooltip, prelude::*};
25use util::ResultExt;
26
27use crate::{AllLanguageModelSettings, ui::InstructionListItem};
28
29const PROVIDER_ID: &str = "mistral";
30const PROVIDER_NAME: &str = "Mistral";
31
32#[derive(Default, Clone, Debug, PartialEq)]
33pub struct MistralSettings {
34 pub api_url: String,
35 pub available_models: Vec<AvailableModel>,
36 pub needs_setting_migration: bool,
37}
38
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
40pub struct AvailableModel {
41 pub name: String,
42 pub display_name: Option<String>,
43 pub max_tokens: usize,
44 pub max_output_tokens: Option<u32>,
45 pub max_completion_tokens: Option<u32>,
46}
47
48pub struct MistralLanguageModelProvider {
49 http_client: Arc<dyn HttpClient>,
50 state: gpui::Entity<State>,
51}
52
53pub struct State {
54 api_key: Option<String>,
55 api_key_from_env: bool,
56 _subscription: Subscription,
57}
58
59const MISTRAL_API_KEY_VAR: &str = "MISTRAL_API_KEY";
60
61impl State {
62 fn is_authenticated(&self) -> bool {
63 self.api_key.is_some()
64 }
65
66 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
67 let credentials_provider = <dyn CredentialsProvider>::global(cx);
68 let api_url = AllLanguageModelSettings::get_global(cx)
69 .mistral
70 .api_url
71 .clone();
72 cx.spawn(async move |this, cx| {
73 credentials_provider
74 .delete_credentials(&api_url, &cx)
75 .await
76 .log_err();
77 this.update(cx, |this, cx| {
78 this.api_key = None;
79 this.api_key_from_env = false;
80 cx.notify();
81 })
82 })
83 }
84
85 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
86 let credentials_provider = <dyn CredentialsProvider>::global(cx);
87 let api_url = AllLanguageModelSettings::get_global(cx)
88 .mistral
89 .api_url
90 .clone();
91 cx.spawn(async move |this, cx| {
92 credentials_provider
93 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
94 .await?;
95 this.update(cx, |this, cx| {
96 this.api_key = Some(api_key);
97 cx.notify();
98 })
99 })
100 }
101
102 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
103 if self.is_authenticated() {
104 return Task::ready(Ok(()));
105 }
106
107 let credentials_provider = <dyn CredentialsProvider>::global(cx);
108 let api_url = AllLanguageModelSettings::get_global(cx)
109 .mistral
110 .api_url
111 .clone();
112 cx.spawn(async move |this, cx| {
113 let (api_key, from_env) = if let Ok(api_key) = std::env::var(MISTRAL_API_KEY_VAR) {
114 (api_key, true)
115 } else {
116 let (_, api_key) = credentials_provider
117 .read_credentials(&api_url, &cx)
118 .await?
119 .ok_or(AuthenticateError::CredentialsNotFound)?;
120 (
121 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
122 false,
123 )
124 };
125 this.update(cx, |this, cx| {
126 this.api_key = Some(api_key);
127 this.api_key_from_env = from_env;
128 cx.notify();
129 })?;
130
131 Ok(())
132 })
133 }
134}
135
136impl MistralLanguageModelProvider {
137 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
138 let state = cx.new(|cx| State {
139 api_key: None,
140 api_key_from_env: false,
141 _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
142 cx.notify();
143 }),
144 });
145
146 Self { http_client, state }
147 }
148
149 fn create_language_model(&self, model: mistral::Model) -> Arc<dyn LanguageModel> {
150 Arc::new(MistralLanguageModel {
151 id: LanguageModelId::from(model.id().to_string()),
152 model,
153 state: self.state.clone(),
154 http_client: self.http_client.clone(),
155 request_limiter: RateLimiter::new(4),
156 })
157 }
158}
159
160impl LanguageModelProviderState for MistralLanguageModelProvider {
161 type ObservableEntity = State;
162
163 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
164 Some(self.state.clone())
165 }
166}
167
168impl LanguageModelProvider for MistralLanguageModelProvider {
169 fn id(&self) -> LanguageModelProviderId {
170 LanguageModelProviderId(PROVIDER_ID.into())
171 }
172
173 fn name(&self) -> LanguageModelProviderName {
174 LanguageModelProviderName(PROVIDER_NAME.into())
175 }
176
177 fn icon(&self) -> IconName {
178 IconName::AiMistral
179 }
180
181 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
182 Some(self.create_language_model(mistral::Model::default()))
183 }
184
185 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
186 Some(self.create_language_model(mistral::Model::default_fast()))
187 }
188
189 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
190 let mut models = BTreeMap::default();
191
192 // Add base models from mistral::Model::iter()
193 for model in mistral::Model::iter() {
194 if !matches!(model, mistral::Model::Custom { .. }) {
195 models.insert(model.id().to_string(), model);
196 }
197 }
198
199 // Override with available models from settings
200 for model in &AllLanguageModelSettings::get_global(cx)
201 .mistral
202 .available_models
203 {
204 models.insert(
205 model.name.clone(),
206 mistral::Model::Custom {
207 name: model.name.clone(),
208 display_name: model.display_name.clone(),
209 max_tokens: model.max_tokens,
210 max_output_tokens: model.max_output_tokens,
211 max_completion_tokens: model.max_completion_tokens,
212 },
213 );
214 }
215
216 models
217 .into_values()
218 .map(|model| {
219 Arc::new(MistralLanguageModel {
220 id: LanguageModelId::from(model.id().to_string()),
221 model,
222 state: self.state.clone(),
223 http_client: self.http_client.clone(),
224 request_limiter: RateLimiter::new(4),
225 }) as Arc<dyn LanguageModel>
226 })
227 .collect()
228 }
229
230 fn is_authenticated(&self, cx: &App) -> bool {
231 self.state.read(cx).is_authenticated()
232 }
233
234 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
235 self.state.update(cx, |state, cx| state.authenticate(cx))
236 }
237
238 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
239 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
240 .into()
241 }
242
243 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
244 self.state.update(cx, |state, cx| state.reset_api_key(cx))
245 }
246}
247
248pub struct MistralLanguageModel {
249 id: LanguageModelId,
250 model: mistral::Model,
251 state: gpui::Entity<State>,
252 http_client: Arc<dyn HttpClient>,
253 request_limiter: RateLimiter,
254}
255
256impl MistralLanguageModel {
257 fn stream_completion(
258 &self,
259 request: mistral::Request,
260 cx: &AsyncApp,
261 ) -> BoxFuture<
262 'static,
263 Result<futures::stream::BoxStream<'static, Result<mistral::StreamResponse>>>,
264 > {
265 let http_client = self.http_client.clone();
266 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
267 let settings = &AllLanguageModelSettings::get_global(cx).mistral;
268 (state.api_key.clone(), settings.api_url.clone())
269 }) else {
270 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
271 };
272
273 let future = self.request_limiter.stream(async move {
274 let api_key = api_key.ok_or_else(|| anyhow!("Missing Mistral API Key"))?;
275 let request =
276 mistral::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
277 let response = request.await?;
278 Ok(response)
279 });
280
281 async move { Ok(future.await?.boxed()) }.boxed()
282 }
283}
284
285impl LanguageModel for MistralLanguageModel {
286 fn id(&self) -> LanguageModelId {
287 self.id.clone()
288 }
289
290 fn name(&self) -> LanguageModelName {
291 LanguageModelName::from(self.model.display_name().to_string())
292 }
293
294 fn provider_id(&self) -> LanguageModelProviderId {
295 LanguageModelProviderId(PROVIDER_ID.into())
296 }
297
298 fn provider_name(&self) -> LanguageModelProviderName {
299 LanguageModelProviderName(PROVIDER_NAME.into())
300 }
301
302 fn supports_tools(&self) -> bool {
303 false
304 }
305
306 fn supports_images(&self) -> bool {
307 false
308 }
309
310 fn supports_tool_choice(&self, _choice: LanguageModelToolChoice) -> bool {
311 false
312 }
313
314 fn telemetry_id(&self) -> String {
315 format!("mistral/{}", self.model.id())
316 }
317
318 fn max_token_count(&self) -> usize {
319 self.model.max_token_count()
320 }
321
322 fn max_output_tokens(&self) -> Option<u32> {
323 self.model.max_output_tokens()
324 }
325
326 fn count_tokens(
327 &self,
328 request: LanguageModelRequest,
329 cx: &App,
330 ) -> BoxFuture<'static, Result<usize>> {
331 cx.background_spawn(async move {
332 let messages = request
333 .messages
334 .into_iter()
335 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
336 role: match message.role {
337 Role::User => "user".into(),
338 Role::Assistant => "assistant".into(),
339 Role::System => "system".into(),
340 },
341 content: Some(message.string_contents()),
342 name: None,
343 function_call: None,
344 })
345 .collect::<Vec<_>>();
346
347 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
348 })
349 .boxed()
350 }
351
352 fn stream_completion(
353 &self,
354 request: LanguageModelRequest,
355 cx: &AsyncApp,
356 ) -> BoxFuture<
357 'static,
358 Result<
359 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
360 >,
361 > {
362 let request = into_mistral(
363 request,
364 self.model.id().to_string(),
365 self.max_output_tokens(),
366 );
367 let stream = self.stream_completion(request, cx);
368
369 async move {
370 let stream = stream.await?;
371 Ok(stream
372 .map(|result| {
373 result
374 .and_then(|response| {
375 response
376 .choices
377 .first()
378 .ok_or_else(|| anyhow!("Empty response"))
379 .map(|choice| {
380 choice
381 .delta
382 .content
383 .clone()
384 .unwrap_or_default()
385 .map(LanguageModelCompletionEvent::Text)
386 })
387 })
388 .map_err(LanguageModelCompletionError::Other)
389 })
390 .boxed())
391 }
392 .boxed()
393 }
394}
395
396pub fn into_mistral(
397 request: LanguageModelRequest,
398 model: String,
399 max_output_tokens: Option<u32>,
400) -> mistral::Request {
401 let len = request.messages.len();
402 let merged_messages =
403 request
404 .messages
405 .into_iter()
406 .fold(Vec::with_capacity(len), |mut acc, msg| {
407 let role = msg.role;
408 let content = msg.string_contents();
409
410 acc.push(match role {
411 Role::User => mistral::RequestMessage::User { content },
412 Role::Assistant => mistral::RequestMessage::Assistant {
413 content: Some(content),
414 tool_calls: Vec::new(),
415 },
416 Role::System => mistral::RequestMessage::System { content },
417 });
418 acc
419 });
420
421 mistral::Request {
422 model,
423 messages: merged_messages,
424 stream: true,
425 max_tokens: max_output_tokens,
426 temperature: request.temperature,
427 response_format: None,
428 tools: request
429 .tools
430 .into_iter()
431 .map(|tool| mistral::ToolDefinition::Function {
432 function: mistral::FunctionDefinition {
433 name: tool.name,
434 description: Some(tool.description),
435 parameters: Some(tool.input_schema),
436 },
437 })
438 .collect(),
439 }
440}
441
442struct ConfigurationView {
443 api_key_editor: Entity<Editor>,
444 state: gpui::Entity<State>,
445 load_credentials_task: Option<Task<()>>,
446}
447
448impl ConfigurationView {
449 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
450 let api_key_editor = cx.new(|cx| {
451 let mut editor = Editor::single_line(window, cx);
452 editor.set_placeholder_text("0aBCDEFGhIjKLmNOpqrSTUVwxyzabCDE1f2", cx);
453 editor
454 });
455
456 cx.observe(&state, |_, _, cx| {
457 cx.notify();
458 })
459 .detach();
460
461 let load_credentials_task = Some(cx.spawn_in(window, {
462 let state = state.clone();
463 async move |this, cx| {
464 if let Some(task) = state
465 .update(cx, |state, cx| state.authenticate(cx))
466 .log_err()
467 {
468 // We don't log an error, because "not signed in" is also an error.
469 let _ = task.await;
470 }
471
472 this.update(cx, |this, cx| {
473 this.load_credentials_task = None;
474 cx.notify();
475 })
476 .log_err();
477 }
478 }));
479
480 Self {
481 api_key_editor,
482 state,
483 load_credentials_task,
484 }
485 }
486
487 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
488 let api_key = self.api_key_editor.read(cx).text(cx);
489 if api_key.is_empty() {
490 return;
491 }
492
493 let state = self.state.clone();
494 cx.spawn_in(window, async move |_, cx| {
495 state
496 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
497 .await
498 })
499 .detach_and_log_err(cx);
500
501 cx.notify();
502 }
503
504 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
505 self.api_key_editor
506 .update(cx, |editor, cx| editor.set_text("", window, cx));
507
508 let state = self.state.clone();
509 cx.spawn_in(window, async move |_, cx| {
510 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
511 })
512 .detach_and_log_err(cx);
513
514 cx.notify();
515 }
516
517 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
518 let settings = ThemeSettings::get_global(cx);
519 let text_style = TextStyle {
520 color: cx.theme().colors().text,
521 font_family: settings.ui_font.family.clone(),
522 font_features: settings.ui_font.features.clone(),
523 font_fallbacks: settings.ui_font.fallbacks.clone(),
524 font_size: rems(0.875).into(),
525 font_weight: settings.ui_font.weight,
526 font_style: FontStyle::Normal,
527 line_height: relative(1.3),
528 white_space: WhiteSpace::Normal,
529 ..Default::default()
530 };
531 EditorElement::new(
532 &self.api_key_editor,
533 EditorStyle {
534 background: cx.theme().colors().editor_background,
535 local_player: cx.theme().players().local(),
536 text: text_style,
537 ..Default::default()
538 },
539 )
540 }
541
542 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
543 !self.state.read(cx).is_authenticated()
544 }
545}
546
547impl Render for ConfigurationView {
548 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
549 let env_var_set = self.state.read(cx).api_key_from_env;
550
551 if self.load_credentials_task.is_some() {
552 div().child(Label::new("Loading credentials...")).into_any()
553 } else if self.should_render_editor(cx) {
554 v_flex()
555 .size_full()
556 .on_action(cx.listener(Self::save_api_key))
557 .child(Label::new("To use Zed's assistant with Mistral, you need to add an API key. Follow these steps:"))
558 .child(
559 List::new()
560 .child(InstructionListItem::new(
561 "Create one by visiting",
562 Some("Mistral's console"),
563 Some("https://console.mistral.ai/api-keys"),
564 ))
565 .child(InstructionListItem::text_only(
566 "Ensure your Mistral account has credits",
567 ))
568 .child(InstructionListItem::text_only(
569 "Paste your API key below and hit enter to start using the assistant",
570 )),
571 )
572 .child(
573 h_flex()
574 .w_full()
575 .my_2()
576 .px_2()
577 .py_1()
578 .bg(cx.theme().colors().editor_background)
579 .border_1()
580 .border_color(cx.theme().colors().border)
581 .rounded_sm()
582 .child(self.render_api_key_editor(cx)),
583 )
584 .child(
585 Label::new(
586 format!("You can also assign the {MISTRAL_API_KEY_VAR} environment variable and restart Zed."),
587 )
588 .size(LabelSize::Small).color(Color::Muted),
589 )
590 .into_any()
591 } else {
592 h_flex()
593 .mt_1()
594 .p_1()
595 .justify_between()
596 .rounded_md()
597 .border_1()
598 .border_color(cx.theme().colors().border)
599 .bg(cx.theme().colors().background)
600 .child(
601 h_flex()
602 .gap_1()
603 .child(Icon::new(IconName::Check).color(Color::Success))
604 .child(Label::new(if env_var_set {
605 format!("API key set in {MISTRAL_API_KEY_VAR} environment variable.")
606 } else {
607 "API key configured.".to_string()
608 })),
609 )
610 .child(
611 Button::new("reset-key", "Reset Key")
612 .label_size(LabelSize::Small)
613 .icon(Some(IconName::Trash))
614 .icon_size(IconSize::Small)
615 .icon_position(IconPosition::Start)
616 .disabled(env_var_set)
617 .when(env_var_set, |this| {
618 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {MISTRAL_API_KEY_VAR} environment variable.")))
619 })
620 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
621 )
622 .into_any()
623 }
624 }
625}