1use crate::AllLanguageModelSettings;
2use anthropic::{AnthropicError, ContentDelta, Event, ResponseContent};
3use anyhow::{anyhow, Context as _, Result};
4use collections::{BTreeMap, HashMap};
5use editor::{Editor, EditorElement, EditorStyle};
6use futures::Stream;
7use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryStreamExt as _};
8use gpui::{
9 AnyView, AppContext, AsyncAppContext, FontStyle, ModelContext, Subscription, Task, TextStyle,
10 View, WhiteSpace,
11};
12use http_client::HttpClient;
13use language_model::{
14 LanguageModel, LanguageModelCacheConfiguration, LanguageModelId, LanguageModelName,
15 LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
16 LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
17};
18use language_model::{LanguageModelCompletionEvent, LanguageModelToolUse, StopReason};
19use schemars::JsonSchema;
20use serde::{Deserialize, Serialize};
21use settings::{Settings, SettingsStore};
22use std::pin::Pin;
23use std::str::FromStr;
24use std::sync::Arc;
25use strum::IntoEnumIterator;
26use theme::ThemeSettings;
27use ui::{prelude::*, Icon, IconName, Tooltip};
28use util::{maybe, ResultExt};
29
30pub const PROVIDER_ID: &str = "anthropic";
31const PROVIDER_NAME: &str = "Anthropic";
32
33#[derive(Default, Clone, Debug, PartialEq)]
34pub struct AnthropicSettings {
35 pub api_url: String,
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-latest, claude-3-opus-20240229, etc
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 language_model::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)) = cx.read_model(&self.state, |state, cx| {
313 let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
314 (state.api_key.clone(), settings.api_url.clone())
315 }) else {
316 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
317 };
318
319 async move {
320 let api_key = api_key.ok_or_else(|| anyhow!("Missing Anthropic API Key"))?;
321 let request =
322 anthropic::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
323 request.await.context("failed to stream completion")
324 }
325 .boxed()
326 }
327}
328
329impl LanguageModel for AnthropicModel {
330 fn id(&self) -> LanguageModelId {
331 self.id.clone()
332 }
333
334 fn name(&self) -> LanguageModelName {
335 LanguageModelName::from(self.model.display_name().to_string())
336 }
337
338 fn provider_id(&self) -> LanguageModelProviderId {
339 LanguageModelProviderId(PROVIDER_ID.into())
340 }
341
342 fn provider_name(&self) -> LanguageModelProviderName {
343 LanguageModelProviderName(PROVIDER_NAME.into())
344 }
345
346 fn telemetry_id(&self) -> String {
347 format!("anthropic/{}", self.model.id())
348 }
349
350 fn api_key(&self, cx: &AppContext) -> Option<String> {
351 self.state.read(cx).api_key.clone()
352 }
353
354 fn max_token_count(&self) -> usize {
355 self.model.max_token_count()
356 }
357
358 fn max_output_tokens(&self) -> Option<u32> {
359 Some(self.model.max_output_tokens())
360 }
361
362 fn count_tokens(
363 &self,
364 request: LanguageModelRequest,
365 cx: &AppContext,
366 ) -> BoxFuture<'static, Result<usize>> {
367 count_anthropic_tokens(request, cx)
368 }
369
370 fn stream_completion(
371 &self,
372 request: LanguageModelRequest,
373 cx: &AsyncAppContext,
374 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
375 let request = request.into_anthropic(
376 self.model.id().into(),
377 self.model.default_temperature(),
378 self.model.max_output_tokens(),
379 );
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.default_temperature(),
409 self.model.max_output_tokens(),
410 );
411 request.tool_choice = Some(anthropic::ToolChoice::Tool {
412 name: tool_name.clone(),
413 });
414 request.tools = vec![anthropic::Tool {
415 name: tool_name.clone(),
416 description: tool_description,
417 input_schema,
418 }];
419
420 let response = self.stream_completion(request, cx);
421 self.request_limiter
422 .run(async move {
423 let response = response.await?;
424 Ok(anthropic::extract_tool_args_from_events(
425 tool_name,
426 Box::pin(response.map_err(|e| anyhow!(e))),
427 )
428 .await?
429 .boxed())
430 })
431 .boxed()
432 }
433}
434
435pub fn map_to_language_model_completion_events(
436 events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
437) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
438 struct RawToolUse {
439 id: String,
440 name: String,
441 input_json: String,
442 }
443
444 struct State {
445 events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
446 tool_uses_by_index: HashMap<usize, RawToolUse>,
447 }
448
449 futures::stream::unfold(
450 State {
451 events,
452 tool_uses_by_index: HashMap::default(),
453 },
454 |mut state| async move {
455 while let Some(event) = state.events.next().await {
456 match event {
457 Ok(event) => match event {
458 Event::ContentBlockStart {
459 index,
460 content_block,
461 } => match content_block {
462 ResponseContent::Text { text } => {
463 return Some((
464 Some(Ok(LanguageModelCompletionEvent::Text(text))),
465 state,
466 ));
467 }
468 ResponseContent::ToolUse { id, name, .. } => {
469 state.tool_uses_by_index.insert(
470 index,
471 RawToolUse {
472 id,
473 name,
474 input_json: String::new(),
475 },
476 );
477
478 return Some((None, state));
479 }
480 },
481 Event::ContentBlockDelta { index, delta } => match delta {
482 ContentDelta::TextDelta { text } => {
483 return Some((
484 Some(Ok(LanguageModelCompletionEvent::Text(text))),
485 state,
486 ));
487 }
488 ContentDelta::InputJsonDelta { partial_json } => {
489 if let Some(tool_use) = state.tool_uses_by_index.get_mut(&index) {
490 tool_use.input_json.push_str(&partial_json);
491 return Some((None, state));
492 }
493 }
494 },
495 Event::ContentBlockStop { index } => {
496 if let Some(tool_use) = state.tool_uses_by_index.remove(&index) {
497 return Some((
498 Some(maybe!({
499 Ok(LanguageModelCompletionEvent::ToolUse(
500 LanguageModelToolUse {
501 id: tool_use.id.into(),
502 name: tool_use.name,
503 input: if tool_use.input_json.is_empty() {
504 serde_json::Value::Null
505 } else {
506 serde_json::Value::from_str(
507 &tool_use.input_json,
508 )
509 .map_err(|err| anyhow!(err))?
510 },
511 },
512 ))
513 })),
514 state,
515 ));
516 }
517 }
518 Event::MessageStart { message } => {
519 return Some((
520 Some(Ok(LanguageModelCompletionEvent::StartMessage {
521 message_id: message.id,
522 })),
523 state,
524 ))
525 }
526 Event::MessageDelta { delta, .. } => {
527 if let Some(stop_reason) = delta.stop_reason.as_deref() {
528 let stop_reason = match stop_reason {
529 "end_turn" => StopReason::EndTurn,
530 "max_tokens" => StopReason::MaxTokens,
531 "tool_use" => StopReason::ToolUse,
532 _ => StopReason::EndTurn,
533 };
534
535 return Some((
536 Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason))),
537 state,
538 ));
539 }
540 }
541 Event::Error { error } => {
542 return Some((
543 Some(Err(anyhow!(AnthropicError::ApiError(error)))),
544 state,
545 ));
546 }
547 _ => {}
548 },
549 Err(err) => {
550 return Some((Some(Err(anyhow!(err))), state));
551 }
552 }
553 }
554
555 None
556 },
557 )
558 .filter_map(|event| async move { event })
559}
560
561struct ConfigurationView {
562 api_key_editor: View<Editor>,
563 state: gpui::Model<State>,
564 load_credentials_task: Option<Task<()>>,
565}
566
567impl ConfigurationView {
568 const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
569
570 fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
571 cx.observe(&state, |_, _, cx| {
572 cx.notify();
573 })
574 .detach();
575
576 let load_credentials_task = Some(cx.spawn({
577 let state = state.clone();
578 |this, mut cx| async move {
579 if let Some(task) = state
580 .update(&mut cx, |state, cx| state.authenticate(cx))
581 .log_err()
582 {
583 // We don't log an error, because "not signed in" is also an error.
584 let _ = task.await;
585 }
586 this.update(&mut cx, |this, cx| {
587 this.load_credentials_task = None;
588 cx.notify();
589 })
590 .log_err();
591 }
592 }));
593
594 Self {
595 api_key_editor: cx.new_view(|cx| {
596 let mut editor = Editor::single_line(cx);
597 editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
598 editor
599 }),
600 state,
601 load_credentials_task,
602 }
603 }
604
605 fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
606 let api_key = self.api_key_editor.read(cx).text(cx);
607 if api_key.is_empty() {
608 return;
609 }
610
611 let state = self.state.clone();
612 cx.spawn(|_, mut cx| async move {
613 state
614 .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
615 .await
616 })
617 .detach_and_log_err(cx);
618
619 cx.notify();
620 }
621
622 fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
623 self.api_key_editor
624 .update(cx, |editor, cx| editor.set_text("", cx));
625
626 let state = self.state.clone();
627 cx.spawn(|_, mut cx| async move {
628 state
629 .update(&mut cx, |state, cx| state.reset_api_key(cx))?
630 .await
631 })
632 .detach_and_log_err(cx);
633
634 cx.notify();
635 }
636
637 fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
638 let settings = ThemeSettings::get_global(cx);
639 let text_style = TextStyle {
640 color: cx.theme().colors().text,
641 font_family: settings.ui_font.family.clone(),
642 font_features: settings.ui_font.features.clone(),
643 font_fallbacks: settings.ui_font.fallbacks.clone(),
644 font_size: rems(0.875).into(),
645 font_weight: settings.ui_font.weight,
646 font_style: FontStyle::Normal,
647 line_height: relative(1.3),
648 background_color: None,
649 underline: None,
650 strikethrough: None,
651 white_space: WhiteSpace::Normal,
652 truncate: None,
653 };
654 EditorElement::new(
655 &self.api_key_editor,
656 EditorStyle {
657 background: cx.theme().colors().editor_background,
658 local_player: cx.theme().players().local(),
659 text: text_style,
660 ..Default::default()
661 },
662 )
663 }
664
665 fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
666 !self.state.read(cx).is_authenticated()
667 }
668}
669
670impl Render for ConfigurationView {
671 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
672 const ANTHROPIC_CONSOLE_URL: &str = "https://console.anthropic.com/settings/keys";
673 const INSTRUCTIONS: [&str; 3] = [
674 "To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:",
675 "- Create one at:",
676 "- Paste your API key below and hit enter to use the assistant:",
677 ];
678 let env_var_set = self.state.read(cx).api_key_from_env;
679
680 if self.load_credentials_task.is_some() {
681 div().child(Label::new("Loading credentials...")).into_any()
682 } else if self.should_render_editor(cx) {
683 v_flex()
684 .size_full()
685 .on_action(cx.listener(Self::save_api_key))
686 .child(Label::new(INSTRUCTIONS[0]))
687 .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
688 Button::new("anthropic_console", ANTHROPIC_CONSOLE_URL)
689 .style(ButtonStyle::Subtle)
690 .icon(IconName::ExternalLink)
691 .icon_size(IconSize::XSmall)
692 .icon_color(Color::Muted)
693 .on_click(move |_, cx| cx.open_url(ANTHROPIC_CONSOLE_URL))
694 )
695 )
696 .child(Label::new(INSTRUCTIONS[2]))
697 .child(
698 h_flex()
699 .w_full()
700 .my_2()
701 .px_2()
702 .py_1()
703 .bg(cx.theme().colors().editor_background)
704 .rounded_md()
705 .child(self.render_api_key_editor(cx)),
706 )
707 .child(
708 Label::new(
709 format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
710 )
711 .size(LabelSize::Small),
712 )
713 .into_any()
714 } else {
715 h_flex()
716 .size_full()
717 .justify_between()
718 .child(
719 h_flex()
720 .gap_1()
721 .child(Icon::new(IconName::Check).color(Color::Success))
722 .child(Label::new(if env_var_set {
723 format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
724 } else {
725 "API key configured.".to_string()
726 })),
727 )
728 .child(
729 Button::new("reset-key", "Reset key")
730 .icon(Some(IconName::Trash))
731 .icon_size(IconSize::Small)
732 .icon_position(IconPosition::Start)
733 .disabled(env_var_set)
734 .when(env_var_set, |this| {
735 this.tooltip(|cx| Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable."), cx))
736 })
737 .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
738 )
739 .into_any()
740 }
741 }
742}