mistral.rs

  1use anyhow::{anyhow, Context as _, Result};
  2use collections::BTreeMap;
  3use credentials_provider::CredentialsProvider;
  4use editor::{Editor, EditorElement, EditorStyle};
  5use futures::{future::BoxFuture, FutureExt, StreamExt};
  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::{prelude::*, Icon, IconName, Tooltip};
 24use util::ResultExt;
 25
 26use crate::AllLanguageModelSettings;
 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(|this, mut cx| async move {
 72            credentials_provider
 73                .delete_credentials(&api_url, &cx)
 74                .await
 75                .log_err();
 76            this.update(&mut 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(|this, mut cx| async move {
 91            credentials_provider
 92                .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
 93                .await?;
 94            this.update(&mut 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(|this, mut cx| async move {
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(&mut 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
149impl LanguageModelProviderState for MistralLanguageModelProvider {
150    type ObservableEntity = State;
151
152    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
153        Some(self.state.clone())
154    }
155}
156
157impl LanguageModelProvider for MistralLanguageModelProvider {
158    fn id(&self) -> LanguageModelProviderId {
159        LanguageModelProviderId(PROVIDER_ID.into())
160    }
161
162    fn name(&self) -> LanguageModelProviderName {
163        LanguageModelProviderName(PROVIDER_NAME.into())
164    }
165
166    fn icon(&self) -> IconName {
167        IconName::AiMistral
168    }
169
170    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
171        let mut models = BTreeMap::default();
172
173        // Add base models from mistral::Model::iter()
174        for model in mistral::Model::iter() {
175            if !matches!(model, mistral::Model::Custom { .. }) {
176                models.insert(model.id().to_string(), model);
177            }
178        }
179
180        // Override with available models from settings
181        for model in &AllLanguageModelSettings::get_global(cx)
182            .mistral
183            .available_models
184        {
185            models.insert(
186                model.name.clone(),
187                mistral::Model::Custom {
188                    name: model.name.clone(),
189                    display_name: model.display_name.clone(),
190                    max_tokens: model.max_tokens,
191                    max_output_tokens: model.max_output_tokens,
192                    max_completion_tokens: model.max_completion_tokens,
193                },
194            );
195        }
196
197        models
198            .into_values()
199            .map(|model| {
200                Arc::new(MistralLanguageModel {
201                    id: LanguageModelId::from(model.id().to_string()),
202                    model,
203                    state: self.state.clone(),
204                    http_client: self.http_client.clone(),
205                    request_limiter: RateLimiter::new(4),
206                }) as Arc<dyn LanguageModel>
207            })
208            .collect()
209    }
210
211    fn is_authenticated(&self, cx: &App) -> bool {
212        self.state.read(cx).is_authenticated()
213    }
214
215    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
216        self.state.update(cx, |state, cx| state.authenticate(cx))
217    }
218
219    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
220        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
221            .into()
222    }
223
224    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
225        self.state.update(cx, |state, cx| state.reset_api_key(cx))
226    }
227}
228
229pub struct MistralLanguageModel {
230    id: LanguageModelId,
231    model: mistral::Model,
232    state: gpui::Entity<State>,
233    http_client: Arc<dyn HttpClient>,
234    request_limiter: RateLimiter,
235}
236
237impl MistralLanguageModel {
238    fn stream_completion(
239        &self,
240        request: mistral::Request,
241        cx: &AsyncApp,
242    ) -> BoxFuture<
243        'static,
244        Result<futures::stream::BoxStream<'static, Result<mistral::StreamResponse>>>,
245    > {
246        let http_client = self.http_client.clone();
247        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
248            let settings = &AllLanguageModelSettings::get_global(cx).mistral;
249            (state.api_key.clone(), settings.api_url.clone())
250        }) else {
251            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
252        };
253
254        let future = self.request_limiter.stream(async move {
255            let api_key = api_key.ok_or_else(|| anyhow!("Missing Mistral API Key"))?;
256            let request =
257                mistral::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
258            let response = request.await?;
259            Ok(response)
260        });
261
262        async move { Ok(future.await?.boxed()) }.boxed()
263    }
264}
265
266impl LanguageModel for MistralLanguageModel {
267    fn id(&self) -> LanguageModelId {
268        self.id.clone()
269    }
270
271    fn name(&self) -> LanguageModelName {
272        LanguageModelName::from(self.model.display_name().to_string())
273    }
274
275    fn provider_id(&self) -> LanguageModelProviderId {
276        LanguageModelProviderId(PROVIDER_ID.into())
277    }
278
279    fn provider_name(&self) -> LanguageModelProviderName {
280        LanguageModelProviderName(PROVIDER_NAME.into())
281    }
282
283    fn telemetry_id(&self) -> String {
284        format!("mistral/{}", self.model.id())
285    }
286
287    fn max_token_count(&self) -> usize {
288        self.model.max_token_count()
289    }
290
291    fn max_output_tokens(&self) -> Option<u32> {
292        self.model.max_output_tokens()
293    }
294
295    fn count_tokens(
296        &self,
297        request: LanguageModelRequest,
298        cx: &App,
299    ) -> BoxFuture<'static, Result<usize>> {
300        cx.background_spawn(async move {
301            let messages = request
302                .messages
303                .into_iter()
304                .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
305                    role: match message.role {
306                        Role::User => "user".into(),
307                        Role::Assistant => "assistant".into(),
308                        Role::System => "system".into(),
309                    },
310                    content: Some(message.string_contents()),
311                    name: None,
312                    function_call: None,
313                })
314                .collect::<Vec<_>>();
315
316            tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
317        })
318        .boxed()
319    }
320
321    fn stream_completion(
322        &self,
323        request: LanguageModelRequest,
324        cx: &AsyncApp,
325    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
326        let request = request.into_mistral(self.model.id().to_string(), self.max_output_tokens());
327        let stream = self.stream_completion(request, cx);
328
329        async move {
330            let stream = stream.await?;
331            Ok(stream
332                .map(|result| {
333                    result.and_then(|response| {
334                        response
335                            .choices
336                            .first()
337                            .ok_or_else(|| anyhow!("Empty response"))
338                            .map(|choice| {
339                                choice
340                                    .delta
341                                    .content
342                                    .clone()
343                                    .unwrap_or_default()
344                                    .map(LanguageModelCompletionEvent::Text)
345                            })
346                    })
347                })
348                .boxed())
349        }
350        .boxed()
351    }
352
353    fn use_any_tool(
354        &self,
355        request: LanguageModelRequest,
356        tool_name: String,
357        tool_description: String,
358        schema: serde_json::Value,
359        cx: &AsyncApp,
360    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
361        let mut request = request.into_mistral(self.model.id().into(), self.max_output_tokens());
362        request.tools = vec![mistral::ToolDefinition::Function {
363            function: mistral::FunctionDefinition {
364                name: tool_name.clone(),
365                description: Some(tool_description),
366                parameters: Some(schema),
367            },
368        }];
369
370        let response = self.stream_completion(request, cx);
371        self.request_limiter
372            .run(async move {
373                let stream = response.await?;
374
375                let tool_args_stream = stream
376                    .filter_map(move |response| async move {
377                        match response {
378                            Ok(response) => {
379                                for choice in response.choices {
380                                    if let Some(tool_calls) = choice.delta.tool_calls {
381                                        for tool_call in tool_calls {
382                                            if let Some(function) = tool_call.function {
383                                                if let Some(args) = function.arguments {
384                                                    return Some(Ok(args));
385                                                }
386                                            }
387                                        }
388                                    }
389                                }
390                                None
391                            }
392                            Err(e) => Some(Err(e)),
393                        }
394                    })
395                    .boxed();
396
397                Ok(tool_args_stream)
398            })
399            .boxed()
400    }
401}
402
403struct ConfigurationView {
404    api_key_editor: Entity<Editor>,
405    state: gpui::Entity<State>,
406    load_credentials_task: Option<Task<()>>,
407}
408
409impl ConfigurationView {
410    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
411        let api_key_editor = cx.new(|cx| {
412            let mut editor = Editor::single_line(window, cx);
413            editor.set_placeholder_text("0aBCDEFGhIjKLmNOpqrSTUVwxyzabCDE1f2", cx);
414            editor
415        });
416
417        cx.observe(&state, |_, _, cx| {
418            cx.notify();
419        })
420        .detach();
421
422        let load_credentials_task = Some(cx.spawn_in(window, {
423            let state = state.clone();
424            |this, mut cx| async move {
425                if let Some(task) = state
426                    .update(&mut cx, |state, cx| state.authenticate(cx))
427                    .log_err()
428                {
429                    // We don't log an error, because "not signed in" is also an error.
430                    let _ = task.await;
431                }
432
433                this.update(&mut cx, |this, cx| {
434                    this.load_credentials_task = None;
435                    cx.notify();
436                })
437                .log_err();
438            }
439        }));
440
441        Self {
442            api_key_editor,
443            state,
444            load_credentials_task,
445        }
446    }
447
448    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
449        let api_key = self.api_key_editor.read(cx).text(cx);
450        if api_key.is_empty() {
451            return;
452        }
453
454        let state = self.state.clone();
455        cx.spawn_in(window, |_, mut cx| async move {
456            state
457                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
458                .await
459        })
460        .detach_and_log_err(cx);
461
462        cx.notify();
463    }
464
465    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
466        self.api_key_editor
467            .update(cx, |editor, cx| editor.set_text("", window, cx));
468
469        let state = self.state.clone();
470        cx.spawn_in(window, |_, mut cx| async move {
471            state
472                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
473                .await
474        })
475        .detach_and_log_err(cx);
476
477        cx.notify();
478    }
479
480    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
481        let settings = ThemeSettings::get_global(cx);
482        let text_style = TextStyle {
483            color: cx.theme().colors().text,
484            font_family: settings.ui_font.family.clone(),
485            font_features: settings.ui_font.features.clone(),
486            font_fallbacks: settings.ui_font.fallbacks.clone(),
487            font_size: rems(0.875).into(),
488            font_weight: settings.ui_font.weight,
489            font_style: FontStyle::Normal,
490            line_height: relative(1.3),
491            white_space: WhiteSpace::Normal,
492            ..Default::default()
493        };
494        EditorElement::new(
495            &self.api_key_editor,
496            EditorStyle {
497                background: cx.theme().colors().editor_background,
498                local_player: cx.theme().players().local(),
499                text: text_style,
500                ..Default::default()
501            },
502        )
503    }
504
505    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
506        !self.state.read(cx).is_authenticated()
507    }
508}
509
510impl Render for ConfigurationView {
511    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
512        const MISTRAL_CONSOLE_URL: &str = "https://console.mistral.ai/api-keys";
513        const INSTRUCTIONS: [&str; 4] = [
514            "To use Zed's assistant with Mistral, you need to add an API key. Follow these steps:",
515            " - Create one by visiting:",
516            " - Ensure your Mistral account has credits",
517            " - Paste your API key below and hit enter to start using the assistant",
518        ];
519
520        let env_var_set = self.state.read(cx).api_key_from_env;
521
522        if self.load_credentials_task.is_some() {
523            div().child(Label::new("Loading credentials...")).into_any()
524        } else if self.should_render_editor(cx) {
525            v_flex()
526                .size_full()
527                .on_action(cx.listener(Self::save_api_key))
528                .child(Label::new(INSTRUCTIONS[0]))
529                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
530                    Button::new("mistral_console", MISTRAL_CONSOLE_URL)
531                        .style(ButtonStyle::Subtle)
532                        .icon(IconName::ArrowUpRight)
533                        .icon_size(IconSize::XSmall)
534                        .icon_color(Color::Muted)
535                        .on_click(move |_, _, cx| cx.open_url(MISTRAL_CONSOLE_URL))
536                    )
537                )
538                .children(
539                    (2..INSTRUCTIONS.len()).map(|n|
540                        Label::new(INSTRUCTIONS[n])).collect::<Vec<_>>())
541                .child(
542                    h_flex()
543                        .w_full()
544                        .my_2()
545                        .px_2()
546                        .py_1()
547                        .bg(cx.theme().colors().editor_background)
548                        .border_1()
549                        .border_color(cx.theme().colors().border_variant)
550                        .rounded_md()
551                        .child(self.render_api_key_editor(cx)),
552                )
553                .child(
554                    Label::new(
555                        format!("You can also assign the {MISTRAL_API_KEY_VAR} environment variable and restart Zed."),
556                    )
557                    .size(LabelSize::Small),
558                )
559                .into_any()
560        } else {
561            h_flex()
562                .size_full()
563                .justify_between()
564                .child(
565                    h_flex()
566                        .gap_1()
567                        .child(Icon::new(IconName::Check).color(Color::Success))
568                        .child(Label::new(if env_var_set {
569                            format!("API key set in {MISTRAL_API_KEY_VAR} environment variable.")
570                        } else {
571                            "API key configured.".to_string()
572                        })),
573                )
574                .child(
575                    Button::new("reset-key", "Reset key")
576                        .icon(Some(IconName::Trash))
577                        .icon_size(IconSize::Small)
578                        .icon_position(IconPosition::Start)
579                        .disabled(env_var_set)
580                        .when(env_var_set, |this| {
581                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {MISTRAL_API_KEY_VAR} environment variable.")))
582                        })
583                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
584                )
585                .into_any()
586        }
587    }
588}