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