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, AsyncAppContext, FontStyle, ModelContext, Subscription, Task, TextStyle,
  7    View, 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: gpui::Model<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 ModelContext<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 ModelContext<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 ModelContext<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 AppContext) -> Self {
118        let state = cx.new_model(|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<gpui::Model<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: &AppContext) -> 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: &AppContext) -> bool {
188        self.state.read(cx).is_authenticated()
189    }
190
191    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
192        self.state.update(cx, |state, cx| state.authenticate(cx))
193    }
194
195    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
196        cx.new_view(|cx| ConfigurationView::new(self.state.clone(), cx))
197            .into()
198    }
199
200    fn reset_credentials(&self, cx: &mut AppContext) -> 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: gpui::Model<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: &AsyncAppContext,
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_model(&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: &AppContext,
272    ) -> BoxFuture<'static, Result<usize>> {
273        cx.background_executor()
274            .spawn(async move {
275                let messages = request
276                    .messages
277                    .into_iter()
278                    .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
279                        role: match message.role {
280                            Role::User => "user".into(),
281                            Role::Assistant => "assistant".into(),
282                            Role::System => "system".into(),
283                        },
284                        content: Some(message.string_contents()),
285                        name: None,
286                        function_call: None,
287                    })
288                    .collect::<Vec<_>>();
289
290                tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
291            })
292            .boxed()
293    }
294
295    fn stream_completion(
296        &self,
297        request: LanguageModelRequest,
298        cx: &AsyncAppContext,
299    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
300        let request = request.into_deepseek(self.model.id().to_string(), self.max_output_tokens());
301        let stream = self.stream_completion(request, cx);
302
303        async move {
304            let stream = stream.await?;
305            Ok(stream
306                .map(|result| {
307                    result.and_then(|response| {
308                        response
309                            .choices
310                            .first()
311                            .ok_or_else(|| anyhow!("Empty response"))
312                            .map(|choice| {
313                                choice
314                                    .delta
315                                    .content
316                                    .clone()
317                                    .unwrap_or_default()
318                                    .map(LanguageModelCompletionEvent::Text)
319                            })
320                    })
321                })
322                .boxed())
323        }
324        .boxed()
325    }
326    fn use_any_tool(
327        &self,
328        request: LanguageModelRequest,
329        name: String,
330        description: String,
331        schema: serde_json::Value,
332        cx: &AsyncAppContext,
333    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
334        let mut deepseek_request =
335            request.into_deepseek(self.model.id().to_string(), self.max_output_tokens());
336
337        deepseek_request.tools = vec![deepseek::ToolDefinition::Function {
338            function: deepseek::FunctionDefinition {
339                name: name.clone(),
340                description: Some(description),
341                parameters: Some(schema),
342            },
343        }];
344
345        let response_stream = self.stream_completion(deepseek_request, cx);
346
347        self.request_limiter
348            .run(async move {
349                let stream = response_stream.await?;
350
351                let tool_args_stream = stream
352                    .filter_map(move |response| async move {
353                        match response {
354                            Ok(response) => {
355                                for choice in response.choices {
356                                    if let Some(tool_calls) = choice.delta.tool_calls {
357                                        for tool_call in tool_calls {
358                                            if let Some(function) = tool_call.function {
359                                                if let Some(args) = function.arguments {
360                                                    return Some(Ok(args));
361                                                }
362                                            }
363                                        }
364                                    }
365                                }
366                                None
367                            }
368                            Err(e) => Some(Err(e)),
369                        }
370                    })
371                    .boxed();
372
373                Ok(tool_args_stream)
374            })
375            .boxed()
376    }
377}
378
379struct ConfigurationView {
380    api_key_editor: View<Editor>,
381    state: gpui::Model<State>,
382    load_credentials_task: Option<Task<()>>,
383}
384
385impl ConfigurationView {
386    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
387        let api_key_editor = cx.new_view(|cx| {
388            let mut editor = Editor::single_line(cx);
389            editor.set_placeholder_text("sk-00000000000000000000000000000000", cx);
390            editor
391        });
392
393        cx.observe(&state, |_, _, cx| {
394            cx.notify();
395        })
396        .detach();
397
398        let load_credentials_task = Some(cx.spawn({
399            let state = state.clone();
400            |this, mut cx| async move {
401                if let Some(task) = state
402                    .update(&mut cx, |state, cx| state.authenticate(cx))
403                    .log_err()
404                {
405                    let _ = task.await;
406                }
407
408                this.update(&mut cx, |this, cx| {
409                    this.load_credentials_task = None;
410                    cx.notify();
411                })
412                .log_err();
413            }
414        }));
415
416        Self {
417            api_key_editor,
418            state,
419            load_credentials_task,
420        }
421    }
422
423    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
424        let api_key = self.api_key_editor.read(cx).text(cx);
425        if api_key.is_empty() {
426            return;
427        }
428
429        let state = self.state.clone();
430        cx.spawn(|_, mut cx| async move {
431            state
432                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
433                .await
434        })
435        .detach_and_log_err(cx);
436
437        cx.notify();
438    }
439
440    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
441        self.api_key_editor
442            .update(cx, |editor, cx| editor.set_text("", cx));
443
444        let state = self.state.clone();
445        cx.spawn(|_, mut cx| async move {
446            state
447                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
448                .await
449        })
450        .detach_and_log_err(cx);
451
452        cx.notify();
453    }
454
455    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
456        let settings = ThemeSettings::get_global(cx);
457        let text_style = TextStyle {
458            color: cx.theme().colors().text,
459            font_family: settings.ui_font.family.clone(),
460            font_features: settings.ui_font.features.clone(),
461            font_fallbacks: settings.ui_font.fallbacks.clone(),
462            font_size: rems(0.875).into(),
463            font_weight: settings.ui_font.weight,
464            font_style: FontStyle::Normal,
465            line_height: relative(1.3),
466            background_color: None,
467            underline: None,
468            strikethrough: None,
469            white_space: WhiteSpace::Normal,
470            truncate: None,
471        };
472        EditorElement::new(
473            &self.api_key_editor,
474            EditorStyle {
475                background: cx.theme().colors().editor_background,
476                local_player: cx.theme().players().local(),
477                text: text_style,
478                ..Default::default()
479            },
480        )
481    }
482
483    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
484        !self.state.read(cx).is_authenticated()
485    }
486}
487
488impl Render for ConfigurationView {
489    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
490        const DEEPSEEK_CONSOLE_URL: &str = "https://platform.deepseek.com/api_keys";
491        const INSTRUCTIONS: [&str; 3] = [
492            "To use DeepSeek in Zed, you need an API key:",
493            "- Get your API key from:",
494            "- Paste it below and press enter:",
495        ];
496
497        let env_var_set = self.state.read(cx).api_key_from_env;
498
499        if self.load_credentials_task.is_some() {
500            div().child(Label::new("Loading credentials...")).into_any()
501        } else if self.should_render_editor(cx) {
502            v_flex()
503                .size_full()
504                .on_action(cx.listener(Self::save_api_key))
505                .child(Label::new(INSTRUCTIONS[0]))
506                .child(
507                    h_flex().child(Label::new(INSTRUCTIONS[1])).child(
508                        Button::new("deepseek_console", DEEPSEEK_CONSOLE_URL)
509                            .style(ButtonStyle::Subtle)
510                            .icon(IconName::ExternalLink)
511                            .icon_size(IconSize::XSmall)
512                            .icon_color(Color::Muted)
513                            .on_click(move |_, cx| cx.open_url(DEEPSEEK_CONSOLE_URL)),
514                    ),
515                )
516                .child(Label::new(INSTRUCTIONS[2]))
517                .child(
518                    h_flex()
519                        .w_full()
520                        .my_2()
521                        .px_2()
522                        .py_1()
523                        .bg(cx.theme().colors().editor_background)
524                        .rounded_md()
525                        .child(self.render_api_key_editor(cx)),
526                )
527                .child(
528                    Label::new(format!(
529                        "Or set {} environment variable",
530                        DEEPSEEK_API_KEY_VAR
531                    ))
532                    .size(LabelSize::Small),
533                )
534                .into_any()
535        } else {
536            h_flex()
537                .size_full()
538                .justify_between()
539                .child(
540                    h_flex()
541                        .gap_1()
542                        .child(Icon::new(IconName::Check).color(Color::Success))
543                        .child(Label::new(if env_var_set {
544                            format!("API key set in {}", DEEPSEEK_API_KEY_VAR)
545                        } else {
546                            "API key configured".to_string()
547                        })),
548                )
549                .child(
550                    Button::new("reset-key", "Reset")
551                        .icon(IconName::Trash)
552                        .disabled(env_var_set)
553                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
554                )
555                .into_any()
556        }
557    }
558}