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