1use anyhow::{anyhow, Context as _, Result};
2use collections::BTreeMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
6use gpui::{
7 AnyView, AppContext as _, AsyncApp, Entity, FontStyle, Subscription, Task, TextStyle,
8 WhiteSpace,
9};
10use http_client::HttpClient;
11use language_model::{
12 AuthenticateError, LanguageModel, LanguageModelCompletionEvent, LanguageModelId,
13 LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
14 LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
15};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18use settings::{Settings, SettingsStore};
19use std::sync::Arc;
20use theme::ThemeSettings;
21use ui::{prelude::*, Icon, IconName};
22use util::ResultExt;
23
24use crate::AllLanguageModelSettings;
25
26const PROVIDER_ID: &str = "deepseek";
27const PROVIDER_NAME: &str = "DeepSeek";
28const DEEPSEEK_API_KEY_VAR: &str = "DEEPSEEK_API_KEY";
29
30#[derive(Default, Clone, Debug, PartialEq)]
31pub struct DeepSeekSettings {
32 pub api_url: String,
33 pub available_models: Vec<AvailableModel>,
34}
35
36#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
37pub struct AvailableModel {
38 pub name: String,
39 pub display_name: Option<String>,
40 pub max_tokens: usize,
41 pub max_output_tokens: Option<u32>,
42}
43
44pub struct DeepSeekLanguageModelProvider {
45 http_client: Arc<dyn HttpClient>,
46 state: Entity<State>,
47}
48
49pub struct State {
50 api_key: Option<String>,
51 api_key_from_env: bool,
52 _subscription: Subscription,
53}
54
55impl State {
56 fn is_authenticated(&self) -> bool {
57 self.api_key.is_some()
58 }
59
60 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
61 let credentials_provider = <dyn CredentialsProvider>::global(cx);
62 let api_url = AllLanguageModelSettings::get_global(cx)
63 .deepseek
64 .api_url
65 .clone();
66 cx.spawn(|this, mut cx| async move {
67 credentials_provider
68 .delete_credentials(&api_url, &cx)
69 .await
70 .log_err();
71 this.update(&mut cx, |this, cx| {
72 this.api_key = None;
73 this.api_key_from_env = false;
74 cx.notify();
75 })
76 })
77 }
78
79 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
80 let credentials_provider = <dyn CredentialsProvider>::global(cx);
81 let api_url = AllLanguageModelSettings::get_global(cx)
82 .deepseek
83 .api_url
84 .clone();
85 cx.spawn(|this, mut cx| async move {
86 credentials_provider
87 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
88 .await?;
89 this.update(&mut cx, |this, cx| {
90 this.api_key = Some(api_key);
91 cx.notify();
92 })
93 })
94 }
95
96 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
97 if self.is_authenticated() {
98 return Task::ready(Ok(()));
99 }
100
101 let credentials_provider = <dyn CredentialsProvider>::global(cx);
102 let api_url = AllLanguageModelSettings::get_global(cx)
103 .deepseek
104 .api_url
105 .clone();
106 cx.spawn(|this, mut cx| async move {
107 let (api_key, from_env) = if let Ok(api_key) = std::env::var(DEEPSEEK_API_KEY_VAR) {
108 (api_key, true)
109 } else {
110 let (_, api_key) = credentials_provider
111 .read_credentials(&api_url, &cx)
112 .await?
113 .ok_or(AuthenticateError::CredentialsNotFound)?;
114 (
115 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
116 false,
117 )
118 };
119
120 this.update(&mut cx, |this, cx| {
121 this.api_key = Some(api_key);
122 this.api_key_from_env = from_env;
123 cx.notify();
124 })?;
125
126 Ok(())
127 })
128 }
129}
130
131impl DeepSeekLanguageModelProvider {
132 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
133 let state = cx.new(|cx| State {
134 api_key: None,
135 api_key_from_env: false,
136 _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
137 cx.notify();
138 }),
139 });
140
141 Self { http_client, state }
142 }
143}
144
145impl LanguageModelProviderState for DeepSeekLanguageModelProvider {
146 type ObservableEntity = State;
147
148 fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
149 Some(self.state.clone())
150 }
151}
152
153impl LanguageModelProvider for DeepSeekLanguageModelProvider {
154 fn id(&self) -> LanguageModelProviderId {
155 LanguageModelProviderId(PROVIDER_ID.into())
156 }
157
158 fn name(&self) -> LanguageModelProviderName {
159 LanguageModelProviderName(PROVIDER_NAME.into())
160 }
161
162 fn icon(&self) -> IconName {
163 IconName::AiDeepSeek
164 }
165
166 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
167 let model = deepseek::Model::Chat;
168 Some(Arc::new(DeepSeekLanguageModel {
169 id: LanguageModelId::from(model.id().to_string()),
170 model,
171 state: self.state.clone(),
172 http_client: self.http_client.clone(),
173 request_limiter: RateLimiter::new(4),
174 }))
175 }
176
177 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
178 let mut models = BTreeMap::default();
179
180 models.insert("deepseek-chat", deepseek::Model::Chat);
181 models.insert("deepseek-reasoner", deepseek::Model::Reasoner);
182
183 for available_model in AllLanguageModelSettings::get_global(cx)
184 .deepseek
185 .available_models
186 .iter()
187 {
188 models.insert(
189 &available_model.name,
190 deepseek::Model::Custom {
191 name: available_model.name.clone(),
192 display_name: available_model.display_name.clone(),
193 max_tokens: available_model.max_tokens,
194 max_output_tokens: available_model.max_output_tokens,
195 },
196 );
197 }
198
199 models
200 .into_values()
201 .map(|model| {
202 Arc::new(DeepSeekLanguageModel {
203 id: LanguageModelId::from(model.id().to_string()),
204 model,
205 state: self.state.clone(),
206 http_client: self.http_client.clone(),
207 request_limiter: RateLimiter::new(4),
208 }) as Arc<dyn LanguageModel>
209 })
210 .collect()
211 }
212
213 fn is_authenticated(&self, cx: &App) -> bool {
214 self.state.read(cx).is_authenticated()
215 }
216
217 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
218 self.state.update(cx, |state, cx| state.authenticate(cx))
219 }
220
221 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
222 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
223 .into()
224 }
225
226 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
227 self.state.update(cx, |state, cx| state.reset_api_key(cx))
228 }
229}
230
231pub struct DeepSeekLanguageModel {
232 id: LanguageModelId,
233 model: deepseek::Model,
234 state: Entity<State>,
235 http_client: Arc<dyn HttpClient>,
236 request_limiter: RateLimiter,
237}
238
239impl DeepSeekLanguageModel {
240 fn stream_completion(
241 &self,
242 request: deepseek::Request,
243 cx: &AsyncApp,
244 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<deepseek::StreamResponse>>>> {
245 let http_client = self.http_client.clone();
246 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
247 let settings = &AllLanguageModelSettings::get_global(cx).deepseek;
248 (state.api_key.clone(), settings.api_url.clone())
249 }) else {
250 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
251 };
252
253 let future = self.request_limiter.stream(async move {
254 let api_key = api_key.ok_or_else(|| anyhow!("Missing DeepSeek API Key"))?;
255 let request =
256 deepseek::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
257 let response = request.await?;
258 Ok(response)
259 });
260
261 async move { Ok(future.await?.boxed()) }.boxed()
262 }
263}
264
265impl LanguageModel for DeepSeekLanguageModel {
266 fn id(&self) -> LanguageModelId {
267 self.id.clone()
268 }
269
270 fn name(&self) -> LanguageModelName {
271 LanguageModelName::from(self.model.display_name().to_string())
272 }
273
274 fn provider_id(&self) -> LanguageModelProviderId {
275 LanguageModelProviderId(PROVIDER_ID.into())
276 }
277
278 fn provider_name(&self) -> LanguageModelProviderName {
279 LanguageModelProviderName(PROVIDER_NAME.into())
280 }
281
282 fn telemetry_id(&self) -> String {
283 format!("deepseek/{}", self.model.id())
284 }
285
286 fn max_token_count(&self) -> usize {
287 self.model.max_token_count()
288 }
289
290 fn max_output_tokens(&self) -> Option<u32> {
291 self.model.max_output_tokens()
292 }
293
294 fn count_tokens(
295 &self,
296 request: LanguageModelRequest,
297 cx: &App,
298 ) -> BoxFuture<'static, Result<usize>> {
299 cx.background_spawn(async move {
300 let messages = request
301 .messages
302 .into_iter()
303 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
304 role: match message.role {
305 Role::User => "user".into(),
306 Role::Assistant => "assistant".into(),
307 Role::System => "system".into(),
308 },
309 content: Some(message.string_contents()),
310 name: None,
311 function_call: None,
312 })
313 .collect::<Vec<_>>();
314
315 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
316 })
317 .boxed()
318 }
319
320 fn stream_completion(
321 &self,
322 request: LanguageModelRequest,
323 cx: &AsyncApp,
324 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
325 let request = request.into_deepseek(self.model.id().to_string(), self.max_output_tokens());
326 let stream = self.stream_completion(request, cx);
327
328 async move {
329 let stream = stream.await?;
330 Ok(stream
331 .map(|result| {
332 result.and_then(|response| {
333 response
334 .choices
335 .first()
336 .ok_or_else(|| anyhow!("Empty response"))
337 .map(|choice| {
338 choice
339 .delta
340 .content
341 .clone()
342 .unwrap_or_default()
343 .map(LanguageModelCompletionEvent::Text)
344 })
345 })
346 })
347 .boxed())
348 }
349 .boxed()
350 }
351
352 fn use_any_tool(
353 &self,
354 request: LanguageModelRequest,
355 name: String,
356 description: String,
357 schema: serde_json::Value,
358 cx: &AsyncApp,
359 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
360 let mut deepseek_request =
361 request.into_deepseek(self.model.id().to_string(), self.max_output_tokens());
362
363 deepseek_request.tools = vec![deepseek::ToolDefinition::Function {
364 function: deepseek::FunctionDefinition {
365 name: name.clone(),
366 description: Some(description),
367 parameters: Some(schema),
368 },
369 }];
370
371 let response_stream = self.stream_completion(deepseek_request, cx);
372
373 self.request_limiter
374 .run(async move {
375 let stream = response_stream.await?;
376
377 let tool_args_stream = stream
378 .filter_map(move |response| async move {
379 match response {
380 Ok(response) => {
381 for choice in response.choices {
382 if let Some(tool_calls) = choice.delta.tool_calls {
383 for tool_call in tool_calls {
384 if let Some(function) = tool_call.function {
385 if let Some(args) = function.arguments {
386 return Some(Ok(args));
387 }
388 }
389 }
390 }
391 }
392 None
393 }
394 Err(e) => Some(Err(e)),
395 }
396 })
397 .boxed();
398
399 Ok(tool_args_stream)
400 })
401 .boxed()
402 }
403}
404
405struct ConfigurationView {
406 api_key_editor: Entity<Editor>,
407 state: Entity<State>,
408 load_credentials_task: Option<Task<()>>,
409}
410
411impl ConfigurationView {
412 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
413 let api_key_editor = cx.new(|cx| {
414 let mut editor = Editor::single_line(window, cx);
415 editor.set_placeholder_text("sk-00000000000000000000000000000000", cx);
416 editor
417 });
418
419 cx.observe(&state, |_, _, cx| {
420 cx.notify();
421 })
422 .detach();
423
424 let load_credentials_task = Some(cx.spawn({
425 let state = state.clone();
426 |this, mut cx| async move {
427 if let Some(task) = state
428 .update(&mut cx, |state, cx| state.authenticate(cx))
429 .log_err()
430 {
431 let _ = task.await;
432 }
433
434 this.update(&mut cx, |this, cx| {
435 this.load_credentials_task = None;
436 cx.notify();
437 })
438 .log_err();
439 }
440 }));
441
442 Self {
443 api_key_editor,
444 state,
445 load_credentials_task,
446 }
447 }
448
449 fn save_api_key(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
450 let api_key = self.api_key_editor.read(cx).text(cx);
451 if api_key.is_empty() {
452 return;
453 }
454
455 let state = self.state.clone();
456 cx.spawn(|_, mut cx| async move {
457 state
458 .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
459 .await
460 })
461 .detach_and_log_err(cx);
462
463 cx.notify();
464 }
465
466 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
467 self.api_key_editor
468 .update(cx, |editor, cx| editor.set_text("", window, cx));
469
470 let state = self.state.clone();
471 cx.spawn(|_, mut cx| async move {
472 state
473 .update(&mut cx, |state, cx| state.reset_api_key(cx))?
474 .await
475 })
476 .detach_and_log_err(cx);
477
478 cx.notify();
479 }
480
481 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
482 let settings = ThemeSettings::get_global(cx);
483 let text_style = TextStyle {
484 color: cx.theme().colors().text,
485 font_family: settings.ui_font.family.clone(),
486 font_features: settings.ui_font.features.clone(),
487 font_fallbacks: settings.ui_font.fallbacks.clone(),
488 font_size: rems(0.875).into(),
489 font_weight: settings.ui_font.weight,
490 font_style: FontStyle::Normal,
491 line_height: relative(1.3),
492 background_color: None,
493 underline: None,
494 strikethrough: None,
495 white_space: WhiteSpace::Normal,
496 ..Default::default()
497 };
498 EditorElement::new(
499 &self.api_key_editor,
500 EditorStyle {
501 background: cx.theme().colors().editor_background,
502 local_player: cx.theme().players().local(),
503 text: text_style,
504 ..Default::default()
505 },
506 )
507 }
508
509 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
510 !self.state.read(cx).is_authenticated()
511 }
512}
513
514impl Render for ConfigurationView {
515 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
516 const DEEPSEEK_CONSOLE_URL: &str = "https://platform.deepseek.com/api_keys";
517 const INSTRUCTIONS: [&str; 3] = [
518 "To use DeepSeek in Zed, you need an API key:",
519 "- Get your API key from:",
520 "- Paste it below and press enter:",
521 ];
522
523 let env_var_set = self.state.read(cx).api_key_from_env;
524
525 if self.load_credentials_task.is_some() {
526 div().child(Label::new("Loading credentials...")).into_any()
527 } else if self.should_render_editor(cx) {
528 v_flex()
529 .size_full()
530 .on_action(cx.listener(Self::save_api_key))
531 .child(Label::new(INSTRUCTIONS[0]))
532 .child(
533 h_flex().child(Label::new(INSTRUCTIONS[1])).child(
534 Button::new("deepseek_console", DEEPSEEK_CONSOLE_URL)
535 .style(ButtonStyle::Subtle)
536 .icon(IconName::ArrowUpRight)
537 .icon_size(IconSize::XSmall)
538 .icon_color(Color::Muted)
539 .on_click(move |_, _window, cx| cx.open_url(DEEPSEEK_CONSOLE_URL)),
540 ),
541 )
542 .child(Label::new(INSTRUCTIONS[2]))
543 .child(
544 h_flex()
545 .w_full()
546 .my_2()
547 .px_2()
548 .py_1()
549 .bg(cx.theme().colors().editor_background)
550 .border_1()
551 .border_color(cx.theme().colors().border_variant)
552 .rounded_md()
553 .child(self.render_api_key_editor(cx)),
554 )
555 .child(
556 Label::new(format!(
557 "Or set the {} environment variable.",
558 DEEPSEEK_API_KEY_VAR
559 ))
560 .size(LabelSize::Small),
561 )
562 .into_any()
563 } else {
564 h_flex()
565 .size_full()
566 .justify_between()
567 .child(
568 h_flex()
569 .gap_1()
570 .child(Icon::new(IconName::Check).color(Color::Success))
571 .child(Label::new(if env_var_set {
572 format!("API key set in {}", DEEPSEEK_API_KEY_VAR)
573 } else {
574 "API key configured".to_string()
575 })),
576 )
577 .child(
578 Button::new("reset-key", "Reset")
579 .icon(IconName::Trash)
580 .disabled(env_var_set)
581 .on_click(
582 cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)),
583 ),
584 )
585 .into_any()
586 }
587 }
588}