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, LanguageModelKnownError, LanguageModelName,
  20    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
  21    LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
  22    LanguageModelToolResultContent, MessageContent, RateLimiter, Role, WrappedTextContent,
  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: usize,
  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<u32>,
  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<usize>> {
 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                        | LanguageModelToolResultContent::WrappedText(WrappedTextContent {
 355                            text,
 356                            ..
 357                        }) => {
 358                            string_contents.push_str(text);
 359                        }
 360                        LanguageModelToolResultContent::Image(image) => {
 361                            tokens_from_images += image.estimate_tokens();
 362                        }
 363                    },
 364                }
 365            }
 366
 367            if !string_contents.is_empty() {
 368                string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
 369                    role: match message.role {
 370                        Role::User => "user".into(),
 371                        Role::Assistant => "assistant".into(),
 372                        Role::System => "system".into(),
 373                    },
 374                    content: Some(string_contents),
 375                    name: None,
 376                    function_call: None,
 377                });
 378            }
 379        }
 380
 381        // Tiktoken doesn't yet support these models, so we manually use the
 382        // same tokenizer as GPT-4.
 383        tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
 384            .map(|tokens| tokens + tokens_from_images)
 385    })
 386    .boxed()
 387}
 388
 389impl AnthropicModel {
 390    fn stream_completion(
 391        &self,
 392        request: anthropic::Request,
 393        cx: &AsyncApp,
 394    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<anthropic::Event, AnthropicError>>>>
 395    {
 396        let http_client = self.http_client.clone();
 397
 398        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
 399            let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
 400            (state.api_key.clone(), settings.api_url.clone())
 401        }) else {
 402            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
 403        };
 404
 405        async move {
 406            let api_key = api_key.context("Missing Anthropic API Key")?;
 407            let request =
 408                anthropic::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
 409            request.await.context("failed to stream completion")
 410        }
 411        .boxed()
 412    }
 413}
 414
 415impl LanguageModel for AnthropicModel {
 416    fn id(&self) -> LanguageModelId {
 417        self.id.clone()
 418    }
 419
 420    fn name(&self) -> LanguageModelName {
 421        LanguageModelName::from(self.model.display_name().to_string())
 422    }
 423
 424    fn provider_id(&self) -> LanguageModelProviderId {
 425        LanguageModelProviderId(PROVIDER_ID.into())
 426    }
 427
 428    fn provider_name(&self) -> LanguageModelProviderName {
 429        LanguageModelProviderName(PROVIDER_NAME.into())
 430    }
 431
 432    fn supports_tools(&self) -> bool {
 433        true
 434    }
 435
 436    fn supports_images(&self) -> bool {
 437        true
 438    }
 439
 440    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
 441        match choice {
 442            LanguageModelToolChoice::Auto
 443            | LanguageModelToolChoice::Any
 444            | LanguageModelToolChoice::None => true,
 445        }
 446    }
 447
 448    fn telemetry_id(&self) -> String {
 449        format!("anthropic/{}", self.model.id())
 450    }
 451
 452    fn api_key(&self, cx: &App) -> Option<String> {
 453        self.state.read(cx).api_key.clone()
 454    }
 455
 456    fn max_token_count(&self) -> usize {
 457        self.model.max_token_count()
 458    }
 459
 460    fn max_output_tokens(&self) -> Option<u32> {
 461        Some(self.model.max_output_tokens())
 462    }
 463
 464    fn count_tokens(
 465        &self,
 466        request: LanguageModelRequest,
 467        cx: &App,
 468    ) -> BoxFuture<'static, Result<usize>> {
 469        count_anthropic_tokens(request, cx)
 470    }
 471
 472    fn stream_completion(
 473        &self,
 474        request: LanguageModelRequest,
 475        cx: &AsyncApp,
 476    ) -> BoxFuture<
 477        'static,
 478        Result<
 479            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 480        >,
 481    > {
 482        let request = into_anthropic(
 483            request,
 484            self.model.request_id().into(),
 485            self.model.default_temperature(),
 486            self.model.max_output_tokens(),
 487            self.model.mode(),
 488        );
 489        let request = self.stream_completion(request, cx);
 490        let future = self.request_limiter.stream(async move {
 491            let response = request
 492                .await
 493                .map_err(|err| match err.downcast::<AnthropicError>() {
 494                    Ok(anthropic_err) => anthropic_err_to_anyhow(anthropic_err),
 495                    Err(err) => anyhow!(err),
 496                })?;
 497            Ok(AnthropicEventMapper::new().map_stream(response))
 498        });
 499        async move { Ok(future.await?.boxed()) }.boxed()
 500    }
 501
 502    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
 503        self.model
 504            .cache_configuration()
 505            .map(|config| LanguageModelCacheConfiguration {
 506                max_cache_anchors: config.max_cache_anchors,
 507                should_speculate: config.should_speculate,
 508                min_total_token: config.min_total_token,
 509            })
 510    }
 511}
 512
 513pub fn into_anthropic(
 514    request: LanguageModelRequest,
 515    model: String,
 516    default_temperature: f32,
 517    max_output_tokens: u32,
 518    mode: AnthropicModelMode,
 519) -> anthropic::Request {
 520    let mut new_messages: Vec<anthropic::Message> = Vec::new();
 521    let mut system_message = String::new();
 522
 523    for message in request.messages {
 524        if message.contents_empty() {
 525            continue;
 526        }
 527
 528        match message.role {
 529            Role::User | Role::Assistant => {
 530                let cache_control = if message.cache {
 531                    Some(anthropic::CacheControl {
 532                        cache_type: anthropic::CacheControlType::Ephemeral,
 533                    })
 534                } else {
 535                    None
 536                };
 537                let anthropic_message_content: Vec<anthropic::RequestContent> = message
 538                    .content
 539                    .into_iter()
 540                    .filter_map(|content| match content {
 541                        MessageContent::Text(text) => {
 542                            if !text.is_empty() {
 543                                Some(anthropic::RequestContent::Text {
 544                                    text,
 545                                    cache_control,
 546                                })
 547                            } else {
 548                                None
 549                            }
 550                        }
 551                        MessageContent::Thinking {
 552                            text: thinking,
 553                            signature,
 554                        } => {
 555                            if !thinking.is_empty() {
 556                                Some(anthropic::RequestContent::Thinking {
 557                                    thinking,
 558                                    signature: signature.unwrap_or_default(),
 559                                    cache_control,
 560                                })
 561                            } else {
 562                                None
 563                            }
 564                        }
 565                        MessageContent::RedactedThinking(data) => {
 566                            if !data.is_empty() {
 567                                Some(anthropic::RequestContent::RedactedThinking {
 568                                    data: String::from_utf8(data).ok()?,
 569                                })
 570                            } else {
 571                                None
 572                            }
 573                        }
 574                        MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
 575                            source: anthropic::ImageSource {
 576                                source_type: "base64".to_string(),
 577                                media_type: "image/png".to_string(),
 578                                data: image.source.to_string(),
 579                            },
 580                            cache_control,
 581                        }),
 582                        MessageContent::ToolUse(tool_use) => {
 583                            Some(anthropic::RequestContent::ToolUse {
 584                                id: tool_use.id.to_string(),
 585                                name: tool_use.name.to_string(),
 586                                input: tool_use.input,
 587                                cache_control,
 588                            })
 589                        }
 590                        MessageContent::ToolResult(tool_result) => {
 591                            Some(anthropic::RequestContent::ToolResult {
 592                                tool_use_id: tool_result.tool_use_id.to_string(),
 593                                is_error: tool_result.is_error,
 594                                content: match tool_result.content {
 595                                    LanguageModelToolResultContent::Text(text)
 596                                    | LanguageModelToolResultContent::WrappedText(
 597                                        WrappedTextContent { text, .. },
 598                                    ) => ToolResultContent::Plain(text.to_string()),
 599                                    LanguageModelToolResultContent::Image(image) => {
 600                                        ToolResultContent::Multipart(vec![ToolResultPart::Image {
 601                                            source: anthropic::ImageSource {
 602                                                source_type: "base64".to_string(),
 603                                                media_type: "image/png".to_string(),
 604                                                data: image.source.to_string(),
 605                                            },
 606                                        }])
 607                                    }
 608                                },
 609                                cache_control,
 610                            })
 611                        }
 612                    })
 613                    .collect();
 614                let anthropic_role = match message.role {
 615                    Role::User => anthropic::Role::User,
 616                    Role::Assistant => anthropic::Role::Assistant,
 617                    Role::System => unreachable!("System role should never occur here"),
 618                };
 619                if let Some(last_message) = new_messages.last_mut() {
 620                    if last_message.role == anthropic_role {
 621                        last_message.content.extend(anthropic_message_content);
 622                        continue;
 623                    }
 624                }
 625                new_messages.push(anthropic::Message {
 626                    role: anthropic_role,
 627                    content: anthropic_message_content,
 628                });
 629            }
 630            Role::System => {
 631                if !system_message.is_empty() {
 632                    system_message.push_str("\n\n");
 633                }
 634                system_message.push_str(&message.string_contents());
 635            }
 636        }
 637    }
 638
 639    anthropic::Request {
 640        model,
 641        messages: new_messages,
 642        max_tokens: max_output_tokens,
 643        system: if system_message.is_empty() {
 644            None
 645        } else {
 646            Some(anthropic::StringOrContents::String(system_message))
 647        },
 648        thinking: if let AnthropicModelMode::Thinking { budget_tokens } = mode {
 649            Some(anthropic::Thinking::Enabled { budget_tokens })
 650        } else {
 651            None
 652        },
 653        tools: request
 654            .tools
 655            .into_iter()
 656            .map(|tool| anthropic::Tool {
 657                name: tool.name,
 658                description: tool.description,
 659                input_schema: tool.input_schema,
 660            })
 661            .collect(),
 662        tool_choice: request.tool_choice.map(|choice| match choice {
 663            LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
 664            LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
 665            LanguageModelToolChoice::None => anthropic::ToolChoice::None,
 666        }),
 667        metadata: None,
 668        stop_sequences: Vec::new(),
 669        temperature: request.temperature.or(Some(default_temperature)),
 670        top_k: None,
 671        top_p: None,
 672    }
 673}
 674
 675pub struct AnthropicEventMapper {
 676    tool_uses_by_index: HashMap<usize, RawToolUse>,
 677    usage: Usage,
 678    stop_reason: StopReason,
 679}
 680
 681impl AnthropicEventMapper {
 682    pub fn new() -> Self {
 683        Self {
 684            tool_uses_by_index: HashMap::default(),
 685            usage: Usage::default(),
 686            stop_reason: StopReason::EndTurn,
 687        }
 688    }
 689
 690    pub fn map_stream(
 691        mut self,
 692        events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
 693    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 694    {
 695        events.flat_map(move |event| {
 696            futures::stream::iter(match event {
 697                Ok(event) => self.map_event(event),
 698                Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
 699            })
 700        })
 701    }
 702
 703    pub fn map_event(
 704        &mut self,
 705        event: Event,
 706    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 707        match event {
 708            Event::ContentBlockStart {
 709                index,
 710                content_block,
 711            } => match content_block {
 712                ResponseContent::Text { text } => {
 713                    vec![Ok(LanguageModelCompletionEvent::Text(text))]
 714                }
 715                ResponseContent::Thinking { thinking } => {
 716                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 717                        text: thinking,
 718                        signature: None,
 719                    })]
 720                }
 721                ResponseContent::RedactedThinking { .. } => {
 722                    // Redacted thinking is encrypted and not accessible to the user, see:
 723                    // https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#suggestions-for-handling-redacted-thinking-in-production
 724                    Vec::new()
 725                }
 726                ResponseContent::ToolUse { id, name, .. } => {
 727                    self.tool_uses_by_index.insert(
 728                        index,
 729                        RawToolUse {
 730                            id,
 731                            name,
 732                            input_json: String::new(),
 733                        },
 734                    );
 735                    Vec::new()
 736                }
 737            },
 738            Event::ContentBlockDelta { index, delta } => match delta {
 739                ContentDelta::TextDelta { text } => {
 740                    vec![Ok(LanguageModelCompletionEvent::Text(text))]
 741                }
 742                ContentDelta::ThinkingDelta { thinking } => {
 743                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 744                        text: thinking,
 745                        signature: None,
 746                    })]
 747                }
 748                ContentDelta::SignatureDelta { signature } => {
 749                    vec![Ok(LanguageModelCompletionEvent::Thinking {
 750                        text: "".to_string(),
 751                        signature: Some(signature),
 752                    })]
 753                }
 754                ContentDelta::InputJsonDelta { partial_json } => {
 755                    if let Some(tool_use) = self.tool_uses_by_index.get_mut(&index) {
 756                        tool_use.input_json.push_str(&partial_json);
 757
 758                        // Try to convert invalid (incomplete) JSON into
 759                        // valid JSON that serde can accept, e.g. by closing
 760                        // unclosed delimiters. This way, we can update the
 761                        // UI with whatever has been streamed back so far.
 762                        if let Ok(input) = serde_json::Value::from_str(
 763                            &partial_json_fixer::fix_json(&tool_use.input_json),
 764                        ) {
 765                            return vec![Ok(LanguageModelCompletionEvent::ToolUse(
 766                                LanguageModelToolUse {
 767                                    id: tool_use.id.clone().into(),
 768                                    name: tool_use.name.clone().into(),
 769                                    is_input_complete: false,
 770                                    raw_input: tool_use.input_json.clone(),
 771                                    input,
 772                                },
 773                            ))];
 774                        }
 775                    }
 776                    return vec![];
 777                }
 778            },
 779            Event::ContentBlockStop { index } => {
 780                if let Some(tool_use) = self.tool_uses_by_index.remove(&index) {
 781                    let input_json = tool_use.input_json.trim();
 782                    let input_value = if input_json.is_empty() {
 783                        Ok(serde_json::Value::Object(serde_json::Map::default()))
 784                    } else {
 785                        serde_json::Value::from_str(input_json)
 786                    };
 787                    let event_result = match input_value {
 788                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
 789                            LanguageModelToolUse {
 790                                id: tool_use.id.into(),
 791                                name: tool_use.name.into(),
 792                                is_input_complete: true,
 793                                input,
 794                                raw_input: tool_use.input_json.clone(),
 795                            },
 796                        )),
 797                        Err(json_parse_err) => Err(LanguageModelCompletionError::BadInputJson {
 798                            id: tool_use.id.into(),
 799                            tool_name: tool_use.name.into(),
 800                            raw_input: input_json.into(),
 801                            json_parse_error: json_parse_err.to_string(),
 802                        }),
 803                    };
 804
 805                    vec![event_result]
 806                } else {
 807                    Vec::new()
 808                }
 809            }
 810            Event::MessageStart { message } => {
 811                update_usage(&mut self.usage, &message.usage);
 812                vec![
 813                    Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
 814                        &self.usage,
 815                    ))),
 816                    Ok(LanguageModelCompletionEvent::StartMessage {
 817                        message_id: message.id,
 818                    }),
 819                ]
 820            }
 821            Event::MessageDelta { delta, usage } => {
 822                update_usage(&mut self.usage, &usage);
 823                if let Some(stop_reason) = delta.stop_reason.as_deref() {
 824                    self.stop_reason = match stop_reason {
 825                        "end_turn" => StopReason::EndTurn,
 826                        "max_tokens" => StopReason::MaxTokens,
 827                        "tool_use" => StopReason::ToolUse,
 828                        _ => {
 829                            log::error!("Unexpected anthropic stop_reason: {stop_reason}");
 830                            StopReason::EndTurn
 831                        }
 832                    };
 833                }
 834                vec![Ok(LanguageModelCompletionEvent::UsageUpdate(
 835                    convert_usage(&self.usage),
 836                ))]
 837            }
 838            Event::MessageStop => {
 839                vec![Ok(LanguageModelCompletionEvent::Stop(self.stop_reason))]
 840            }
 841            Event::Error { error } => {
 842                vec![Err(LanguageModelCompletionError::Other(anyhow!(
 843                    AnthropicError::ApiError(error)
 844                )))]
 845            }
 846            _ => Vec::new(),
 847        }
 848    }
 849}
 850
 851struct RawToolUse {
 852    id: String,
 853    name: String,
 854    input_json: String,
 855}
 856
 857pub fn anthropic_err_to_anyhow(err: AnthropicError) -> anyhow::Error {
 858    if let AnthropicError::ApiError(api_err) = &err {
 859        if let Some(tokens) = api_err.match_window_exceeded() {
 860            return anyhow!(LanguageModelKnownError::ContextWindowLimitExceeded { tokens });
 861        }
 862    }
 863
 864    anyhow!(err)
 865}
 866
 867/// Updates usage data by preferring counts from `new`.
 868fn update_usage(usage: &mut Usage, new: &Usage) {
 869    if let Some(input_tokens) = new.input_tokens {
 870        usage.input_tokens = Some(input_tokens);
 871    }
 872    if let Some(output_tokens) = new.output_tokens {
 873        usage.output_tokens = Some(output_tokens);
 874    }
 875    if let Some(cache_creation_input_tokens) = new.cache_creation_input_tokens {
 876        usage.cache_creation_input_tokens = Some(cache_creation_input_tokens);
 877    }
 878    if let Some(cache_read_input_tokens) = new.cache_read_input_tokens {
 879        usage.cache_read_input_tokens = Some(cache_read_input_tokens);
 880    }
 881}
 882
 883fn convert_usage(usage: &Usage) -> language_model::TokenUsage {
 884    language_model::TokenUsage {
 885        input_tokens: usage.input_tokens.unwrap_or(0),
 886        output_tokens: usage.output_tokens.unwrap_or(0),
 887        cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or(0),
 888        cache_read_input_tokens: usage.cache_read_input_tokens.unwrap_or(0),
 889    }
 890}
 891
 892struct ConfigurationView {
 893    api_key_editor: Entity<Editor>,
 894    state: gpui::Entity<State>,
 895    load_credentials_task: Option<Task<()>>,
 896}
 897
 898impl ConfigurationView {
 899    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
 900
 901    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 902        cx.observe(&state, |_, _, cx| {
 903            cx.notify();
 904        })
 905        .detach();
 906
 907        let load_credentials_task = Some(cx.spawn({
 908            let state = state.clone();
 909            async move |this, cx| {
 910                if let Some(task) = state
 911                    .update(cx, |state, cx| state.authenticate(cx))
 912                    .log_err()
 913                {
 914                    // We don't log an error, because "not signed in" is also an error.
 915                    let _ = task.await;
 916                }
 917                this.update(cx, |this, cx| {
 918                    this.load_credentials_task = None;
 919                    cx.notify();
 920                })
 921                .log_err();
 922            }
 923        }));
 924
 925        Self {
 926            api_key_editor: cx.new(|cx| {
 927                let mut editor = Editor::single_line(window, cx);
 928                editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
 929                editor
 930            }),
 931            state,
 932            load_credentials_task,
 933        }
 934    }
 935
 936    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 937        let api_key = self.api_key_editor.read(cx).text(cx);
 938        if api_key.is_empty() {
 939            return;
 940        }
 941
 942        let state = self.state.clone();
 943        cx.spawn_in(window, async move |_, cx| {
 944            state
 945                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
 946                .await
 947        })
 948        .detach_and_log_err(cx);
 949
 950        cx.notify();
 951    }
 952
 953    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 954        self.api_key_editor
 955            .update(cx, |editor, cx| editor.set_text("", window, cx));
 956
 957        let state = self.state.clone();
 958        cx.spawn_in(window, async move |_, cx| {
 959            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
 960        })
 961        .detach_and_log_err(cx);
 962
 963        cx.notify();
 964    }
 965
 966    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
 967        let settings = ThemeSettings::get_global(cx);
 968        let text_style = TextStyle {
 969            color: cx.theme().colors().text,
 970            font_family: settings.ui_font.family.clone(),
 971            font_features: settings.ui_font.features.clone(),
 972            font_fallbacks: settings.ui_font.fallbacks.clone(),
 973            font_size: rems(0.875).into(),
 974            font_weight: settings.ui_font.weight,
 975            font_style: FontStyle::Normal,
 976            line_height: relative(1.3),
 977            white_space: WhiteSpace::Normal,
 978            ..Default::default()
 979        };
 980        EditorElement::new(
 981            &self.api_key_editor,
 982            EditorStyle {
 983                background: cx.theme().colors().editor_background,
 984                local_player: cx.theme().players().local(),
 985                text: text_style,
 986                ..Default::default()
 987            },
 988        )
 989    }
 990
 991    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
 992        !self.state.read(cx).is_authenticated()
 993    }
 994}
 995
 996impl Render for ConfigurationView {
 997    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 998        let env_var_set = self.state.read(cx).api_key_from_env;
 999
1000        if self.load_credentials_task.is_some() {
1001            div().child(Label::new("Loading credentials...")).into_any()
1002        } else if self.should_render_editor(cx) {
1003            v_flex()
1004                .size_full()
1005                .on_action(cx.listener(Self::save_api_key))
1006                .child(Label::new("To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:"))
1007                .child(
1008                    List::new()
1009                        .child(
1010                            InstructionListItem::new(
1011                                "Create one by visiting",
1012                                Some("Anthropic's settings"),
1013                                Some("https://console.anthropic.com/settings/keys")
1014                            )
1015                        )
1016                        .child(
1017                            InstructionListItem::text_only("Paste your API key below and hit enter to start using the assistant")
1018                        )
1019                )
1020                .child(
1021                    h_flex()
1022                        .w_full()
1023                        .my_2()
1024                        .px_2()
1025                        .py_1()
1026                        .bg(cx.theme().colors().editor_background)
1027                        .border_1()
1028                        .border_color(cx.theme().colors().border)
1029                        .rounded_sm()
1030                        .child(self.render_api_key_editor(cx)),
1031                )
1032                .child(
1033                    Label::new(
1034                        format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
1035                    )
1036                    .size(LabelSize::Small)
1037                    .color(Color::Muted),
1038                )
1039                .into_any()
1040        } else {
1041            h_flex()
1042                .mt_1()
1043                .p_1()
1044                .justify_between()
1045                .rounded_md()
1046                .border_1()
1047                .border_color(cx.theme().colors().border)
1048                .bg(cx.theme().colors().background)
1049                .child(
1050                    h_flex()
1051                        .gap_1()
1052                        .child(Icon::new(IconName::Check).color(Color::Success))
1053                        .child(Label::new(if env_var_set {
1054                            format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
1055                        } else {
1056                            "API key configured.".to_string()
1057                        })),
1058                )
1059                .child(
1060                    Button::new("reset-key", "Reset Key")
1061                        .label_size(LabelSize::Small)
1062                        .icon(Some(IconName::Trash))
1063                        .icon_size(IconSize::Small)
1064                        .icon_position(IconPosition::Start)
1065                        .disabled(env_var_set)
1066                        .when(env_var_set, |this| {
1067                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
1068                        })
1069                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
1070                )
1071                .into_any()
1072        }
1073    }
1074}