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