anthropic.rs

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