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