deepseek.rs

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