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, AsyncApp, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
  7};
  8use http_client::HttpClient;
  9use language_model::{
 10    LanguageModel, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
 11    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 12    LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
 13};
 14use schemars::JsonSchema;
 15use serde::{Deserialize, Serialize};
 16use settings::{Settings, SettingsStore};
 17use std::sync::Arc;
 18use theme::ThemeSettings;
 19use ui::{prelude::*, Icon, IconName};
 20use util::ResultExt;
 21
 22use crate::AllLanguageModelSettings;
 23
 24const PROVIDER_ID: &str = "deepseek";
 25const PROVIDER_NAME: &str = "DeepSeek";
 26const DEEPSEEK_API_KEY_VAR: &str = "DEEPSEEK_API_KEY";
 27
 28#[derive(Default, Clone, Debug, PartialEq)]
 29pub struct DeepSeekSettings {
 30    pub api_url: String,
 31    pub available_models: Vec<AvailableModel>,
 32}
 33
 34#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 35pub struct AvailableModel {
 36    pub name: String,
 37    pub display_name: Option<String>,
 38    pub max_tokens: usize,
 39    pub max_output_tokens: Option<u32>,
 40}
 41
 42pub struct DeepSeekLanguageModelProvider {
 43    http_client: Arc<dyn HttpClient>,
 44    state: Entity<State>,
 45}
 46
 47pub struct State {
 48    api_key: Option<String>,
 49    api_key_from_env: bool,
 50    _subscription: Subscription,
 51}
 52
 53impl State {
 54    fn is_authenticated(&self) -> bool {
 55        self.api_key.is_some()
 56    }
 57
 58    fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 59        let settings = &AllLanguageModelSettings::get_global(cx).deepseek;
 60        let delete_credentials = cx.delete_credentials(&settings.api_url);
 61        cx.spawn(|this, mut cx| async move {
 62            delete_credentials.await.log_err();
 63            this.update(&mut cx, |this, cx| {
 64                this.api_key = None;
 65                this.api_key_from_env = false;
 66                cx.notify();
 67            })
 68        })
 69    }
 70
 71    fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
 72        let settings = &AllLanguageModelSettings::get_global(cx).deepseek;
 73        let write_credentials =
 74            cx.write_credentials(&settings.api_url, "Bearer", api_key.as_bytes());
 75
 76        cx.spawn(|this, mut cx| async move {
 77            write_credentials.await?;
 78            this.update(&mut cx, |this, cx| {
 79                this.api_key = Some(api_key);
 80                cx.notify();
 81            })
 82        })
 83    }
 84
 85    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 86        if self.is_authenticated() {
 87            Task::ready(Ok(()))
 88        } else {
 89            let api_url = AllLanguageModelSettings::get_global(cx)
 90                .deepseek
 91                .api_url
 92                .clone();
 93
 94            cx.spawn(|this, mut cx| async move {
 95                let (api_key, from_env) = if let Ok(api_key) = std::env::var(DEEPSEEK_API_KEY_VAR) {
 96                    (api_key, true)
 97                } else {
 98                    let (_, api_key) = cx
 99                        .update(|cx| cx.read_credentials(&api_url))?
100                        .await?
101                        .ok_or_else(|| anyhow!("credentials not found"))?;
102                    (String::from_utf8(api_key)?, false)
103                };
104
105                this.update(&mut cx, |this, cx| {
106                    this.api_key = Some(api_key);
107                    this.api_key_from_env = from_env;
108                    cx.notify();
109                })
110            })
111        }
112    }
113}
114
115impl DeepSeekLanguageModelProvider {
116    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
117        let state = cx.new(|cx| State {
118            api_key: None,
119            api_key_from_env: false,
120            _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
121                cx.notify();
122            }),
123        });
124
125        Self { http_client, state }
126    }
127}
128
129impl LanguageModelProviderState for DeepSeekLanguageModelProvider {
130    type ObservableEntity = State;
131
132    fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
133        Some(self.state.clone())
134    }
135}
136
137impl LanguageModelProvider for DeepSeekLanguageModelProvider {
138    fn id(&self) -> LanguageModelProviderId {
139        LanguageModelProviderId(PROVIDER_ID.into())
140    }
141
142    fn name(&self) -> LanguageModelProviderName {
143        LanguageModelProviderName(PROVIDER_NAME.into())
144    }
145
146    fn icon(&self) -> IconName {
147        IconName::AiDeepSeek
148    }
149
150    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
151        let mut models = BTreeMap::default();
152
153        models.insert("deepseek-chat", deepseek::Model::Chat);
154        models.insert("deepseek-reasoner", deepseek::Model::Reasoner);
155
156        for available_model in AllLanguageModelSettings::get_global(cx)
157            .deepseek
158            .available_models
159            .iter()
160        {
161            models.insert(
162                &available_model.name,
163                deepseek::Model::Custom {
164                    name: available_model.name.clone(),
165                    display_name: available_model.display_name.clone(),
166                    max_tokens: available_model.max_tokens,
167                    max_output_tokens: available_model.max_output_tokens,
168                },
169            );
170        }
171
172        models
173            .into_values()
174            .map(|model| {
175                Arc::new(DeepSeekLanguageModel {
176                    id: LanguageModelId::from(model.id().to_string()),
177                    model,
178                    state: self.state.clone(),
179                    http_client: self.http_client.clone(),
180                    request_limiter: RateLimiter::new(4),
181                }) as Arc<dyn LanguageModel>
182            })
183            .collect()
184    }
185
186    fn is_authenticated(&self, cx: &App) -> bool {
187        self.state.read(cx).is_authenticated()
188    }
189
190    fn authenticate(&self, cx: &mut App) -> Task<Result<()>> {
191        self.state.update(cx, |state, cx| state.authenticate(cx))
192    }
193
194    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
195        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
196            .into()
197    }
198
199    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
200        self.state.update(cx, |state, cx| state.reset_api_key(cx))
201    }
202}
203
204pub struct DeepSeekLanguageModel {
205    id: LanguageModelId,
206    model: deepseek::Model,
207    state: Entity<State>,
208    http_client: Arc<dyn HttpClient>,
209    request_limiter: RateLimiter,
210}
211
212impl DeepSeekLanguageModel {
213    fn stream_completion(
214        &self,
215        request: deepseek::Request,
216        cx: &AsyncApp,
217    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<deepseek::StreamResponse>>>> {
218        let http_client = self.http_client.clone();
219        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
220            let settings = &AllLanguageModelSettings::get_global(cx).deepseek;
221            (state.api_key.clone(), settings.api_url.clone())
222        }) else {
223            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
224        };
225
226        let future = self.request_limiter.stream(async move {
227            let api_key = api_key.ok_or_else(|| anyhow!("Missing DeepSeek API Key"))?;
228            let request =
229                deepseek::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
230            let response = request.await?;
231            Ok(response)
232        });
233
234        async move { Ok(future.await?.boxed()) }.boxed()
235    }
236}
237
238impl LanguageModel for DeepSeekLanguageModel {
239    fn id(&self) -> LanguageModelId {
240        self.id.clone()
241    }
242
243    fn name(&self) -> LanguageModelName {
244        LanguageModelName::from(self.model.display_name().to_string())
245    }
246
247    fn provider_id(&self) -> LanguageModelProviderId {
248        LanguageModelProviderId(PROVIDER_ID.into())
249    }
250
251    fn provider_name(&self) -> LanguageModelProviderName {
252        LanguageModelProviderName(PROVIDER_NAME.into())
253    }
254
255    fn telemetry_id(&self) -> String {
256        format!("deepseek/{}", self.model.id())
257    }
258
259    fn max_token_count(&self) -> usize {
260        self.model.max_token_count()
261    }
262
263    fn max_output_tokens(&self) -> Option<u32> {
264        self.model.max_output_tokens()
265    }
266
267    fn count_tokens(
268        &self,
269        request: LanguageModelRequest,
270        cx: &App,
271    ) -> BoxFuture<'static, Result<usize>> {
272        cx.background_executor()
273            .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            truncate: None,
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::ExternalLink)
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                        .rounded_md()
524                        .child(self.render_api_key_editor(cx)),
525                )
526                .child(
527                    Label::new(format!(
528                        "Or set {} environment variable",
529                        DEEPSEEK_API_KEY_VAR
530                    ))
531                    .size(LabelSize::Small),
532                )
533                .into_any()
534        } else {
535            h_flex()
536                .size_full()
537                .justify_between()
538                .child(
539                    h_flex()
540                        .gap_1()
541                        .child(Icon::new(IconName::Check).color(Color::Success))
542                        .child(Label::new(if env_var_set {
543                            format!("API key set in {}", DEEPSEEK_API_KEY_VAR)
544                        } else {
545                            "API key configured".to_string()
546                        })),
547                )
548                .child(
549                    Button::new("reset-key", "Reset")
550                        .icon(IconName::Trash)
551                        .disabled(env_var_set)
552                        .on_click(
553                            cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)),
554                        ),
555                )
556                .into_any()
557        }
558    }
559}