1use anthropic::{
2 ANTHROPIC_API_URL, AnthropicError, AnthropicModelMode, ContentDelta, CountTokensRequest, Event,
3 ResponseContent, ToolResultContent, ToolResultPart, Usage,
4};
5use anyhow::Result;
6use collections::{BTreeMap, HashMap};
7use futures::{FutureExt, Stream, StreamExt, future::BoxFuture, stream::BoxStream};
8use gpui::{AnyView, App, AsyncApp, Context, Entity, Task};
9use http_client::HttpClient;
10use language_model::{
11 ApiKeyState, AuthenticateError, ConfigurationViewTargetAgent, EnvVar, IconOrSvg, LanguageModel,
12 LanguageModelCacheConfiguration, LanguageModelCompletionError, LanguageModelCompletionEvent,
13 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
14 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
15 LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
16 RateLimiter, Role, StopReason, env_var,
17};
18use settings::{Settings, SettingsStore};
19use std::pin::Pin;
20use std::str::FromStr;
21use std::sync::{Arc, LazyLock};
22use strum::IntoEnumIterator;
23use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
24use ui_input::InputField;
25use util::ResultExt;
26
27use crate::provider::util::parse_tool_arguments;
28
29pub use settings::AnthropicAvailableModel as AvailableModel;
30
31const PROVIDER_ID: LanguageModelProviderId = language_model::ANTHROPIC_PROVIDER_ID;
32const PROVIDER_NAME: LanguageModelProviderName = language_model::ANTHROPIC_PROVIDER_NAME;
33
34#[derive(Default, Clone, Debug, PartialEq)]
35pub struct AnthropicSettings {
36 pub api_url: String,
37 /// Extend Zed's list of Anthropic models.
38 pub available_models: Vec<AvailableModel>,
39}
40
41pub struct AnthropicLanguageModelProvider {
42 http_client: Arc<dyn HttpClient>,
43 state: Entity<State>,
44}
45
46const API_KEY_ENV_VAR_NAME: &str = "ANTHROPIC_API_KEY";
47static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
48
49pub struct State {
50 api_key_state: ApiKeyState,
51}
52
53impl State {
54 fn is_authenticated(&self) -> bool {
55 self.api_key_state.has_key()
56 }
57
58 fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
59 let api_url = AnthropicLanguageModelProvider::api_url(cx);
60 self.api_key_state
61 .store(api_url, api_key, |this| &mut this.api_key_state, cx)
62 }
63
64 fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
65 let api_url = AnthropicLanguageModelProvider::api_url(cx);
66 self.api_key_state
67 .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
68 }
69}
70
71impl AnthropicLanguageModelProvider {
72 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
73 let state = cx.new(|cx| {
74 cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
75 let api_url = Self::api_url(cx);
76 this.api_key_state
77 .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
78 cx.notify();
79 })
80 .detach();
81 State {
82 api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
83 }
84 });
85
86 Self { http_client, state }
87 }
88
89 fn create_language_model(&self, model: anthropic::Model) -> Arc<dyn LanguageModel> {
90 Arc::new(AnthropicModel {
91 id: LanguageModelId::from(model.id().to_string()),
92 model,
93 state: self.state.clone(),
94 http_client: self.http_client.clone(),
95 request_limiter: RateLimiter::new(4),
96 })
97 }
98
99 fn settings(cx: &App) -> &AnthropicSettings {
100 &crate::AllLanguageModelSettings::get_global(cx).anthropic
101 }
102
103 fn api_url(cx: &App) -> SharedString {
104 let api_url = &Self::settings(cx).api_url;
105 if api_url.is_empty() {
106 ANTHROPIC_API_URL.into()
107 } else {
108 SharedString::new(api_url.as_str())
109 }
110 }
111}
112
113impl LanguageModelProviderState for AnthropicLanguageModelProvider {
114 type ObservableEntity = State;
115
116 fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
117 Some(self.state.clone())
118 }
119}
120
121impl LanguageModelProvider for AnthropicLanguageModelProvider {
122 fn id(&self) -> LanguageModelProviderId {
123 PROVIDER_ID
124 }
125
126 fn name(&self) -> LanguageModelProviderName {
127 PROVIDER_NAME
128 }
129
130 fn icon(&self) -> IconOrSvg {
131 IconOrSvg::Icon(IconName::AiAnthropic)
132 }
133
134 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
135 Some(self.create_language_model(anthropic::Model::default()))
136 }
137
138 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
139 Some(self.create_language_model(anthropic::Model::default_fast()))
140 }
141
142 fn recommended_models(&self, _cx: &App) -> Vec<Arc<dyn LanguageModel>> {
143 [
144 anthropic::Model::ClaudeSonnet4_6,
145 anthropic::Model::ClaudeSonnet4_6Thinking,
146 ]
147 .into_iter()
148 .map(|model| self.create_language_model(model))
149 .collect()
150 }
151
152 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
153 let mut models = BTreeMap::default();
154
155 // Add base models from anthropic::Model::iter()
156 for model in anthropic::Model::iter() {
157 if !matches!(model, anthropic::Model::Custom { .. }) {
158 models.insert(model.id().to_string(), model);
159 }
160 }
161
162 // Override with available models from settings
163 for model in &AnthropicLanguageModelProvider::settings(cx).available_models {
164 models.insert(
165 model.name.clone(),
166 anthropic::Model::Custom {
167 name: model.name.clone(),
168 display_name: model.display_name.clone(),
169 max_tokens: model.max_tokens,
170 tool_override: model.tool_override.clone(),
171 cache_configuration: model.cache_configuration.as_ref().map(|config| {
172 anthropic::AnthropicModelCacheConfiguration {
173 max_cache_anchors: config.max_cache_anchors,
174 should_speculate: config.should_speculate,
175 min_total_token: config.min_total_token,
176 }
177 }),
178 max_output_tokens: model.max_output_tokens,
179 default_temperature: model.default_temperature,
180 extra_beta_headers: model.extra_beta_headers.clone(),
181 mode: model.mode.unwrap_or_default().into(),
182 },
183 );
184 }
185
186 models
187 .into_values()
188 .map(|model| self.create_language_model(model))
189 .collect()
190 }
191
192 fn is_authenticated(&self, cx: &App) -> bool {
193 self.state.read(cx).is_authenticated()
194 }
195
196 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
197 self.state.update(cx, |state, cx| state.authenticate(cx))
198 }
199
200 fn configuration_view(
201 &self,
202 target_agent: ConfigurationViewTargetAgent,
203 window: &mut Window,
204 cx: &mut App,
205 ) -> AnyView {
206 cx.new(|cx| ConfigurationView::new(self.state.clone(), target_agent, window, cx))
207 .into()
208 }
209
210 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
211 self.state
212 .update(cx, |state, cx| state.set_api_key(None, cx))
213 }
214}
215
216pub struct AnthropicModel {
217 id: LanguageModelId,
218 model: anthropic::Model,
219 state: Entity<State>,
220 http_client: Arc<dyn HttpClient>,
221 request_limiter: RateLimiter,
222}
223
224fn to_anthropic_content(content: MessageContent) -> Option<anthropic::RequestContent> {
225 match content {
226 MessageContent::Text(text) => {
227 let text = if text.chars().last().is_some_and(|c| c.is_whitespace()) {
228 text.trim_end().to_string()
229 } else {
230 text
231 };
232 if !text.is_empty() {
233 Some(anthropic::RequestContent::Text {
234 text,
235 cache_control: None,
236 })
237 } else {
238 None
239 }
240 }
241 MessageContent::Thinking {
242 text: thinking,
243 signature,
244 } => {
245 if let Some(signature) = signature
246 && !thinking.is_empty()
247 {
248 Some(anthropic::RequestContent::Thinking {
249 thinking,
250 signature,
251 cache_control: None,
252 })
253 } else {
254 None
255 }
256 }
257 MessageContent::RedactedThinking(data) => {
258 if !data.is_empty() {
259 Some(anthropic::RequestContent::RedactedThinking { data })
260 } else {
261 None
262 }
263 }
264 MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
265 source: anthropic::ImageSource {
266 source_type: "base64".to_string(),
267 media_type: "image/png".to_string(),
268 data: image.source.to_string(),
269 },
270 cache_control: None,
271 }),
272 MessageContent::ToolUse(tool_use) => Some(anthropic::RequestContent::ToolUse {
273 id: tool_use.id.to_string(),
274 name: tool_use.name.to_string(),
275 input: tool_use.input,
276 cache_control: None,
277 }),
278 MessageContent::ToolResult(tool_result) => Some(anthropic::RequestContent::ToolResult {
279 tool_use_id: tool_result.tool_use_id.to_string(),
280 is_error: tool_result.is_error,
281 content: match tool_result.content {
282 LanguageModelToolResultContent::Text(text) => {
283 ToolResultContent::Plain(text.to_string())
284 }
285 LanguageModelToolResultContent::Image(image) => {
286 ToolResultContent::Multipart(vec![ToolResultPart::Image {
287 source: anthropic::ImageSource {
288 source_type: "base64".to_string(),
289 media_type: "image/png".to_string(),
290 data: image.source.to_string(),
291 },
292 }])
293 }
294 },
295 cache_control: None,
296 }),
297 }
298}
299
300/// Convert a LanguageModelRequest to an Anthropic CountTokensRequest.
301pub fn into_anthropic_count_tokens_request(
302 request: LanguageModelRequest,
303 model: String,
304 mode: AnthropicModelMode,
305) -> CountTokensRequest {
306 let mut new_messages: Vec<anthropic::Message> = Vec::new();
307 let mut system_message = String::new();
308
309 for message in request.messages {
310 if message.contents_empty() {
311 continue;
312 }
313
314 match message.role {
315 Role::User | Role::Assistant => {
316 let anthropic_message_content: Vec<anthropic::RequestContent> = message
317 .content
318 .into_iter()
319 .filter_map(to_anthropic_content)
320 .collect();
321 let anthropic_role = match message.role {
322 Role::User => anthropic::Role::User,
323 Role::Assistant => anthropic::Role::Assistant,
324 Role::System => unreachable!("System role should never occur here"),
325 };
326 if anthropic_message_content.is_empty() {
327 continue;
328 }
329
330 if let Some(last_message) = new_messages.last_mut()
331 && last_message.role == anthropic_role
332 {
333 last_message.content.extend(anthropic_message_content);
334 continue;
335 }
336
337 new_messages.push(anthropic::Message {
338 role: anthropic_role,
339 content: anthropic_message_content,
340 });
341 }
342 Role::System => {
343 if !system_message.is_empty() {
344 system_message.push_str("\n\n");
345 }
346 system_message.push_str(&message.string_contents());
347 }
348 }
349 }
350
351 CountTokensRequest {
352 model,
353 messages: new_messages,
354 system: if system_message.is_empty() {
355 None
356 } else {
357 Some(anthropic::StringOrContents::String(system_message))
358 },
359 thinking: if request.thinking_allowed
360 && let AnthropicModelMode::Thinking { budget_tokens } = mode
361 {
362 Some(anthropic::Thinking::Enabled { budget_tokens })
363 } else {
364 None
365 },
366 tools: request
367 .tools
368 .into_iter()
369 .map(|tool| anthropic::Tool {
370 name: tool.name,
371 description: tool.description,
372 input_schema: tool.input_schema,
373 })
374 .collect(),
375 tool_choice: request.tool_choice.map(|choice| match choice {
376 LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
377 LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
378 LanguageModelToolChoice::None => anthropic::ToolChoice::None,
379 }),
380 }
381}
382
383/// Estimate tokens using tiktoken. Used as a fallback when the API is unavailable,
384/// or by providers (like Zed Cloud) that don't have direct Anthropic API access.
385pub fn count_anthropic_tokens_with_tiktoken(request: LanguageModelRequest) -> Result<u64> {
386 let messages = request.messages;
387 let mut tokens_from_images = 0;
388 let mut string_messages = Vec::with_capacity(messages.len());
389
390 for message in messages {
391 let mut string_contents = String::new();
392
393 for content in message.content {
394 match content {
395 MessageContent::Text(text) => {
396 string_contents.push_str(&text);
397 }
398 MessageContent::Thinking { .. } => {
399 // Thinking blocks are not included in the input token count.
400 }
401 MessageContent::RedactedThinking(_) => {
402 // Thinking blocks are not included in the input token count.
403 }
404 MessageContent::Image(image) => {
405 tokens_from_images += image.estimate_tokens();
406 }
407 MessageContent::ToolUse(_tool_use) => {
408 // TODO: Estimate token usage from tool uses.
409 }
410 MessageContent::ToolResult(tool_result) => match &tool_result.content {
411 LanguageModelToolResultContent::Text(text) => {
412 string_contents.push_str(text);
413 }
414 LanguageModelToolResultContent::Image(image) => {
415 tokens_from_images += image.estimate_tokens();
416 }
417 },
418 }
419 }
420
421 if !string_contents.is_empty() {
422 string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
423 role: match message.role {
424 Role::User => "user".into(),
425 Role::Assistant => "assistant".into(),
426 Role::System => "system".into(),
427 },
428 content: Some(string_contents),
429 name: None,
430 function_call: None,
431 });
432 }
433 }
434
435 // Tiktoken doesn't yet support these models, so we manually use the
436 // same tokenizer as GPT-4.
437 tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
438 .map(|tokens| (tokens + tokens_from_images) as u64)
439}
440
441impl AnthropicModel {
442 fn stream_completion(
443 &self,
444 request: anthropic::Request,
445 cx: &AsyncApp,
446 ) -> BoxFuture<
447 'static,
448 Result<
449 BoxStream<'static, Result<anthropic::Event, AnthropicError>>,
450 LanguageModelCompletionError,
451 >,
452 > {
453 let http_client = self.http_client.clone();
454
455 let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
456 let api_url = AnthropicLanguageModelProvider::api_url(cx);
457 (state.api_key_state.key(&api_url), api_url)
458 });
459
460 let beta_headers = self.model.beta_headers();
461
462 async move {
463 let Some(api_key) = api_key else {
464 return Err(LanguageModelCompletionError::NoApiKey {
465 provider: PROVIDER_NAME,
466 });
467 };
468 let request = anthropic::stream_completion(
469 http_client.as_ref(),
470 &api_url,
471 &api_key,
472 request,
473 beta_headers,
474 );
475 request.await.map_err(Into::into)
476 }
477 .boxed()
478 }
479}
480
481impl LanguageModel for AnthropicModel {
482 fn id(&self) -> LanguageModelId {
483 self.id.clone()
484 }
485
486 fn name(&self) -> LanguageModelName {
487 LanguageModelName::from(self.model.display_name().to_string())
488 }
489
490 fn provider_id(&self) -> LanguageModelProviderId {
491 PROVIDER_ID
492 }
493
494 fn provider_name(&self) -> LanguageModelProviderName {
495 PROVIDER_NAME
496 }
497
498 fn supports_tools(&self) -> bool {
499 true
500 }
501
502 fn supports_images(&self) -> bool {
503 true
504 }
505
506 fn supports_streaming_tools(&self) -> bool {
507 true
508 }
509
510 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
511 match choice {
512 LanguageModelToolChoice::Auto
513 | LanguageModelToolChoice::Any
514 | LanguageModelToolChoice::None => true,
515 }
516 }
517
518 fn supports_thinking(&self) -> bool {
519 matches!(self.model.mode(), AnthropicModelMode::Thinking { .. })
520 }
521
522 fn telemetry_id(&self) -> String {
523 format!("anthropic/{}", self.model.id())
524 }
525
526 fn api_key(&self, cx: &App) -> Option<String> {
527 self.state.read_with(cx, |state, cx| {
528 let api_url = AnthropicLanguageModelProvider::api_url(cx);
529 state.api_key_state.key(&api_url).map(|key| key.to_string())
530 })
531 }
532
533 fn max_token_count(&self) -> u64 {
534 self.model.max_token_count()
535 }
536
537 fn max_output_tokens(&self) -> Option<u64> {
538 Some(self.model.max_output_tokens())
539 }
540
541 fn count_tokens(
542 &self,
543 request: LanguageModelRequest,
544 cx: &App,
545 ) -> BoxFuture<'static, Result<u64>> {
546 let http_client = self.http_client.clone();
547 let model_id = self.model.request_id().to_string();
548 let mode = self.model.mode();
549
550 let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
551 let api_url = AnthropicLanguageModelProvider::api_url(cx);
552 (
553 state.api_key_state.key(&api_url).map(|k| k.to_string()),
554 api_url.to_string(),
555 )
556 });
557
558 async move {
559 // If no API key, fall back to tiktoken estimation
560 let Some(api_key) = api_key else {
561 return count_anthropic_tokens_with_tiktoken(request);
562 };
563
564 let count_request =
565 into_anthropic_count_tokens_request(request.clone(), model_id, mode);
566
567 match anthropic::count_tokens(http_client.as_ref(), &api_url, &api_key, count_request)
568 .await
569 {
570 Ok(response) => Ok(response.input_tokens),
571 Err(err) => {
572 log::error!(
573 "Anthropic count_tokens API failed, falling back to tiktoken: {err:?}"
574 );
575 count_anthropic_tokens_with_tiktoken(request)
576 }
577 }
578 }
579 .boxed()
580 }
581
582 fn stream_completion(
583 &self,
584 request: LanguageModelRequest,
585 cx: &AsyncApp,
586 ) -> BoxFuture<
587 'static,
588 Result<
589 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
590 LanguageModelCompletionError,
591 >,
592 > {
593 let request = into_anthropic(
594 request,
595 self.model.request_id().into(),
596 self.model.default_temperature(),
597 self.model.max_output_tokens(),
598 self.model.mode(),
599 );
600 let request = self.stream_completion(request, cx);
601 let future = self.request_limiter.stream(async move {
602 let response = request.await?;
603 Ok(AnthropicEventMapper::new().map_stream(response))
604 });
605 async move { Ok(future.await?.boxed()) }.boxed()
606 }
607
608 fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
609 self.model
610 .cache_configuration()
611 .map(|config| LanguageModelCacheConfiguration {
612 max_cache_anchors: config.max_cache_anchors,
613 should_speculate: config.should_speculate,
614 min_total_token: config.min_total_token,
615 })
616 }
617}
618
619pub fn into_anthropic(
620 request: LanguageModelRequest,
621 model: String,
622 default_temperature: f32,
623 max_output_tokens: u64,
624 mode: AnthropicModelMode,
625) -> anthropic::Request {
626 let mut new_messages: Vec<anthropic::Message> = Vec::new();
627 let mut system_message = String::new();
628
629 for message in request.messages {
630 if message.contents_empty() {
631 continue;
632 }
633
634 match message.role {
635 Role::User | Role::Assistant => {
636 let mut anthropic_message_content: Vec<anthropic::RequestContent> = message
637 .content
638 .into_iter()
639 .filter_map(to_anthropic_content)
640 .collect();
641 let anthropic_role = match message.role {
642 Role::User => anthropic::Role::User,
643 Role::Assistant => anthropic::Role::Assistant,
644 Role::System => unreachable!("System role should never occur here"),
645 };
646 if anthropic_message_content.is_empty() {
647 continue;
648 }
649
650 if let Some(last_message) = new_messages.last_mut()
651 && last_message.role == anthropic_role
652 {
653 last_message.content.extend(anthropic_message_content);
654 continue;
655 }
656
657 // Mark the last segment of the message as cached
658 if message.cache {
659 let cache_control_value = Some(anthropic::CacheControl {
660 cache_type: anthropic::CacheControlType::Ephemeral,
661 });
662 for message_content in anthropic_message_content.iter_mut().rev() {
663 match message_content {
664 anthropic::RequestContent::RedactedThinking { .. } => {
665 // Caching is not possible, fallback to next message
666 }
667 anthropic::RequestContent::Text { cache_control, .. }
668 | anthropic::RequestContent::Thinking { cache_control, .. }
669 | anthropic::RequestContent::Image { cache_control, .. }
670 | anthropic::RequestContent::ToolUse { cache_control, .. }
671 | anthropic::RequestContent::ToolResult { cache_control, .. } => {
672 *cache_control = cache_control_value;
673 break;
674 }
675 }
676 }
677 }
678
679 new_messages.push(anthropic::Message {
680 role: anthropic_role,
681 content: anthropic_message_content,
682 });
683 }
684 Role::System => {
685 if !system_message.is_empty() {
686 system_message.push_str("\n\n");
687 }
688 system_message.push_str(&message.string_contents());
689 }
690 }
691 }
692
693 anthropic::Request {
694 model,
695 messages: new_messages,
696 max_tokens: max_output_tokens,
697 system: if system_message.is_empty() {
698 None
699 } else {
700 Some(anthropic::StringOrContents::String(system_message))
701 },
702 thinking: if request.thinking_allowed
703 && let AnthropicModelMode::Thinking { budget_tokens } = mode
704 {
705 Some(anthropic::Thinking::Enabled { budget_tokens })
706 } else {
707 None
708 },
709 tools: request
710 .tools
711 .into_iter()
712 .map(|tool| anthropic::Tool {
713 name: tool.name,
714 description: tool.description,
715 input_schema: tool.input_schema,
716 })
717 .collect(),
718 tool_choice: request.tool_choice.map(|choice| match choice {
719 LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
720 LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
721 LanguageModelToolChoice::None => anthropic::ToolChoice::None,
722 }),
723 metadata: None,
724 output_config: None,
725 stop_sequences: Vec::new(),
726 temperature: request.temperature.or(Some(default_temperature)),
727 top_k: None,
728 top_p: None,
729 }
730}
731
732pub struct AnthropicEventMapper {
733 tool_uses_by_index: HashMap<usize, RawToolUse>,
734 usage: Usage,
735 stop_reason: StopReason,
736}
737
738impl AnthropicEventMapper {
739 pub fn new() -> Self {
740 Self {
741 tool_uses_by_index: HashMap::default(),
742 usage: Usage::default(),
743 stop_reason: StopReason::EndTurn,
744 }
745 }
746
747 pub fn map_stream(
748 mut self,
749 events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
750 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
751 {
752 events.flat_map(move |event| {
753 futures::stream::iter(match event {
754 Ok(event) => self.map_event(event),
755 Err(error) => vec![Err(error.into())],
756 })
757 })
758 }
759
760 pub fn map_event(
761 &mut self,
762 event: Event,
763 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
764 match event {
765 Event::ContentBlockStart {
766 index,
767 content_block,
768 } => match content_block {
769 ResponseContent::Text { text } => {
770 vec![Ok(LanguageModelCompletionEvent::Text(text))]
771 }
772 ResponseContent::Thinking { thinking } => {
773 vec![Ok(LanguageModelCompletionEvent::Thinking {
774 text: thinking,
775 signature: None,
776 })]
777 }
778 ResponseContent::RedactedThinking { data } => {
779 vec![Ok(LanguageModelCompletionEvent::RedactedThinking { data })]
780 }
781 ResponseContent::ToolUse { id, name, .. } => {
782 self.tool_uses_by_index.insert(
783 index,
784 RawToolUse {
785 id,
786 name,
787 input_json: String::new(),
788 },
789 );
790 Vec::new()
791 }
792 },
793 Event::ContentBlockDelta { index, delta } => match delta {
794 ContentDelta::TextDelta { text } => {
795 vec![Ok(LanguageModelCompletionEvent::Text(text))]
796 }
797 ContentDelta::ThinkingDelta { thinking } => {
798 vec![Ok(LanguageModelCompletionEvent::Thinking {
799 text: thinking,
800 signature: None,
801 })]
802 }
803 ContentDelta::SignatureDelta { signature } => {
804 vec![Ok(LanguageModelCompletionEvent::Thinking {
805 text: "".to_string(),
806 signature: Some(signature),
807 })]
808 }
809 ContentDelta::InputJsonDelta { partial_json } => {
810 if let Some(tool_use) = self.tool_uses_by_index.get_mut(&index) {
811 tool_use.input_json.push_str(&partial_json);
812
813 // Try to convert invalid (incomplete) JSON into
814 // valid JSON that serde can accept, e.g. by closing
815 // unclosed delimiters. This way, we can update the
816 // UI with whatever has been streamed back so far.
817 if let Ok(input) = serde_json::Value::from_str(
818 &partial_json_fixer::fix_json(&tool_use.input_json),
819 ) {
820 return vec![Ok(LanguageModelCompletionEvent::ToolUse(
821 LanguageModelToolUse {
822 id: tool_use.id.clone().into(),
823 name: tool_use.name.clone().into(),
824 is_input_complete: false,
825 raw_input: tool_use.input_json.clone(),
826 input,
827 thought_signature: None,
828 },
829 ))];
830 }
831 }
832 vec![]
833 }
834 },
835 Event::ContentBlockStop { index } => {
836 if let Some(tool_use) = self.tool_uses_by_index.remove(&index) {
837 let input_json = tool_use.input_json.trim();
838 let event_result = match parse_tool_arguments(input_json) {
839 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
840 LanguageModelToolUse {
841 id: tool_use.id.into(),
842 name: tool_use.name.into(),
843 is_input_complete: true,
844 input,
845 raw_input: tool_use.input_json.clone(),
846 thought_signature: None,
847 },
848 )),
849 Err(json_parse_err) => {
850 Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
851 id: tool_use.id.into(),
852 tool_name: tool_use.name.into(),
853 raw_input: input_json.into(),
854 json_parse_error: json_parse_err.to_string(),
855 })
856 }
857 };
858
859 vec![event_result]
860 } else {
861 Vec::new()
862 }
863 }
864 Event::MessageStart { message } => {
865 update_usage(&mut self.usage, &message.usage);
866 vec![
867 Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
868 &self.usage,
869 ))),
870 Ok(LanguageModelCompletionEvent::StartMessage {
871 message_id: message.id,
872 }),
873 ]
874 }
875 Event::MessageDelta { delta, usage } => {
876 update_usage(&mut self.usage, &usage);
877 if let Some(stop_reason) = delta.stop_reason.as_deref() {
878 self.stop_reason = match stop_reason {
879 "end_turn" => StopReason::EndTurn,
880 "max_tokens" => StopReason::MaxTokens,
881 "tool_use" => StopReason::ToolUse,
882 "refusal" => StopReason::Refusal,
883 _ => {
884 log::error!("Unexpected anthropic stop_reason: {stop_reason}");
885 StopReason::EndTurn
886 }
887 };
888 }
889 vec![Ok(LanguageModelCompletionEvent::UsageUpdate(
890 convert_usage(&self.usage),
891 ))]
892 }
893 Event::MessageStop => {
894 vec![Ok(LanguageModelCompletionEvent::Stop(self.stop_reason))]
895 }
896 Event::Error { error } => {
897 vec![Err(error.into())]
898 }
899 _ => Vec::new(),
900 }
901 }
902}
903
904struct RawToolUse {
905 id: String,
906 name: String,
907 input_json: String,
908}
909
910/// Updates usage data by preferring counts from `new`.
911fn update_usage(usage: &mut Usage, new: &Usage) {
912 if let Some(input_tokens) = new.input_tokens {
913 usage.input_tokens = Some(input_tokens);
914 }
915 if let Some(output_tokens) = new.output_tokens {
916 usage.output_tokens = Some(output_tokens);
917 }
918 if let Some(cache_creation_input_tokens) = new.cache_creation_input_tokens {
919 usage.cache_creation_input_tokens = Some(cache_creation_input_tokens);
920 }
921 if let Some(cache_read_input_tokens) = new.cache_read_input_tokens {
922 usage.cache_read_input_tokens = Some(cache_read_input_tokens);
923 }
924}
925
926fn convert_usage(usage: &Usage) -> language_model::TokenUsage {
927 language_model::TokenUsage {
928 input_tokens: usage.input_tokens.unwrap_or(0),
929 output_tokens: usage.output_tokens.unwrap_or(0),
930 cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or(0),
931 cache_read_input_tokens: usage.cache_read_input_tokens.unwrap_or(0),
932 }
933}
934
935struct ConfigurationView {
936 api_key_editor: Entity<InputField>,
937 state: Entity<State>,
938 load_credentials_task: Option<Task<()>>,
939 target_agent: ConfigurationViewTargetAgent,
940}
941
942impl ConfigurationView {
943 const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
944
945 fn new(
946 state: Entity<State>,
947 target_agent: ConfigurationViewTargetAgent,
948 window: &mut Window,
949 cx: &mut Context<Self>,
950 ) -> Self {
951 cx.observe(&state, |_, _, cx| {
952 cx.notify();
953 })
954 .detach();
955
956 let load_credentials_task = Some(cx.spawn({
957 let state = state.clone();
958 async move |this, cx| {
959 let task = state.update(cx, |state, cx| state.authenticate(cx));
960 // We don't log an error, because "not signed in" is also an error.
961 let _ = task.await;
962 this.update(cx, |this, cx| {
963 this.load_credentials_task = None;
964 cx.notify();
965 })
966 .log_err();
967 }
968 }));
969
970 Self {
971 api_key_editor: cx.new(|cx| InputField::new(window, cx, Self::PLACEHOLDER_TEXT)),
972 state,
973 load_credentials_task,
974 target_agent,
975 }
976 }
977
978 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
979 let api_key = self.api_key_editor.read(cx).text(cx);
980 if api_key.is_empty() {
981 return;
982 }
983
984 // url changes can cause the editor to be displayed again
985 self.api_key_editor
986 .update(cx, |editor, cx| editor.set_text("", window, cx));
987
988 let state = self.state.clone();
989 cx.spawn_in(window, async move |_, cx| {
990 state
991 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
992 .await
993 })
994 .detach_and_log_err(cx);
995 }
996
997 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
998 self.api_key_editor
999 .update(cx, |editor, cx| editor.set_text("", window, cx));
1000
1001 let state = self.state.clone();
1002 cx.spawn_in(window, async move |_, cx| {
1003 state
1004 .update(cx, |state, cx| state.set_api_key(None, cx))
1005 .await
1006 })
1007 .detach_and_log_err(cx);
1008 }
1009
1010 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
1011 !self.state.read(cx).is_authenticated()
1012 }
1013}
1014
1015impl Render for ConfigurationView {
1016 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1017 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
1018 let configured_card_label = if env_var_set {
1019 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
1020 } else {
1021 let api_url = AnthropicLanguageModelProvider::api_url(cx);
1022 if api_url == ANTHROPIC_API_URL {
1023 "API key configured".to_string()
1024 } else {
1025 format!("API key configured for {}", api_url)
1026 }
1027 };
1028
1029 if self.load_credentials_task.is_some() {
1030 div()
1031 .child(Label::new("Loading credentials..."))
1032 .into_any_element()
1033 } else if self.should_render_editor(cx) {
1034 v_flex()
1035 .size_full()
1036 .on_action(cx.listener(Self::save_api_key))
1037 .child(Label::new(format!("To use {}, you need to add an API key. Follow these steps:", match &self.target_agent {
1038 ConfigurationViewTargetAgent::ZedAgent => "Zed's agent with Anthropic".into(),
1039 ConfigurationViewTargetAgent::Other(agent) => agent.clone(),
1040 })))
1041 .child(
1042 List::new()
1043 .child(
1044 ListBulletItem::new("")
1045 .child(Label::new("Create one by visiting"))
1046 .child(ButtonLink::new("Anthropic's settings", "https://console.anthropic.com/settings/keys"))
1047 )
1048 .child(
1049 ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
1050 )
1051 )
1052 .child(self.api_key_editor.clone())
1053 .child(
1054 Label::new(
1055 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
1056 )
1057 .size(LabelSize::Small)
1058 .color(Color::Muted)
1059 .mt_0p5(),
1060 )
1061 .into_any_element()
1062 } else {
1063 ConfiguredApiCard::new(configured_card_label)
1064 .disabled(env_var_set)
1065 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
1066 .when(env_var_set, |this| {
1067 this.tooltip_label(format!(
1068 "To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."
1069 ))
1070 })
1071 .into_any_element()
1072 }
1073 }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078 use super::*;
1079 use anthropic::AnthropicModelMode;
1080 use language_model::{LanguageModelRequestMessage, MessageContent};
1081
1082 #[test]
1083 fn test_cache_control_only_on_last_segment() {
1084 let request = LanguageModelRequest {
1085 messages: vec![LanguageModelRequestMessage {
1086 role: Role::User,
1087 content: vec![
1088 MessageContent::Text("Some prompt".to_string()),
1089 MessageContent::Image(language_model::LanguageModelImage::empty()),
1090 MessageContent::Image(language_model::LanguageModelImage::empty()),
1091 MessageContent::Image(language_model::LanguageModelImage::empty()),
1092 MessageContent::Image(language_model::LanguageModelImage::empty()),
1093 ],
1094 cache: true,
1095 reasoning_details: None,
1096 }],
1097 thread_id: None,
1098 prompt_id: None,
1099 intent: None,
1100 stop: vec![],
1101 temperature: None,
1102 tools: vec![],
1103 tool_choice: None,
1104 thinking_allowed: true,
1105 thinking_effort: None,
1106 };
1107
1108 let anthropic_request = into_anthropic(
1109 request,
1110 "claude-3-5-sonnet".to_string(),
1111 0.7,
1112 4096,
1113 AnthropicModelMode::Default,
1114 );
1115
1116 assert_eq!(anthropic_request.messages.len(), 1);
1117
1118 let message = &anthropic_request.messages[0];
1119 assert_eq!(message.content.len(), 5);
1120
1121 assert!(matches!(
1122 message.content[0],
1123 anthropic::RequestContent::Text {
1124 cache_control: None,
1125 ..
1126 }
1127 ));
1128 for i in 1..3 {
1129 assert!(matches!(
1130 message.content[i],
1131 anthropic::RequestContent::Image {
1132 cache_control: None,
1133 ..
1134 }
1135 ));
1136 }
1137
1138 assert!(matches!(
1139 message.content[4],
1140 anthropic::RequestContent::Image {
1141 cache_control: Some(anthropic::CacheControl {
1142 cache_type: anthropic::CacheControlType::Ephemeral,
1143 }),
1144 ..
1145 }
1146 ));
1147 }
1148
1149 fn request_with_assistant_content(
1150 assistant_content: Vec<MessageContent>,
1151 ) -> anthropic::Request {
1152 let mut request = LanguageModelRequest {
1153 messages: vec![LanguageModelRequestMessage {
1154 role: Role::User,
1155 content: vec![MessageContent::Text("Hello".to_string())],
1156 cache: false,
1157 reasoning_details: None,
1158 }],
1159 thinking_effort: None,
1160 thread_id: None,
1161 prompt_id: None,
1162 intent: None,
1163 stop: vec![],
1164 temperature: None,
1165 tools: vec![],
1166 tool_choice: None,
1167 thinking_allowed: true,
1168 };
1169 request.messages.push(LanguageModelRequestMessage {
1170 role: Role::Assistant,
1171 content: assistant_content,
1172 cache: false,
1173 reasoning_details: None,
1174 });
1175 into_anthropic(
1176 request,
1177 "claude-sonnet-4-5".to_string(),
1178 1.0,
1179 16000,
1180 AnthropicModelMode::Thinking {
1181 budget_tokens: Some(10000),
1182 },
1183 )
1184 }
1185
1186 #[test]
1187 fn test_unsigned_thinking_blocks_stripped() {
1188 let result = request_with_assistant_content(vec![
1189 MessageContent::Thinking {
1190 text: "Cancelled mid-think, no signature".to_string(),
1191 signature: None,
1192 },
1193 MessageContent::Text("Some response text".to_string()),
1194 ]);
1195
1196 let assistant_message = result
1197 .messages
1198 .iter()
1199 .find(|m| m.role == anthropic::Role::Assistant)
1200 .expect("assistant message should still exist");
1201
1202 assert_eq!(
1203 assistant_message.content.len(),
1204 1,
1205 "Only the text content should remain; unsigned thinking block should be stripped"
1206 );
1207 assert!(matches!(
1208 &assistant_message.content[0],
1209 anthropic::RequestContent::Text { text, .. } if text == "Some response text"
1210 ));
1211 }
1212
1213 #[test]
1214 fn test_signed_thinking_blocks_preserved() {
1215 let result = request_with_assistant_content(vec![
1216 MessageContent::Thinking {
1217 text: "Completed thinking".to_string(),
1218 signature: Some("valid-signature".to_string()),
1219 },
1220 MessageContent::Text("Response".to_string()),
1221 ]);
1222
1223 let assistant_message = result
1224 .messages
1225 .iter()
1226 .find(|m| m.role == anthropic::Role::Assistant)
1227 .expect("assistant message should exist");
1228
1229 assert_eq!(
1230 assistant_message.content.len(),
1231 2,
1232 "Both the signed thinking block and text should be preserved"
1233 );
1234 assert!(matches!(
1235 &assistant_message.content[0],
1236 anthropic::RequestContent::Thinking { thinking, signature, .. }
1237 if thinking == "Completed thinking" && signature == "valid-signature"
1238 ));
1239 }
1240
1241 #[test]
1242 fn test_only_unsigned_thinking_block_omits_entire_message() {
1243 let result = request_with_assistant_content(vec![MessageContent::Thinking {
1244 text: "Cancelled before any text or signature".to_string(),
1245 signature: None,
1246 }]);
1247
1248 let assistant_messages: Vec<_> = result
1249 .messages
1250 .iter()
1251 .filter(|m| m.role == anthropic::Role::Assistant)
1252 .collect();
1253
1254 assert_eq!(
1255 assistant_messages.len(),
1256 0,
1257 "An assistant message whose only content was an unsigned thinking block \
1258 should be omitted entirely"
1259 );
1260 }
1261}