anthropic.rs

  1use crate::{
  2    settings::AllLanguageModelSettings, LanguageModel, LanguageModelCacheConfiguration,
  3    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
  4    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
  5};
  6use anthropic::AnthropicError;
  7use anyhow::{anyhow, Context as _, Result};
  8use collections::BTreeMap;
  9use editor::{Editor, EditorElement, EditorStyle};
 10use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryStreamExt as _};
 11use gpui::{
 12    AnyView, AppContext, AsyncAppContext, FontStyle, ModelContext, Subscription, Task, TextStyle,
 13    View, WhiteSpace,
 14};
 15use http_client::HttpClient;
 16use schemars::JsonSchema;
 17use serde::{Deserialize, Serialize};
 18use settings::{Settings, SettingsStore};
 19use std::{sync::Arc, time::Duration};
 20use strum::IntoEnumIterator;
 21use theme::ThemeSettings;
 22use ui::{prelude::*, Icon, IconName, Tooltip};
 23use util::ResultExt;
 24
 25const PROVIDER_ID: &str = "anthropic";
 26const PROVIDER_NAME: &str = "Anthropic";
 27
 28#[derive(Default, Clone, Debug, PartialEq)]
 29pub struct AnthropicSettings {
 30    pub api_url: String,
 31    pub low_speed_timeout: Option<Duration>,
 32    /// Extend Zed's list of Anthropic models.
 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    /// The model's name in the Anthropic API. e.g. claude-3-5-sonnet-20240620
 40    pub name: String,
 41    /// The model's name in Zed's UI, such as in the model selector dropdown menu in the assistant panel.
 42    pub display_name: Option<String>,
 43    /// The model's context window size.
 44    pub max_tokens: usize,
 45    /// A model `name` to substitute when calling tools, in case the primary model doesn't support tool calling.
 46    pub tool_override: Option<String>,
 47    /// Configuration of Anthropic's caching API.
 48    pub cache_configuration: Option<LanguageModelCacheConfiguration>,
 49    pub max_output_tokens: Option<u32>,
 50}
 51
 52pub struct AnthropicLanguageModelProvider {
 53    http_client: Arc<dyn HttpClient>,
 54    state: gpui::Model<State>,
 55}
 56
 57const ANTHROPIC_API_KEY_VAR: &'static str = "ANTHROPIC_API_KEY";
 58
 59pub struct State {
 60    api_key: Option<String>,
 61    api_key_from_env: bool,
 62    _subscription: Subscription,
 63}
 64
 65impl State {
 66    fn reset_api_key(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 67        let delete_credentials =
 68            cx.delete_credentials(&AllLanguageModelSettings::get_global(cx).anthropic.api_url);
 69        cx.spawn(|this, mut cx| async move {
 70            delete_credentials.await.ok();
 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 ModelContext<Self>) -> Task<Result<()>> {
 80        let write_credentials = cx.write_credentials(
 81            AllLanguageModelSettings::get_global(cx)
 82                .anthropic
 83                .api_url
 84                .as_str(),
 85            "Bearer",
 86            api_key.as_bytes(),
 87        );
 88        cx.spawn(|this, mut cx| async move {
 89            write_credentials.await?;
 90
 91            this.update(&mut cx, |this, cx| {
 92                this.api_key = Some(api_key);
 93                cx.notify();
 94            })
 95        })
 96    }
 97
 98    fn is_authenticated(&self) -> bool {
 99        self.api_key.is_some()
100    }
101
102    fn authenticate(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
103        if self.is_authenticated() {
104            Task::ready(Ok(()))
105        } else {
106            let api_url = AllLanguageModelSettings::get_global(cx)
107                .anthropic
108                .api_url
109                .clone();
110
111            cx.spawn(|this, mut cx| async move {
112                let (api_key, from_env) = if let Ok(api_key) = std::env::var(ANTHROPIC_API_KEY_VAR)
113                {
114                    (api_key, true)
115                } else {
116                    let (_, api_key) = cx
117                        .update(|cx| cx.read_credentials(&api_url))?
118                        .await?
119                        .ok_or_else(|| anyhow!("credentials not found"))?;
120                    (String::from_utf8(api_key)?, false)
121                };
122
123                this.update(&mut cx, |this, cx| {
124                    this.api_key = Some(api_key);
125                    this.api_key_from_env = from_env;
126                    cx.notify();
127                })
128            })
129        }
130    }
131}
132
133impl AnthropicLanguageModelProvider {
134    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Self {
135        let state = cx.new_model(|cx| State {
136            api_key: None,
137            api_key_from_env: false,
138            _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
139                cx.notify();
140            }),
141        });
142
143        Self { http_client, state }
144    }
145}
146
147impl LanguageModelProviderState for AnthropicLanguageModelProvider {
148    type ObservableEntity = State;
149
150    fn observable_entity(&self) -> Option<gpui::Model<Self::ObservableEntity>> {
151        Some(self.state.clone())
152    }
153}
154
155impl LanguageModelProvider for AnthropicLanguageModelProvider {
156    fn id(&self) -> LanguageModelProviderId {
157        LanguageModelProviderId(PROVIDER_ID.into())
158    }
159
160    fn name(&self) -> LanguageModelProviderName {
161        LanguageModelProviderName(PROVIDER_NAME.into())
162    }
163
164    fn icon(&self) -> IconName {
165        IconName::AiAnthropic
166    }
167
168    fn provided_models(&self, cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
169        let mut models = BTreeMap::default();
170
171        // Add base models from anthropic::Model::iter()
172        for model in anthropic::Model::iter() {
173            if !matches!(model, anthropic::Model::Custom { .. }) {
174                models.insert(model.id().to_string(), model);
175            }
176        }
177
178        // Override with available models from settings
179        for model in AllLanguageModelSettings::get_global(cx)
180            .anthropic
181            .available_models
182            .iter()
183        {
184            models.insert(
185                model.name.clone(),
186                anthropic::Model::Custom {
187                    name: model.name.clone(),
188                    display_name: model.display_name.clone(),
189                    max_tokens: model.max_tokens,
190                    tool_override: model.tool_override.clone(),
191                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
192                        anthropic::AnthropicModelCacheConfiguration {
193                            max_cache_anchors: config.max_cache_anchors,
194                            should_speculate: config.should_speculate,
195                            min_total_token: config.min_total_token,
196                        }
197                    }),
198                    max_output_tokens: model.max_output_tokens,
199                },
200            );
201        }
202
203        models
204            .into_values()
205            .map(|model| {
206                Arc::new(AnthropicModel {
207                    id: LanguageModelId::from(model.id().to_string()),
208                    model,
209                    state: self.state.clone(),
210                    http_client: self.http_client.clone(),
211                    request_limiter: RateLimiter::new(4),
212                }) as Arc<dyn LanguageModel>
213            })
214            .collect()
215    }
216
217    fn is_authenticated(&self, cx: &AppContext) -> bool {
218        self.state.read(cx).is_authenticated()
219    }
220
221    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
222        self.state.update(cx, |state, cx| state.authenticate(cx))
223    }
224
225    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
226        cx.new_view(|cx| ConfigurationView::new(self.state.clone(), cx))
227            .into()
228    }
229
230    fn reset_credentials(&self, cx: &mut AppContext) -> Task<Result<()>> {
231        self.state.update(cx, |state, cx| state.reset_api_key(cx))
232    }
233}
234
235pub struct AnthropicModel {
236    id: LanguageModelId,
237    model: anthropic::Model,
238    state: gpui::Model<State>,
239    http_client: Arc<dyn HttpClient>,
240    request_limiter: RateLimiter,
241}
242
243pub fn count_anthropic_tokens(
244    request: LanguageModelRequest,
245    cx: &AppContext,
246) -> BoxFuture<'static, Result<usize>> {
247    cx.background_executor()
248        .spawn(async move {
249            let messages = request.messages;
250            let mut tokens_from_images = 0;
251            let mut string_messages = Vec::with_capacity(messages.len());
252
253            for message in messages {
254                use crate::MessageContent;
255
256                let mut string_contents = String::new();
257
258                for content in message.content {
259                    match content {
260                        MessageContent::Text(string) => {
261                            string_contents.push_str(&string);
262                        }
263                        MessageContent::Image(image) => {
264                            tokens_from_images += image.estimate_tokens();
265                        }
266                    }
267                }
268
269                if !string_contents.is_empty() {
270                    string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
271                        role: match message.role {
272                            Role::User => "user".into(),
273                            Role::Assistant => "assistant".into(),
274                            Role::System => "system".into(),
275                        },
276                        content: Some(string_contents),
277                        name: None,
278                        function_call: None,
279                    });
280                }
281            }
282
283            // Tiktoken doesn't yet support these models, so we manually use the
284            // same tokenizer as GPT-4.
285            tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
286                .map(|tokens| tokens + tokens_from_images)
287        })
288        .boxed()
289}
290
291impl AnthropicModel {
292    fn stream_completion(
293        &self,
294        request: anthropic::Request,
295        cx: &AsyncAppContext,
296    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<anthropic::Event, AnthropicError>>>>
297    {
298        let http_client = self.http_client.clone();
299
300        let Ok((api_key, api_url, low_speed_timeout)) = cx.read_model(&self.state, |state, cx| {
301            let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
302            (
303                state.api_key.clone(),
304                settings.api_url.clone(),
305                settings.low_speed_timeout,
306            )
307        }) else {
308            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
309        };
310
311        async move {
312            let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
313            let request = anthropic::stream_completion(
314                http_client.as_ref(),
315                &api_url,
316                &api_key,
317                request,
318                low_speed_timeout,
319            );
320            request.await.context("failed to stream completion")
321        }
322        .boxed()
323    }
324}
325
326impl LanguageModel for AnthropicModel {
327    fn id(&self) -> LanguageModelId {
328        self.id.clone()
329    }
330
331    fn name(&self) -> LanguageModelName {
332        LanguageModelName::from(self.model.display_name().to_string())
333    }
334
335    fn provider_id(&self) -> LanguageModelProviderId {
336        LanguageModelProviderId(PROVIDER_ID.into())
337    }
338
339    fn provider_name(&self) -> LanguageModelProviderName {
340        LanguageModelProviderName(PROVIDER_NAME.into())
341    }
342
343    fn telemetry_id(&self) -> String {
344        format!("anthropic/{}", self.model.id())
345    }
346
347    fn max_token_count(&self) -> usize {
348        self.model.max_token_count()
349    }
350
351    fn max_output_tokens(&self) -> Option<u32> {
352        Some(self.model.max_output_tokens())
353    }
354
355    fn count_tokens(
356        &self,
357        request: LanguageModelRequest,
358        cx: &AppContext,
359    ) -> BoxFuture<'static, Result<usize>> {
360        count_anthropic_tokens(request, cx)
361    }
362
363    fn stream_completion(
364        &self,
365        request: LanguageModelRequest,
366        cx: &AsyncAppContext,
367    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
368        let request =
369            request.into_anthropic(self.model.id().into(), self.model.max_output_tokens());
370        let request = self.stream_completion(request, cx);
371        let future = self.request_limiter.stream(async move {
372            let response = request.await.map_err(|err| anyhow!(err))?;
373            Ok(anthropic::extract_text_from_events(response))
374        });
375        async move {
376            Ok(future
377                .await?
378                .map(|result| result.map_err(|err| anyhow!(err)))
379                .boxed())
380        }
381        .boxed()
382    }
383
384    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
385        self.model
386            .cache_configuration()
387            .map(|config| LanguageModelCacheConfiguration {
388                max_cache_anchors: config.max_cache_anchors,
389                should_speculate: config.should_speculate,
390                min_total_token: config.min_total_token,
391            })
392    }
393
394    fn use_any_tool(
395        &self,
396        request: LanguageModelRequest,
397        tool_name: String,
398        tool_description: String,
399        input_schema: serde_json::Value,
400        cx: &AsyncAppContext,
401    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
402        let mut request = request.into_anthropic(
403            self.model.tool_model_id().into(),
404            self.model.max_output_tokens(),
405        );
406        request.tool_choice = Some(anthropic::ToolChoice::Tool {
407            name: tool_name.clone(),
408        });
409        request.tools = vec![anthropic::Tool {
410            name: tool_name.clone(),
411            description: tool_description,
412            input_schema,
413        }];
414
415        let response = self.stream_completion(request, cx);
416        self.request_limiter
417            .run(async move {
418                let response = response.await?;
419                Ok(anthropic::extract_tool_args_from_events(
420                    tool_name,
421                    Box::pin(response.map_err(|e| anyhow!(e))),
422                )
423                .await?
424                .boxed())
425            })
426            .boxed()
427    }
428}
429
430struct ConfigurationView {
431    api_key_editor: View<Editor>,
432    state: gpui::Model<State>,
433    load_credentials_task: Option<Task<()>>,
434}
435
436impl ConfigurationView {
437    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
438
439    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
440        cx.observe(&state, |_, _, cx| {
441            cx.notify();
442        })
443        .detach();
444
445        let load_credentials_task = Some(cx.spawn({
446            let state = state.clone();
447            |this, mut cx| async move {
448                if let Some(task) = state
449                    .update(&mut cx, |state, cx| state.authenticate(cx))
450                    .log_err()
451                {
452                    // We don't log an error, because "not signed in" is also an error.
453                    let _ = task.await;
454                }
455                this.update(&mut cx, |this, cx| {
456                    this.load_credentials_task = None;
457                    cx.notify();
458                })
459                .log_err();
460            }
461        }));
462
463        Self {
464            api_key_editor: cx.new_view(|cx| {
465                let mut editor = Editor::single_line(cx);
466                editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
467                editor
468            }),
469            state,
470            load_credentials_task,
471        }
472    }
473
474    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
475        let api_key = self.api_key_editor.read(cx).text(cx);
476        if api_key.is_empty() {
477            return;
478        }
479
480        let state = self.state.clone();
481        cx.spawn(|_, mut cx| async move {
482            state
483                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
484                .await
485        })
486        .detach_and_log_err(cx);
487
488        cx.notify();
489    }
490
491    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
492        self.api_key_editor
493            .update(cx, |editor, cx| editor.set_text("", cx));
494
495        let state = self.state.clone();
496        cx.spawn(|_, mut cx| async move {
497            state
498                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
499                .await
500        })
501        .detach_and_log_err(cx);
502
503        cx.notify();
504    }
505
506    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
507        let settings = ThemeSettings::get_global(cx);
508        let text_style = TextStyle {
509            color: cx.theme().colors().text,
510            font_family: settings.ui_font.family.clone(),
511            font_features: settings.ui_font.features.clone(),
512            font_fallbacks: settings.ui_font.fallbacks.clone(),
513            font_size: rems(0.875).into(),
514            font_weight: settings.ui_font.weight,
515            font_style: FontStyle::Normal,
516            line_height: relative(1.3),
517            background_color: None,
518            underline: None,
519            strikethrough: None,
520            white_space: WhiteSpace::Normal,
521            truncate: None,
522        };
523        EditorElement::new(
524            &self.api_key_editor,
525            EditorStyle {
526                background: cx.theme().colors().editor_background,
527                local_player: cx.theme().players().local(),
528                text: text_style,
529                ..Default::default()
530            },
531        )
532    }
533
534    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
535        !self.state.read(cx).is_authenticated()
536    }
537}
538
539impl Render for ConfigurationView {
540    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
541        const INSTRUCTIONS: [&str; 4] = [
542            "To use the assistant panel or inline assistant, you need to add your Anthropic API key.",
543            "You can create an API key at: https://console.anthropic.com/settings/keys",
544            "",
545            "Paste your Anthropic API key below and hit enter to use the assistant:",
546        ];
547
548        let env_var_set = self.state.read(cx).api_key_from_env;
549
550        if self.load_credentials_task.is_some() {
551            div().child(Label::new("Loading credentials...")).into_any()
552        } else if self.should_render_editor(cx) {
553            v_flex()
554                .size_full()
555                .on_action(cx.listener(Self::save_api_key))
556                .children(
557                    INSTRUCTIONS.map(|instruction| Label::new(instruction)),
558                )
559                .child(
560                    h_flex()
561                        .w_full()
562                        .my_2()
563                        .px_2()
564                        .py_1()
565                        .bg(cx.theme().colors().editor_background)
566                        .rounded_md()
567                        .child(self.render_api_key_editor(cx)),
568                )
569                .child(
570                    Label::new(
571                        "You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed.",
572                    )
573                    .size(LabelSize::Small),
574                )
575                .into_any()
576        } else {
577            h_flex()
578                .size_full()
579                .justify_between()
580                .child(
581                    h_flex()
582                        .gap_1()
583                        .child(Icon::new(IconName::Check).color(Color::Success))
584                        .child(Label::new(if env_var_set {
585                            format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
586                        } else {
587                            "API key configured.".to_string()
588                        })),
589                )
590                .child(
591                    Button::new("reset-key", "Reset key")
592                        .icon(Some(IconName::Trash))
593                        .icon_size(IconSize::Small)
594                        .icon_position(IconPosition::Start)
595                        .disabled(env_var_set)
596                        .when(env_var_set, |this| {
597                            this.tooltip(|cx| Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable."), cx))
598                        })
599                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
600                )
601                .into_any()
602        }
603    }
604}