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