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