mistral.rs

  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_tool_choice(&self, _choice: LanguageModelToolChoice) -> bool {
307        false
308    }
309
310    fn telemetry_id(&self) -> String {
311        format!("mistral/{}", self.model.id())
312    }
313
314    fn max_token_count(&self) -> usize {
315        self.model.max_token_count()
316    }
317
318    fn max_output_tokens(&self) -> Option<u32> {
319        self.model.max_output_tokens()
320    }
321
322    fn count_tokens(
323        &self,
324        request: LanguageModelRequest,
325        cx: &App,
326    ) -> BoxFuture<'static, Result<usize>> {
327        cx.background_spawn(async move {
328            let messages = request
329                .messages
330                .into_iter()
331                .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
332                    role: match message.role {
333                        Role::User => "user".into(),
334                        Role::Assistant => "assistant".into(),
335                        Role::System => "system".into(),
336                    },
337                    content: Some(message.string_contents()),
338                    name: None,
339                    function_call: None,
340                })
341                .collect::<Vec<_>>();
342
343            tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
344        })
345        .boxed()
346    }
347
348    fn stream_completion(
349        &self,
350        request: LanguageModelRequest,
351        cx: &AsyncApp,
352    ) -> BoxFuture<
353        'static,
354        Result<
355            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
356        >,
357    > {
358        let request = into_mistral(
359            request,
360            self.model.id().to_string(),
361            self.max_output_tokens(),
362        );
363        let stream = self.stream_completion(request, cx);
364
365        async move {
366            let stream = stream.await?;
367            Ok(stream
368                .map(|result| {
369                    result
370                        .and_then(|response| {
371                            response
372                                .choices
373                                .first()
374                                .ok_or_else(|| anyhow!("Empty response"))
375                                .map(|choice| {
376                                    choice
377                                        .delta
378                                        .content
379                                        .clone()
380                                        .unwrap_or_default()
381                                        .map(LanguageModelCompletionEvent::Text)
382                                })
383                        })
384                        .map_err(LanguageModelCompletionError::Other)
385                })
386                .boxed())
387        }
388        .boxed()
389    }
390}
391
392pub fn into_mistral(
393    request: LanguageModelRequest,
394    model: String,
395    max_output_tokens: Option<u32>,
396) -> mistral::Request {
397    let len = request.messages.len();
398    let merged_messages =
399        request
400            .messages
401            .into_iter()
402            .fold(Vec::with_capacity(len), |mut acc, msg| {
403                let role = msg.role;
404                let content = msg.string_contents();
405
406                acc.push(match role {
407                    Role::User => mistral::RequestMessage::User { content },
408                    Role::Assistant => mistral::RequestMessage::Assistant {
409                        content: Some(content),
410                        tool_calls: Vec::new(),
411                    },
412                    Role::System => mistral::RequestMessage::System { content },
413                });
414                acc
415            });
416
417    mistral::Request {
418        model,
419        messages: merged_messages,
420        stream: true,
421        max_tokens: max_output_tokens,
422        temperature: request.temperature,
423        response_format: None,
424        tools: request
425            .tools
426            .into_iter()
427            .map(|tool| mistral::ToolDefinition::Function {
428                function: mistral::FunctionDefinition {
429                    name: tool.name,
430                    description: Some(tool.description),
431                    parameters: Some(tool.input_schema),
432                },
433            })
434            .collect(),
435    }
436}
437
438struct ConfigurationView {
439    api_key_editor: Entity<Editor>,
440    state: gpui::Entity<State>,
441    load_credentials_task: Option<Task<()>>,
442}
443
444impl ConfigurationView {
445    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
446        let api_key_editor = cx.new(|cx| {
447            let mut editor = Editor::single_line(window, cx);
448            editor.set_placeholder_text("0aBCDEFGhIjKLmNOpqrSTUVwxyzabCDE1f2", cx);
449            editor
450        });
451
452        cx.observe(&state, |_, _, cx| {
453            cx.notify();
454        })
455        .detach();
456
457        let load_credentials_task = Some(cx.spawn_in(window, {
458            let state = state.clone();
459            async move |this, cx| {
460                if let Some(task) = state
461                    .update(cx, |state, cx| state.authenticate(cx))
462                    .log_err()
463                {
464                    // We don't log an error, because "not signed in" is also an error.
465                    let _ = task.await;
466                }
467
468                this.update(cx, |this, cx| {
469                    this.load_credentials_task = None;
470                    cx.notify();
471                })
472                .log_err();
473            }
474        }));
475
476        Self {
477            api_key_editor,
478            state,
479            load_credentials_task,
480        }
481    }
482
483    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
484        let api_key = self.api_key_editor.read(cx).text(cx);
485        if api_key.is_empty() {
486            return;
487        }
488
489        let state = self.state.clone();
490        cx.spawn_in(window, async move |_, cx| {
491            state
492                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
493                .await
494        })
495        .detach_and_log_err(cx);
496
497        cx.notify();
498    }
499
500    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
501        self.api_key_editor
502            .update(cx, |editor, cx| editor.set_text("", window, cx));
503
504        let state = self.state.clone();
505        cx.spawn_in(window, async move |_, cx| {
506            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
507        })
508        .detach_and_log_err(cx);
509
510        cx.notify();
511    }
512
513    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
514        let settings = ThemeSettings::get_global(cx);
515        let text_style = TextStyle {
516            color: cx.theme().colors().text,
517            font_family: settings.ui_font.family.clone(),
518            font_features: settings.ui_font.features.clone(),
519            font_fallbacks: settings.ui_font.fallbacks.clone(),
520            font_size: rems(0.875).into(),
521            font_weight: settings.ui_font.weight,
522            font_style: FontStyle::Normal,
523            line_height: relative(1.3),
524            white_space: WhiteSpace::Normal,
525            ..Default::default()
526        };
527        EditorElement::new(
528            &self.api_key_editor,
529            EditorStyle {
530                background: cx.theme().colors().editor_background,
531                local_player: cx.theme().players().local(),
532                text: text_style,
533                ..Default::default()
534            },
535        )
536    }
537
538    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
539        !self.state.read(cx).is_authenticated()
540    }
541}
542
543impl Render for ConfigurationView {
544    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
545        let env_var_set = self.state.read(cx).api_key_from_env;
546
547        if self.load_credentials_task.is_some() {
548            div().child(Label::new("Loading credentials...")).into_any()
549        } else if self.should_render_editor(cx) {
550            v_flex()
551                .size_full()
552                .on_action(cx.listener(Self::save_api_key))
553                .child(Label::new("To use Zed's assistant with Mistral, you need to add an API key. Follow these steps:"))
554                .child(
555                    List::new()
556                        .child(InstructionListItem::new(
557                            "Create one by visiting",
558                            Some("Mistral's console"),
559                            Some("https://console.mistral.ai/api-keys"),
560                        ))
561                        .child(InstructionListItem::text_only(
562                            "Ensure your Mistral account has credits",
563                        ))
564                        .child(InstructionListItem::text_only(
565                            "Paste your API key below and hit enter to start using the assistant",
566                        )),
567                )
568                .child(
569                    h_flex()
570                        .w_full()
571                        .my_2()
572                        .px_2()
573                        .py_1()
574                        .bg(cx.theme().colors().editor_background)
575                        .border_1()
576                        .border_color(cx.theme().colors().border)
577                        .rounded_sm()
578                        .child(self.render_api_key_editor(cx)),
579                )
580                .child(
581                    Label::new(
582                        format!("You can also assign the {MISTRAL_API_KEY_VAR} environment variable and restart Zed."),
583                    )
584                    .size(LabelSize::Small).color(Color::Muted),
585                )
586                .into_any()
587        } else {
588            h_flex()
589                .mt_1()
590                .p_1()
591                .justify_between()
592                .rounded_md()
593                .border_1()
594                .border_color(cx.theme().colors().border)
595                .bg(cx.theme().colors().background)
596                .child(
597                    h_flex()
598                        .gap_1()
599                        .child(Icon::new(IconName::Check).color(Color::Success))
600                        .child(Label::new(if env_var_set {
601                            format!("API key set in {MISTRAL_API_KEY_VAR} environment variable.")
602                        } else {
603                            "API key configured.".to_string()
604                        })),
605                )
606                .child(
607                    Button::new("reset-key", "Reset Key")
608                        .label_size(LabelSize::Small)
609                        .icon(Some(IconName::Trash))
610                        .icon_size(IconSize::Small)
611                        .icon_position(IconPosition::Start)
612                        .disabled(env_var_set)
613                        .when(env_var_set, |this| {
614                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {MISTRAL_API_KEY_VAR} environment variable.")))
615                        })
616                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
617                )
618                .into_any()
619        }
620    }
621}