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