anthropic.rs

   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_5,
 145            anthropic::Model::ClaudeSonnet4_5Thinking,
 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 telemetry_id(&self) -> String {
 519        format!("anthropic/{}", self.model.id())
 520    }
 521
 522    fn api_key(&self, cx: &App) -> Option<String> {
 523        self.state.read_with(cx, |state, cx| {
 524            let api_url = AnthropicLanguageModelProvider::api_url(cx);
 525            state.api_key_state.key(&api_url).map(|key| key.to_string())
 526        })
 527    }
 528
 529    fn max_token_count(&self) -> u64 {
 530        self.model.max_token_count()
 531    }
 532
 533    fn max_output_tokens(&self) -> Option<u64> {
 534        Some(self.model.max_output_tokens())
 535    }
 536
 537    fn count_tokens(
 538        &self,
 539        request: LanguageModelRequest,
 540        cx: &App,
 541    ) -> BoxFuture<'static, Result<u64>> {
 542        let http_client = self.http_client.clone();
 543        let model_id = self.model.request_id().to_string();
 544        let mode = self.model.mode();
 545
 546        let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
 547            let api_url = AnthropicLanguageModelProvider::api_url(cx);
 548            (
 549                state.api_key_state.key(&api_url).map(|k| k.to_string()),
 550                api_url.to_string(),
 551            )
 552        });
 553
 554        async move {
 555            // If no API key, fall back to tiktoken estimation
 556            let Some(api_key) = api_key else {
 557                return count_anthropic_tokens_with_tiktoken(request);
 558            };
 559
 560            let count_request =
 561                into_anthropic_count_tokens_request(request.clone(), model_id, mode);
 562
 563            match anthropic::count_tokens(http_client.as_ref(), &api_url, &api_key, count_request)
 564                .await
 565            {
 566                Ok(response) => Ok(response.input_tokens),
 567                Err(err) => {
 568                    log::error!(
 569                        "Anthropic count_tokens API failed, falling back to tiktoken: {err:?}"
 570                    );
 571                    count_anthropic_tokens_with_tiktoken(request)
 572                }
 573            }
 574        }
 575        .boxed()
 576    }
 577
 578    fn stream_completion(
 579        &self,
 580        request: LanguageModelRequest,
 581        cx: &AsyncApp,
 582    ) -> BoxFuture<
 583        'static,
 584        Result<
 585            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 586            LanguageModelCompletionError,
 587        >,
 588    > {
 589        let request = into_anthropic(
 590            request,
 591            self.model.request_id().into(),
 592            self.model.default_temperature(),
 593            self.model.max_output_tokens(),
 594            self.model.mode(),
 595        );
 596        let request = self.stream_completion(request, cx);
 597        let future = self.request_limiter.stream(async move {
 598            let response = request.await?;
 599            Ok(AnthropicEventMapper::new().map_stream(response))
 600        });
 601        async move { Ok(future.await?.boxed()) }.boxed()
 602    }
 603
 604    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
 605        self.model
 606            .cache_configuration()
 607            .map(|config| LanguageModelCacheConfiguration {
 608                max_cache_anchors: config.max_cache_anchors,
 609                should_speculate: config.should_speculate,
 610                min_total_token: config.min_total_token,
 611            })
 612    }
 613}
 614
 615pub fn into_anthropic(
 616    request: LanguageModelRequest,
 617    model: String,
 618    default_temperature: f32,
 619    max_output_tokens: u64,
 620    mode: AnthropicModelMode,
 621) -> anthropic::Request {
 622    let mut new_messages: Vec<anthropic::Message> = Vec::new();
 623    let mut system_message = String::new();
 624
 625    for message in request.messages {
 626        if message.contents_empty() {
 627            continue;
 628        }
 629
 630        match message.role {
 631            Role::User | Role::Assistant => {
 632                let mut anthropic_message_content: Vec<anthropic::RequestContent> = message
 633                    .content
 634                    .into_iter()
 635                    .filter_map(to_anthropic_content)
 636                    .collect();
 637                let anthropic_role = match message.role {
 638                    Role::User => anthropic::Role::User,
 639                    Role::Assistant => anthropic::Role::Assistant,
 640                    Role::System => unreachable!("System role should never occur here"),
 641                };
 642                if anthropic_message_content.is_empty() {
 643                    continue;
 644                }
 645
 646                if let Some(last_message) = new_messages.last_mut()
 647                    && last_message.role == anthropic_role
 648                {
 649                    last_message.content.extend(anthropic_message_content);
 650                    continue;
 651                }
 652
 653                // Mark the last segment of the message as cached
 654                if message.cache {
 655                    let cache_control_value = Some(anthropic::CacheControl {
 656                        cache_type: anthropic::CacheControlType::Ephemeral,
 657                    });
 658                    for message_content in anthropic_message_content.iter_mut().rev() {
 659                        match message_content {
 660                            anthropic::RequestContent::RedactedThinking { .. } => {
 661                                // Caching is not possible, fallback to next message
 662                            }
 663                            anthropic::RequestContent::Text { cache_control, .. }
 664                            | anthropic::RequestContent::Thinking { cache_control, .. }
 665                            | anthropic::RequestContent::Image { cache_control, .. }
 666                            | anthropic::RequestContent::ToolUse { cache_control, .. }
 667                            | anthropic::RequestContent::ToolResult { cache_control, .. } => {
 668                                *cache_control = cache_control_value;
 669                                break;
 670                            }
 671                        }
 672                    }
 673                }
 674
 675                new_messages.push(anthropic::Message {
 676                    role: anthropic_role,
 677                    content: anthropic_message_content,
 678                });
 679            }
 680            Role::System => {
 681                if !system_message.is_empty() {
 682                    system_message.push_str("\n\n");
 683                }
 684                system_message.push_str(&message.string_contents());
 685            }
 686        }
 687    }
 688
 689    anthropic::Request {
 690        model,
 691        messages: new_messages,
 692        max_tokens: max_output_tokens,
 693        system: if system_message.is_empty() {
 694            None
 695        } else {
 696            Some(anthropic::StringOrContents::String(system_message))
 697        },
 698        thinking: if request.thinking_allowed
 699            && let AnthropicModelMode::Thinking { budget_tokens } = mode
 700        {
 701            Some(anthropic::Thinking::Enabled { budget_tokens })
 702        } else {
 703            None
 704        },
 705        tools: request
 706            .tools
 707            .into_iter()
 708            .map(|tool| anthropic::Tool {
 709                name: tool.name,
 710                description: tool.description,
 711                input_schema: tool.input_schema,
 712            })
 713            .collect(),
 714        tool_choice: request.tool_choice.map(|choice| match choice {
 715            LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
 716            LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
 717            LanguageModelToolChoice::None => anthropic::ToolChoice::None,
 718        }),
 719        metadata: None,
 720        output_config: None,
 721        stop_sequences: Vec::new(),
 722        temperature: request.temperature.or(Some(default_temperature)),
 723        top_k: None,
 724        top_p: None,
 725    }
 726}
 727
 728pub struct AnthropicEventMapper {
 729    tool_uses_by_index: HashMap<usize, RawToolUse>,
 730    usage: Usage,
 731    stop_reason: StopReason,
 732}
 733
 734impl AnthropicEventMapper {
 735    pub fn new() -> Self {
 736        Self {
 737            tool_uses_by_index: HashMap::default(),
 738            usage: Usage::default(),
 739            stop_reason: StopReason::EndTurn,
 740        }
 741    }
 742
 743    pub fn map_stream(
 744        mut self,
 745        events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
 746    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 747    {
 748        events.flat_map(move |event| {
 749            futures::stream::iter(match event {
 750                Ok(event) => self.map_event(event),
 751                Err(error) => vec![Err(error.into())],
 752            })
 753        })
 754    }
 755
 756    pub fn map_event(
 757        &mut self,
 758        event: Event,
 759    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 760        match event {
 761            Event::ContentBlockStart {
 762                index,
 763                content_block,
 764            } => match content_block {
 765                ResponseContent::Text { text } => {
 766                    vec![Ok(LanguageModelCompletionEvent::Text(text))]
 767                }
 768                ResponseContent::Thinking { thinking } => {
 769                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 770                        text: thinking,
 771                        signature: None,
 772                    })]
 773                }
 774                ResponseContent::RedactedThinking { data } => {
 775                    vec![Ok(LanguageModelCompletionEvent::RedactedThinking { data })]
 776                }
 777                ResponseContent::ToolUse { id, name, .. } => {
 778                    self.tool_uses_by_index.insert(
 779                        index,
 780                        RawToolUse {
 781                            id,
 782                            name,
 783                            input_json: String::new(),
 784                        },
 785                    );
 786                    Vec::new()
 787                }
 788            },
 789            Event::ContentBlockDelta { index, delta } => match delta {
 790                ContentDelta::TextDelta { text } => {
 791                    vec![Ok(LanguageModelCompletionEvent::Text(text))]
 792                }
 793                ContentDelta::ThinkingDelta { thinking } => {
 794                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 795                        text: thinking,
 796                        signature: None,
 797                    })]
 798                }
 799                ContentDelta::SignatureDelta { signature } => {
 800                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 801                        text: "".to_string(),
 802                        signature: Some(signature),
 803                    })]
 804                }
 805                ContentDelta::InputJsonDelta { partial_json } => {
 806                    if let Some(tool_use) = self.tool_uses_by_index.get_mut(&index) {
 807                        tool_use.input_json.push_str(&partial_json);
 808
 809                        // Try to convert invalid (incomplete) JSON into
 810                        // valid JSON that serde can accept, e.g. by closing
 811                        // unclosed delimiters. This way, we can update the
 812                        // UI with whatever has been streamed back so far.
 813                        if let Ok(input) = serde_json::Value::from_str(
 814                            &partial_json_fixer::fix_json(&tool_use.input_json),
 815                        ) {
 816                            return vec![Ok(LanguageModelCompletionEvent::ToolUse(
 817                                LanguageModelToolUse {
 818                                    id: tool_use.id.clone().into(),
 819                                    name: tool_use.name.clone().into(),
 820                                    is_input_complete: false,
 821                                    raw_input: tool_use.input_json.clone(),
 822                                    input,
 823                                    thought_signature: None,
 824                                },
 825                            ))];
 826                        }
 827                    }
 828                    vec![]
 829                }
 830            },
 831            Event::ContentBlockStop { index } => {
 832                if let Some(tool_use) = self.tool_uses_by_index.remove(&index) {
 833                    let input_json = tool_use.input_json.trim();
 834                    let event_result = match parse_tool_arguments(input_json) {
 835                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
 836                            LanguageModelToolUse {
 837                                id: tool_use.id.into(),
 838                                name: tool_use.name.into(),
 839                                is_input_complete: true,
 840                                input,
 841                                raw_input: tool_use.input_json.clone(),
 842                                thought_signature: None,
 843                            },
 844                        )),
 845                        Err(json_parse_err) => {
 846                            Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
 847                                id: tool_use.id.into(),
 848                                tool_name: tool_use.name.into(),
 849                                raw_input: input_json.into(),
 850                                json_parse_error: json_parse_err.to_string(),
 851                            })
 852                        }
 853                    };
 854
 855                    vec![event_result]
 856                } else {
 857                    Vec::new()
 858                }
 859            }
 860            Event::MessageStart { message } => {
 861                update_usage(&mut self.usage, &message.usage);
 862                vec![
 863                    Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
 864                        &self.usage,
 865                    ))),
 866                    Ok(LanguageModelCompletionEvent::StartMessage {
 867                        message_id: message.id,
 868                    }),
 869                ]
 870            }
 871            Event::MessageDelta { delta, usage } => {
 872                update_usage(&mut self.usage, &usage);
 873                if let Some(stop_reason) = delta.stop_reason.as_deref() {
 874                    self.stop_reason = match stop_reason {
 875                        "end_turn" => StopReason::EndTurn,
 876                        "max_tokens" => StopReason::MaxTokens,
 877                        "tool_use" => StopReason::ToolUse,
 878                        "refusal" => StopReason::Refusal,
 879                        _ => {
 880                            log::error!("Unexpected anthropic stop_reason: {stop_reason}");
 881                            StopReason::EndTurn
 882                        }
 883                    };
 884                }
 885                vec![Ok(LanguageModelCompletionEvent::UsageUpdate(
 886                    convert_usage(&self.usage),
 887                ))]
 888            }
 889            Event::MessageStop => {
 890                vec![Ok(LanguageModelCompletionEvent::Stop(self.stop_reason))]
 891            }
 892            Event::Error { error } => {
 893                vec![Err(error.into())]
 894            }
 895            _ => Vec::new(),
 896        }
 897    }
 898}
 899
 900struct RawToolUse {
 901    id: String,
 902    name: String,
 903    input_json: String,
 904}
 905
 906/// Updates usage data by preferring counts from `new`.
 907fn update_usage(usage: &mut Usage, new: &Usage) {
 908    if let Some(input_tokens) = new.input_tokens {
 909        usage.input_tokens = Some(input_tokens);
 910    }
 911    if let Some(output_tokens) = new.output_tokens {
 912        usage.output_tokens = Some(output_tokens);
 913    }
 914    if let Some(cache_creation_input_tokens) = new.cache_creation_input_tokens {
 915        usage.cache_creation_input_tokens = Some(cache_creation_input_tokens);
 916    }
 917    if let Some(cache_read_input_tokens) = new.cache_read_input_tokens {
 918        usage.cache_read_input_tokens = Some(cache_read_input_tokens);
 919    }
 920}
 921
 922fn convert_usage(usage: &Usage) -> language_model::TokenUsage {
 923    language_model::TokenUsage {
 924        input_tokens: usage.input_tokens.unwrap_or(0),
 925        output_tokens: usage.output_tokens.unwrap_or(0),
 926        cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or(0),
 927        cache_read_input_tokens: usage.cache_read_input_tokens.unwrap_or(0),
 928    }
 929}
 930
 931struct ConfigurationView {
 932    api_key_editor: Entity<InputField>,
 933    state: Entity<State>,
 934    load_credentials_task: Option<Task<()>>,
 935    target_agent: ConfigurationViewTargetAgent,
 936}
 937
 938impl ConfigurationView {
 939    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
 940
 941    fn new(
 942        state: Entity<State>,
 943        target_agent: ConfigurationViewTargetAgent,
 944        window: &mut Window,
 945        cx: &mut Context<Self>,
 946    ) -> Self {
 947        cx.observe(&state, |_, _, cx| {
 948            cx.notify();
 949        })
 950        .detach();
 951
 952        let load_credentials_task = Some(cx.spawn({
 953            let state = state.clone();
 954            async move |this, cx| {
 955                let task = state.update(cx, |state, cx| state.authenticate(cx));
 956                // We don't log an error, because "not signed in" is also an error.
 957                let _ = task.await;
 958                this.update(cx, |this, cx| {
 959                    this.load_credentials_task = None;
 960                    cx.notify();
 961                })
 962                .log_err();
 963            }
 964        }));
 965
 966        Self {
 967            api_key_editor: cx.new(|cx| InputField::new(window, cx, Self::PLACEHOLDER_TEXT)),
 968            state,
 969            load_credentials_task,
 970            target_agent,
 971        }
 972    }
 973
 974    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 975        let api_key = self.api_key_editor.read(cx).text(cx);
 976        if api_key.is_empty() {
 977            return;
 978        }
 979
 980        // url changes can cause the editor to be displayed again
 981        self.api_key_editor
 982            .update(cx, |editor, cx| editor.set_text("", window, cx));
 983
 984        let state = self.state.clone();
 985        cx.spawn_in(window, async move |_, cx| {
 986            state
 987                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
 988                .await
 989        })
 990        .detach_and_log_err(cx);
 991    }
 992
 993    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 994        self.api_key_editor
 995            .update(cx, |editor, cx| editor.set_text("", window, cx));
 996
 997        let state = self.state.clone();
 998        cx.spawn_in(window, async move |_, cx| {
 999            state
1000                .update(cx, |state, cx| state.set_api_key(None, cx))
1001                .await
1002        })
1003        .detach_and_log_err(cx);
1004    }
1005
1006    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
1007        !self.state.read(cx).is_authenticated()
1008    }
1009}
1010
1011impl Render for ConfigurationView {
1012    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1013        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
1014        let configured_card_label = if env_var_set {
1015            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
1016        } else {
1017            let api_url = AnthropicLanguageModelProvider::api_url(cx);
1018            if api_url == ANTHROPIC_API_URL {
1019                "API key configured".to_string()
1020            } else {
1021                format!("API key configured for {}", api_url)
1022            }
1023        };
1024
1025        if self.load_credentials_task.is_some() {
1026            div()
1027                .child(Label::new("Loading credentials..."))
1028                .into_any_element()
1029        } else if self.should_render_editor(cx) {
1030            v_flex()
1031                .size_full()
1032                .on_action(cx.listener(Self::save_api_key))
1033                .child(Label::new(format!("To use {}, you need to add an API key. Follow these steps:", match &self.target_agent {
1034                    ConfigurationViewTargetAgent::ZedAgent => "Zed's agent with Anthropic".into(),
1035                    ConfigurationViewTargetAgent::Other(agent) => agent.clone(),
1036                })))
1037                .child(
1038                    List::new()
1039                        .child(
1040                            ListBulletItem::new("")
1041                                .child(Label::new("Create one by visiting"))
1042                                .child(ButtonLink::new("Anthropic's settings", "https://console.anthropic.com/settings/keys"))
1043                        )
1044                        .child(
1045                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
1046                        )
1047                )
1048                .child(self.api_key_editor.clone())
1049                .child(
1050                    Label::new(
1051                        format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
1052                    )
1053                    .size(LabelSize::Small)
1054                    .color(Color::Muted)
1055                    .mt_0p5(),
1056                )
1057                .into_any_element()
1058        } else {
1059            ConfiguredApiCard::new(configured_card_label)
1060                .disabled(env_var_set)
1061                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
1062                .when(env_var_set, |this| {
1063                    this.tooltip_label(format!(
1064                    "To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."
1065                ))
1066                })
1067                .into_any_element()
1068        }
1069    }
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074    use super::*;
1075    use anthropic::AnthropicModelMode;
1076    use language_model::{LanguageModelRequestMessage, MessageContent};
1077
1078    #[test]
1079    fn test_cache_control_only_on_last_segment() {
1080        let request = LanguageModelRequest {
1081            messages: vec![LanguageModelRequestMessage {
1082                role: Role::User,
1083                content: vec![
1084                    MessageContent::Text("Some prompt".to_string()),
1085                    MessageContent::Image(language_model::LanguageModelImage::empty()),
1086                    MessageContent::Image(language_model::LanguageModelImage::empty()),
1087                    MessageContent::Image(language_model::LanguageModelImage::empty()),
1088                    MessageContent::Image(language_model::LanguageModelImage::empty()),
1089                ],
1090                cache: true,
1091                reasoning_details: None,
1092            }],
1093            thread_id: None,
1094            prompt_id: None,
1095            intent: None,
1096            stop: vec![],
1097            temperature: None,
1098            tools: vec![],
1099            tool_choice: None,
1100            thinking_allowed: true,
1101            thinking_effort: None,
1102        };
1103
1104        let anthropic_request = into_anthropic(
1105            request,
1106            "claude-3-5-sonnet".to_string(),
1107            0.7,
1108            4096,
1109            AnthropicModelMode::Default,
1110        );
1111
1112        assert_eq!(anthropic_request.messages.len(), 1);
1113
1114        let message = &anthropic_request.messages[0];
1115        assert_eq!(message.content.len(), 5);
1116
1117        assert!(matches!(
1118            message.content[0],
1119            anthropic::RequestContent::Text {
1120                cache_control: None,
1121                ..
1122            }
1123        ));
1124        for i in 1..3 {
1125            assert!(matches!(
1126                message.content[i],
1127                anthropic::RequestContent::Image {
1128                    cache_control: None,
1129                    ..
1130                }
1131            ));
1132        }
1133
1134        assert!(matches!(
1135            message.content[4],
1136            anthropic::RequestContent::Image {
1137                cache_control: Some(anthropic::CacheControl {
1138                    cache_type: anthropic::CacheControlType::Ephemeral,
1139                }),
1140                ..
1141            }
1142        ));
1143    }
1144
1145    fn request_with_assistant_content(
1146        assistant_content: Vec<MessageContent>,
1147    ) -> anthropic::Request {
1148        let mut request = LanguageModelRequest {
1149            messages: vec![LanguageModelRequestMessage {
1150                role: Role::User,
1151                content: vec![MessageContent::Text("Hello".to_string())],
1152                cache: false,
1153                reasoning_details: None,
1154            }],
1155            thinking_effort: None,
1156            thread_id: None,
1157            prompt_id: None,
1158            intent: None,
1159            stop: vec![],
1160            temperature: None,
1161            tools: vec![],
1162            tool_choice: None,
1163            thinking_allowed: true,
1164        };
1165        request.messages.push(LanguageModelRequestMessage {
1166            role: Role::Assistant,
1167            content: assistant_content,
1168            cache: false,
1169            reasoning_details: None,
1170        });
1171        into_anthropic(
1172            request,
1173            "claude-sonnet-4-5".to_string(),
1174            1.0,
1175            16000,
1176            AnthropicModelMode::Thinking {
1177                budget_tokens: Some(10000),
1178            },
1179        )
1180    }
1181
1182    #[test]
1183    fn test_unsigned_thinking_blocks_stripped() {
1184        let result = request_with_assistant_content(vec![
1185            MessageContent::Thinking {
1186                text: "Cancelled mid-think, no signature".to_string(),
1187                signature: None,
1188            },
1189            MessageContent::Text("Some response text".to_string()),
1190        ]);
1191
1192        let assistant_message = result
1193            .messages
1194            .iter()
1195            .find(|m| m.role == anthropic::Role::Assistant)
1196            .expect("assistant message should still exist");
1197
1198        assert_eq!(
1199            assistant_message.content.len(),
1200            1,
1201            "Only the text content should remain; unsigned thinking block should be stripped"
1202        );
1203        assert!(matches!(
1204            &assistant_message.content[0],
1205            anthropic::RequestContent::Text { text, .. } if text == "Some response text"
1206        ));
1207    }
1208
1209    #[test]
1210    fn test_signed_thinking_blocks_preserved() {
1211        let result = request_with_assistant_content(vec![
1212            MessageContent::Thinking {
1213                text: "Completed thinking".to_string(),
1214                signature: Some("valid-signature".to_string()),
1215            },
1216            MessageContent::Text("Response".to_string()),
1217        ]);
1218
1219        let assistant_message = result
1220            .messages
1221            .iter()
1222            .find(|m| m.role == anthropic::Role::Assistant)
1223            .expect("assistant message should exist");
1224
1225        assert_eq!(
1226            assistant_message.content.len(),
1227            2,
1228            "Both the signed thinking block and text should be preserved"
1229        );
1230        assert!(matches!(
1231            &assistant_message.content[0],
1232            anthropic::RequestContent::Thinking { thinking, signature, .. }
1233                if thinking == "Completed thinking" && signature == "valid-signature"
1234        ));
1235    }
1236
1237    #[test]
1238    fn test_only_unsigned_thinking_block_omits_entire_message() {
1239        let result = request_with_assistant_content(vec![MessageContent::Thinking {
1240            text: "Cancelled before any text or signature".to_string(),
1241            signature: None,
1242        }]);
1243
1244        let assistant_messages: Vec<_> = result
1245            .messages
1246            .iter()
1247            .filter(|m| m.role == anthropic::Role::Assistant)
1248            .collect();
1249
1250        assert_eq!(
1251            assistant_messages.len(),
1252            0,
1253            "An assistant message whose only content was an unsigned thinking block \
1254             should be omitted entirely"
1255        );
1256    }
1257}