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