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_executor()
285            .spawn(async move {
286                let messages = request
287                    .messages
288                    .into_iter()
289                    .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
290                        role: match message.role {
291                            Role::User => "user".into(),
292                            Role::Assistant => "assistant".into(),
293                            Role::System => "system".into(),
294                        },
295                        content: Some(message.string_contents()),
296                        name: None,
297                        function_call: None,
298                    })
299                    .collect::<Vec<_>>();
300
301                tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
302            })
303            .boxed()
304    }
305
306    fn stream_completion(
307        &self,
308        request: LanguageModelRequest,
309        cx: &AsyncApp,
310    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
311        let request = request.into_mistral(self.model.id().to_string(), self.max_output_tokens());
312        let stream = self.stream_completion(request, cx);
313
314        async move {
315            let stream = stream.await?;
316            Ok(stream
317                .map(|result| {
318                    result.and_then(|response| {
319                        response
320                            .choices
321                            .first()
322                            .ok_or_else(|| anyhow!("Empty response"))
323                            .map(|choice| {
324                                choice
325                                    .delta
326                                    .content
327                                    .clone()
328                                    .unwrap_or_default()
329                                    .map(LanguageModelCompletionEvent::Text)
330                            })
331                    })
332                })
333                .boxed())
334        }
335        .boxed()
336    }
337
338    fn use_any_tool(
339        &self,
340        request: LanguageModelRequest,
341        tool_name: String,
342        tool_description: String,
343        schema: serde_json::Value,
344        cx: &AsyncApp,
345    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
346        let mut request = request.into_mistral(self.model.id().into(), self.max_output_tokens());
347        request.tools = vec![mistral::ToolDefinition::Function {
348            function: mistral::FunctionDefinition {
349                name: tool_name.clone(),
350                description: Some(tool_description),
351                parameters: Some(schema),
352            },
353        }];
354
355        let response = self.stream_completion(request, cx);
356        self.request_limiter
357            .run(async move {
358                let stream = response.await?;
359
360                let tool_args_stream = stream
361                    .filter_map(move |response| async move {
362                        match response {
363                            Ok(response) => {
364                                for choice in response.choices {
365                                    if let Some(tool_calls) = choice.delta.tool_calls {
366                                        for tool_call in tool_calls {
367                                            if let Some(function) = tool_call.function {
368                                                if let Some(args) = function.arguments {
369                                                    return Some(Ok(args));
370                                                }
371                                            }
372                                        }
373                                    }
374                                }
375                                None
376                            }
377                            Err(e) => Some(Err(e)),
378                        }
379                    })
380                    .boxed();
381
382                Ok(tool_args_stream)
383            })
384            .boxed()
385    }
386}
387
388struct ConfigurationView {
389    api_key_editor: Entity<Editor>,
390    state: gpui::Entity<State>,
391    load_credentials_task: Option<Task<()>>,
392}
393
394impl ConfigurationView {
395    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
396        let api_key_editor = cx.new(|cx| {
397            let mut editor = Editor::single_line(window, cx);
398            editor.set_placeholder_text("0aBCDEFGhIjKLmNOpqrSTUVwxyzabCDE1f2", cx);
399            editor
400        });
401
402        cx.observe(&state, |_, _, cx| {
403            cx.notify();
404        })
405        .detach();
406
407        let load_credentials_task = Some(cx.spawn_in(window, {
408            let state = state.clone();
409            |this, mut cx| async move {
410                if let Some(task) = state
411                    .update(&mut cx, |state, cx| state.authenticate(cx))
412                    .log_err()
413                {
414                    // We don't log an error, because "not signed in" is also an error.
415                    let _ = task.await;
416                }
417
418                this.update(&mut cx, |this, cx| {
419                    this.load_credentials_task = None;
420                    cx.notify();
421                })
422                .log_err();
423            }
424        }));
425
426        Self {
427            api_key_editor,
428            state,
429            load_credentials_task,
430        }
431    }
432
433    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
434        let api_key = self.api_key_editor.read(cx).text(cx);
435        if api_key.is_empty() {
436            return;
437        }
438
439        let state = self.state.clone();
440        cx.spawn_in(window, |_, mut cx| async move {
441            state
442                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
443                .await
444        })
445        .detach_and_log_err(cx);
446
447        cx.notify();
448    }
449
450    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
451        self.api_key_editor
452            .update(cx, |editor, cx| editor.set_text("", window, cx));
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.reset_api_key(cx))?
458                .await
459        })
460        .detach_and_log_err(cx);
461
462        cx.notify();
463    }
464
465    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
466        let settings = ThemeSettings::get_global(cx);
467        let text_style = TextStyle {
468            color: cx.theme().colors().text,
469            font_family: settings.ui_font.family.clone(),
470            font_features: settings.ui_font.features.clone(),
471            font_fallbacks: settings.ui_font.fallbacks.clone(),
472            font_size: rems(0.875).into(),
473            font_weight: settings.ui_font.weight,
474            font_style: FontStyle::Normal,
475            line_height: relative(1.3),
476            white_space: WhiteSpace::Normal,
477            ..Default::default()
478        };
479        EditorElement::new(
480            &self.api_key_editor,
481            EditorStyle {
482                background: cx.theme().colors().editor_background,
483                local_player: cx.theme().players().local(),
484                text: text_style,
485                ..Default::default()
486            },
487        )
488    }
489
490    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
491        !self.state.read(cx).is_authenticated()
492    }
493}
494
495impl Render for ConfigurationView {
496    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
497        const MISTRAL_CONSOLE_URL: &str = "https://console.mistral.ai/api-keys";
498        const INSTRUCTIONS: [&str; 4] = [
499            "To use Zed's assistant with Mistral, you need to add an API key. Follow these steps:",
500            " - Create one by visiting:",
501            " - Ensure your Mistral account has credits",
502            " - Paste your API key below and hit enter to start using the assistant",
503        ];
504
505        let env_var_set = self.state.read(cx).api_key_from_env;
506
507        if self.load_credentials_task.is_some() {
508            div().child(Label::new("Loading credentials...")).into_any()
509        } else if self.should_render_editor(cx) {
510            v_flex()
511                .size_full()
512                .on_action(cx.listener(Self::save_api_key))
513                .child(Label::new(INSTRUCTIONS[0]))
514                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
515                    Button::new("mistral_console", MISTRAL_CONSOLE_URL)
516                        .style(ButtonStyle::Subtle)
517                        .icon(IconName::ArrowUpRight)
518                        .icon_size(IconSize::XSmall)
519                        .icon_color(Color::Muted)
520                        .on_click(move |_, _, cx| cx.open_url(MISTRAL_CONSOLE_URL))
521                    )
522                )
523                .children(
524                    (2..INSTRUCTIONS.len()).map(|n|
525                        Label::new(INSTRUCTIONS[n])).collect::<Vec<_>>())
526                .child(
527                    h_flex()
528                        .w_full()
529                        .my_2()
530                        .px_2()
531                        .py_1()
532                        .bg(cx.theme().colors().editor_background)
533                        .border_1()
534                        .border_color(cx.theme().colors().border_variant)
535                        .rounded_md()
536                        .child(self.render_api_key_editor(cx)),
537                )
538                .child(
539                    Label::new(
540                        format!("You can also assign the {MISTRAL_API_KEY_VAR} environment variable and restart Zed."),
541                    )
542                    .size(LabelSize::Small),
543                )
544                .into_any()
545        } else {
546            h_flex()
547                .size_full()
548                .justify_between()
549                .child(
550                    h_flex()
551                        .gap_1()
552                        .child(Icon::new(IconName::Check).color(Color::Success))
553                        .child(Label::new(if env_var_set {
554                            format!("API key set in {MISTRAL_API_KEY_VAR} environment variable.")
555                        } else {
556                            "API key configured.".to_string()
557                        })),
558                )
559                .child(
560                    Button::new("reset-key", "Reset key")
561                        .icon(Some(IconName::Trash))
562                        .icon_size(IconSize::Small)
563                        .icon_position(IconPosition::Start)
564                        .disabled(env_var_set)
565                        .when(env_var_set, |this| {
566                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {MISTRAL_API_KEY_VAR} environment variable.")))
567                        })
568                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
569                )
570                .into_any()
571        }
572    }
573}