mistral.rs

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