anthropic.rs

  1use crate::AllLanguageModelSettings;
  2use anthropic::{AnthropicError, ContentDelta, Event, ResponseContent};
  3use anyhow::{anyhow, Context as _, Result};
  4use collections::{BTreeMap, HashMap};
  5use credentials_provider::CredentialsProvider;
  6use editor::{Editor, EditorElement, EditorStyle};
  7use futures::Stream;
  8use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryStreamExt as _};
  9use gpui::{
 10    AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
 11};
 12use http_client::HttpClient;
 13use language_model::{
 14    AuthenticateError, LanguageModel, LanguageModelCacheConfiguration, LanguageModelId,
 15    LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 16    LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
 17};
 18use language_model::{LanguageModelCompletionEvent, LanguageModelToolUse, StopReason};
 19use schemars::JsonSchema;
 20use serde::{Deserialize, Serialize};
 21use settings::{Settings, SettingsStore};
 22use std::pin::Pin;
 23use std::str::FromStr;
 24use std::sync::Arc;
 25use strum::IntoEnumIterator;
 26use theme::ThemeSettings;
 27use ui::{prelude::*, Icon, IconName, Tooltip};
 28use util::{maybe, ResultExt};
 29
 30pub const PROVIDER_ID: &str = "anthropic";
 31const PROVIDER_NAME: &str = "Anthropic";
 32
 33#[derive(Default, Clone, Debug, PartialEq)]
 34pub struct AnthropicSettings {
 35    pub api_url: String,
 36    /// Extend Zed's list of Anthropic models.
 37    pub available_models: Vec<AvailableModel>,
 38    pub needs_setting_migration: bool,
 39}
 40
 41#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 42pub struct AvailableModel {
 43    /// The model's name in the Anthropic API. e.g. claude-3-5-sonnet-latest, claude-3-opus-20240229, etc
 44    pub name: String,
 45    /// The model's name in Zed's UI, such as in the model selector dropdown menu in the assistant panel.
 46    pub display_name: Option<String>,
 47    /// The model's context window size.
 48    pub max_tokens: usize,
 49    /// A model `name` to substitute when calling tools, in case the primary model doesn't support tool calling.
 50    pub tool_override: Option<String>,
 51    /// Configuration of Anthropic's caching API.
 52    pub cache_configuration: Option<LanguageModelCacheConfiguration>,
 53    pub max_output_tokens: Option<u32>,
 54    pub default_temperature: Option<f32>,
 55    #[serde(default)]
 56    pub extra_beta_headers: Vec<String>,
 57}
 58
 59pub struct AnthropicLanguageModelProvider {
 60    http_client: Arc<dyn HttpClient>,
 61    state: gpui::Entity<State>,
 62}
 63
 64const ANTHROPIC_API_KEY_VAR: &str = "ANTHROPIC_API_KEY";
 65
 66pub struct State {
 67    api_key: Option<String>,
 68    api_key_from_env: bool,
 69    _subscription: Subscription,
 70}
 71
 72impl State {
 73    fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 74        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 75        let api_url = AllLanguageModelSettings::get_global(cx)
 76            .anthropic
 77            .api_url
 78            .clone();
 79        cx.spawn(|this, mut cx| async move {
 80            credentials_provider
 81                .delete_credentials(&api_url, &cx)
 82                .await
 83                .ok();
 84            this.update(&mut cx, |this, cx| {
 85                this.api_key = None;
 86                this.api_key_from_env = false;
 87                cx.notify();
 88            })
 89        })
 90    }
 91
 92    fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
 93        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 94        let api_url = AllLanguageModelSettings::get_global(cx)
 95            .anthropic
 96            .api_url
 97            .clone();
 98        cx.spawn(|this, mut cx| async move {
 99            credentials_provider
100                .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
101                .await
102                .ok();
103
104            this.update(&mut cx, |this, cx| {
105                this.api_key = Some(api_key);
106                cx.notify();
107            })
108        })
109    }
110
111    fn is_authenticated(&self) -> bool {
112        self.api_key.is_some()
113    }
114
115    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
116        if self.is_authenticated() {
117            return Task::ready(Ok(()));
118        }
119
120        let credentials_provider = <dyn CredentialsProvider>::global(cx);
121        let api_url = AllLanguageModelSettings::get_global(cx)
122            .anthropic
123            .api_url
124            .clone();
125
126        cx.spawn(|this, mut cx| async move {
127            let (api_key, from_env) = if let Ok(api_key) = std::env::var(ANTHROPIC_API_KEY_VAR) {
128                (api_key, true)
129            } else {
130                let (_, api_key) = credentials_provider
131                    .read_credentials(&api_url, &cx)
132                    .await?
133                    .ok_or(AuthenticateError::CredentialsNotFound)?;
134                (
135                    String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
136                    false,
137                )
138            };
139
140            this.update(&mut cx, |this, cx| {
141                this.api_key = Some(api_key);
142                this.api_key_from_env = from_env;
143                cx.notify();
144            })?;
145
146            Ok(())
147        })
148    }
149}
150
151impl AnthropicLanguageModelProvider {
152    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
153        let state = cx.new(|cx| State {
154            api_key: None,
155            api_key_from_env: false,
156            _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
157                cx.notify();
158            }),
159        });
160
161        Self { http_client, state }
162    }
163}
164
165impl LanguageModelProviderState for AnthropicLanguageModelProvider {
166    type ObservableEntity = State;
167
168    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
169        Some(self.state.clone())
170    }
171}
172
173impl LanguageModelProvider for AnthropicLanguageModelProvider {
174    fn id(&self) -> LanguageModelProviderId {
175        LanguageModelProviderId(PROVIDER_ID.into())
176    }
177
178    fn name(&self) -> LanguageModelProviderName {
179        LanguageModelProviderName(PROVIDER_NAME.into())
180    }
181
182    fn icon(&self) -> IconName {
183        IconName::AiAnthropic
184    }
185
186    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
187        let model = anthropic::Model::default();
188        Some(Arc::new(AnthropicModel {
189            id: LanguageModelId::from(model.id().to_string()),
190            model,
191            state: self.state.clone(),
192            http_client: self.http_client.clone(),
193            request_limiter: RateLimiter::new(4),
194        }))
195    }
196
197    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
198        let mut models = BTreeMap::default();
199
200        // Add base models from anthropic::Model::iter()
201        for model in anthropic::Model::iter() {
202            if !matches!(model, anthropic::Model::Custom { .. }) {
203                models.insert(model.id().to_string(), model);
204            }
205        }
206
207        // Override with available models from settings
208        for model in AllLanguageModelSettings::get_global(cx)
209            .anthropic
210            .available_models
211            .iter()
212        {
213            models.insert(
214                model.name.clone(),
215                anthropic::Model::Custom {
216                    name: model.name.clone(),
217                    display_name: model.display_name.clone(),
218                    max_tokens: model.max_tokens,
219                    tool_override: model.tool_override.clone(),
220                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
221                        anthropic::AnthropicModelCacheConfiguration {
222                            max_cache_anchors: config.max_cache_anchors,
223                            should_speculate: config.should_speculate,
224                            min_total_token: config.min_total_token,
225                        }
226                    }),
227                    max_output_tokens: model.max_output_tokens,
228                    default_temperature: model.default_temperature,
229                    extra_beta_headers: model.extra_beta_headers.clone(),
230                },
231            );
232        }
233
234        models
235            .into_values()
236            .map(|model| {
237                Arc::new(AnthropicModel {
238                    id: LanguageModelId::from(model.id().to_string()),
239                    model,
240                    state: self.state.clone(),
241                    http_client: self.http_client.clone(),
242                    request_limiter: RateLimiter::new(4),
243                }) as Arc<dyn LanguageModel>
244            })
245            .collect()
246    }
247
248    fn is_authenticated(&self, cx: &App) -> bool {
249        self.state.read(cx).is_authenticated()
250    }
251
252    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
253        self.state.update(cx, |state, cx| state.authenticate(cx))
254    }
255
256    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
257        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
258            .into()
259    }
260
261    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
262        self.state.update(cx, |state, cx| state.reset_api_key(cx))
263    }
264}
265
266pub struct AnthropicModel {
267    id: LanguageModelId,
268    model: anthropic::Model,
269    state: gpui::Entity<State>,
270    http_client: Arc<dyn HttpClient>,
271    request_limiter: RateLimiter,
272}
273
274pub fn count_anthropic_tokens(
275    request: LanguageModelRequest,
276    cx: &App,
277) -> BoxFuture<'static, Result<usize>> {
278    cx.background_spawn(async move {
279        let messages = request.messages;
280        let mut tokens_from_images = 0;
281        let mut string_messages = Vec::with_capacity(messages.len());
282
283        for message in messages {
284            use language_model::MessageContent;
285
286            let mut string_contents = String::new();
287
288            for content in message.content {
289                match content {
290                    MessageContent::Text(text) => {
291                        string_contents.push_str(&text);
292                    }
293                    MessageContent::Image(image) => {
294                        tokens_from_images += image.estimate_tokens();
295                    }
296                    MessageContent::ToolUse(_tool_use) => {
297                        // TODO: Estimate token usage from tool uses.
298                    }
299                    MessageContent::ToolResult(tool_result) => {
300                        string_contents.push_str(&tool_result.content);
301                    }
302                }
303            }
304
305            if !string_contents.is_empty() {
306                string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
307                    role: match message.role {
308                        Role::User => "user".into(),
309                        Role::Assistant => "assistant".into(),
310                        Role::System => "system".into(),
311                    },
312                    content: Some(string_contents),
313                    name: None,
314                    function_call: None,
315                });
316            }
317        }
318
319        // Tiktoken doesn't yet support these models, so we manually use the
320        // same tokenizer as GPT-4.
321        tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
322            .map(|tokens| tokens + tokens_from_images)
323    })
324    .boxed()
325}
326
327impl AnthropicModel {
328    fn stream_completion(
329        &self,
330        request: anthropic::Request,
331        cx: &AsyncApp,
332    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<anthropic::Event, AnthropicError>>>>
333    {
334        let http_client = self.http_client.clone();
335
336        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
337            let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
338            (state.api_key.clone(), settings.api_url.clone())
339        }) else {
340            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
341        };
342
343        async move {
344            let api_key = api_key.ok_or_else(|| anyhow!("Missing Anthropic API Key"))?;
345            let request =
346                anthropic::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
347            request.await.context("failed to stream completion")
348        }
349        .boxed()
350    }
351}
352
353impl LanguageModel for AnthropicModel {
354    fn id(&self) -> LanguageModelId {
355        self.id.clone()
356    }
357
358    fn name(&self) -> LanguageModelName {
359        LanguageModelName::from(self.model.display_name().to_string())
360    }
361
362    fn provider_id(&self) -> LanguageModelProviderId {
363        LanguageModelProviderId(PROVIDER_ID.into())
364    }
365
366    fn provider_name(&self) -> LanguageModelProviderName {
367        LanguageModelProviderName(PROVIDER_NAME.into())
368    }
369
370    fn telemetry_id(&self) -> String {
371        format!("anthropic/{}", self.model.id())
372    }
373
374    fn api_key(&self, cx: &App) -> Option<String> {
375        self.state.read(cx).api_key.clone()
376    }
377
378    fn max_token_count(&self) -> usize {
379        self.model.max_token_count()
380    }
381
382    fn max_output_tokens(&self) -> Option<u32> {
383        Some(self.model.max_output_tokens())
384    }
385
386    fn count_tokens(
387        &self,
388        request: LanguageModelRequest,
389        cx: &App,
390    ) -> BoxFuture<'static, Result<usize>> {
391        count_anthropic_tokens(request, cx)
392    }
393
394    fn stream_completion(
395        &self,
396        request: LanguageModelRequest,
397        cx: &AsyncApp,
398    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
399        let request = request.into_anthropic(
400            self.model.id().into(),
401            self.model.default_temperature(),
402            self.model.max_output_tokens(),
403        );
404        let request = self.stream_completion(request, cx);
405        let future = self.request_limiter.stream(async move {
406            let response = request.await.map_err(|err| anyhow!(err))?;
407            Ok(map_to_language_model_completion_events(response))
408        });
409        async move { Ok(future.await?.boxed()) }.boxed()
410    }
411
412    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
413        self.model
414            .cache_configuration()
415            .map(|config| LanguageModelCacheConfiguration {
416                max_cache_anchors: config.max_cache_anchors,
417                should_speculate: config.should_speculate,
418                min_total_token: config.min_total_token,
419            })
420    }
421
422    fn use_any_tool(
423        &self,
424        request: LanguageModelRequest,
425        tool_name: String,
426        tool_description: String,
427        input_schema: serde_json::Value,
428        cx: &AsyncApp,
429    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
430        let mut request = request.into_anthropic(
431            self.model.tool_model_id().into(),
432            self.model.default_temperature(),
433            self.model.max_output_tokens(),
434        );
435        request.tool_choice = Some(anthropic::ToolChoice::Tool {
436            name: tool_name.clone(),
437        });
438        request.tools = vec![anthropic::Tool {
439            name: tool_name.clone(),
440            description: tool_description,
441            input_schema,
442        }];
443
444        let response = self.stream_completion(request, cx);
445        self.request_limiter
446            .run(async move {
447                let response = response.await?;
448                Ok(anthropic::extract_tool_args_from_events(
449                    tool_name,
450                    Box::pin(response.map_err(|e| anyhow!(e))),
451                )
452                .await?
453                .boxed())
454            })
455            .boxed()
456    }
457}
458
459pub fn map_to_language_model_completion_events(
460    events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
461) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
462    struct RawToolUse {
463        id: String,
464        name: String,
465        input_json: String,
466    }
467
468    struct State {
469        events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
470        tool_uses_by_index: HashMap<usize, RawToolUse>,
471    }
472
473    futures::stream::unfold(
474        State {
475            events,
476            tool_uses_by_index: HashMap::default(),
477        },
478        |mut state| async move {
479            while let Some(event) = state.events.next().await {
480                match event {
481                    Ok(event) => match event {
482                        Event::ContentBlockStart {
483                            index,
484                            content_block,
485                        } => match content_block {
486                            ResponseContent::Text { text } => {
487                                return Some((
488                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
489                                    state,
490                                ));
491                            }
492                            ResponseContent::ToolUse { id, name, .. } => {
493                                state.tool_uses_by_index.insert(
494                                    index,
495                                    RawToolUse {
496                                        id,
497                                        name,
498                                        input_json: String::new(),
499                                    },
500                                );
501
502                                return Some((None, state));
503                            }
504                        },
505                        Event::ContentBlockDelta { index, delta } => match delta {
506                            ContentDelta::TextDelta { text } => {
507                                return Some((
508                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
509                                    state,
510                                ));
511                            }
512                            ContentDelta::InputJsonDelta { partial_json } => {
513                                if let Some(tool_use) = state.tool_uses_by_index.get_mut(&index) {
514                                    tool_use.input_json.push_str(&partial_json);
515                                    return Some((None, state));
516                                }
517                            }
518                        },
519                        Event::ContentBlockStop { index } => {
520                            if let Some(tool_use) = state.tool_uses_by_index.remove(&index) {
521                                return Some((
522                                    Some(maybe!({
523                                        Ok(LanguageModelCompletionEvent::ToolUse(
524                                            LanguageModelToolUse {
525                                                id: tool_use.id.into(),
526                                                name: tool_use.name,
527                                                input: if tool_use.input_json.is_empty() {
528                                                    serde_json::Value::Null
529                                                } else {
530                                                    serde_json::Value::from_str(
531                                                        &tool_use.input_json,
532                                                    )
533                                                    .map_err(|err| anyhow!(err))?
534                                                },
535                                            },
536                                        ))
537                                    })),
538                                    state,
539                                ));
540                            }
541                        }
542                        Event::MessageStart { message } => {
543                            return Some((
544                                Some(Ok(LanguageModelCompletionEvent::StartMessage {
545                                    message_id: message.id,
546                                })),
547                                state,
548                            ))
549                        }
550                        Event::MessageDelta { delta, .. } => {
551                            if let Some(stop_reason) = delta.stop_reason.as_deref() {
552                                let stop_reason = match stop_reason {
553                                    "end_turn" => StopReason::EndTurn,
554                                    "max_tokens" => StopReason::MaxTokens,
555                                    "tool_use" => StopReason::ToolUse,
556                                    _ => StopReason::EndTurn,
557                                };
558
559                                return Some((
560                                    Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason))),
561                                    state,
562                                ));
563                            }
564                        }
565                        Event::Error { error } => {
566                            return Some((
567                                Some(Err(anyhow!(AnthropicError::ApiError(error)))),
568                                state,
569                            ));
570                        }
571                        _ => {}
572                    },
573                    Err(err) => {
574                        return Some((Some(Err(anyhow!(err))), state));
575                    }
576                }
577            }
578
579            None
580        },
581    )
582    .filter_map(|event| async move { event })
583}
584
585struct ConfigurationView {
586    api_key_editor: Entity<Editor>,
587    state: gpui::Entity<State>,
588    load_credentials_task: Option<Task<()>>,
589}
590
591impl ConfigurationView {
592    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
593
594    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
595        cx.observe(&state, |_, _, cx| {
596            cx.notify();
597        })
598        .detach();
599
600        let load_credentials_task = Some(cx.spawn({
601            let state = state.clone();
602            |this, mut cx| async move {
603                if let Some(task) = state
604                    .update(&mut cx, |state, cx| state.authenticate(cx))
605                    .log_err()
606                {
607                    // We don't log an error, because "not signed in" is also an error.
608                    let _ = task.await;
609                }
610                this.update(&mut cx, |this, cx| {
611                    this.load_credentials_task = None;
612                    cx.notify();
613                })
614                .log_err();
615            }
616        }));
617
618        Self {
619            api_key_editor: cx.new(|cx| {
620                let mut editor = Editor::single_line(window, cx);
621                editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
622                editor
623            }),
624            state,
625            load_credentials_task,
626        }
627    }
628
629    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
630        let api_key = self.api_key_editor.read(cx).text(cx);
631        if api_key.is_empty() {
632            return;
633        }
634
635        let state = self.state.clone();
636        cx.spawn_in(window, |_, mut cx| async move {
637            state
638                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
639                .await
640        })
641        .detach_and_log_err(cx);
642
643        cx.notify();
644    }
645
646    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
647        self.api_key_editor
648            .update(cx, |editor, cx| editor.set_text("", window, cx));
649
650        let state = self.state.clone();
651        cx.spawn_in(window, |_, mut cx| async move {
652            state
653                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
654                .await
655        })
656        .detach_and_log_err(cx);
657
658        cx.notify();
659    }
660
661    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
662        let settings = ThemeSettings::get_global(cx);
663        let text_style = TextStyle {
664            color: cx.theme().colors().text,
665            font_family: settings.ui_font.family.clone(),
666            font_features: settings.ui_font.features.clone(),
667            font_fallbacks: settings.ui_font.fallbacks.clone(),
668            font_size: rems(0.875).into(),
669            font_weight: settings.ui_font.weight,
670            font_style: FontStyle::Normal,
671            line_height: relative(1.3),
672            white_space: WhiteSpace::Normal,
673            ..Default::default()
674        };
675        EditorElement::new(
676            &self.api_key_editor,
677            EditorStyle {
678                background: cx.theme().colors().editor_background,
679                local_player: cx.theme().players().local(),
680                text: text_style,
681                ..Default::default()
682            },
683        )
684    }
685
686    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
687        !self.state.read(cx).is_authenticated()
688    }
689}
690
691impl Render for ConfigurationView {
692    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
693        const ANTHROPIC_CONSOLE_URL: &str = "https://console.anthropic.com/settings/keys";
694        const INSTRUCTIONS: [&str; 3] = [
695            "To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:",
696            "- Create one at:",
697            "- Paste your API key below and hit enter to use the assistant:",
698        ];
699        let env_var_set = self.state.read(cx).api_key_from_env;
700
701        if self.load_credentials_task.is_some() {
702            div().child(Label::new("Loading credentials...")).into_any()
703        } else if self.should_render_editor(cx) {
704            v_flex()
705                .size_full()
706                .on_action(cx.listener(Self::save_api_key))
707                .child(Label::new(INSTRUCTIONS[0]))
708                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
709                    Button::new("anthropic_console", ANTHROPIC_CONSOLE_URL)
710                        .style(ButtonStyle::Subtle)
711                        .icon(IconName::ArrowUpRight)
712                        .icon_size(IconSize::XSmall)
713                        .icon_color(Color::Muted)
714                        .on_click(move |_, _, cx| cx.open_url(ANTHROPIC_CONSOLE_URL))
715                    )
716                )
717                .child(Label::new(INSTRUCTIONS[2]))
718                .child(
719                    h_flex()
720                        .w_full()
721                        .my_2()
722                        .px_2()
723                        .py_1()
724                        .bg(cx.theme().colors().editor_background)
725                        .border_1()
726                        .border_color(cx.theme().colors().border_variant)
727                        .rounded_md()
728                        .child(self.render_api_key_editor(cx)),
729                )
730                .child(
731                    Label::new(
732                        format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
733                    )
734                    .size(LabelSize::Small),
735                )
736                .into_any()
737        } else {
738            h_flex()
739                .size_full()
740                .justify_between()
741                .child(
742                    h_flex()
743                        .gap_1()
744                        .child(Icon::new(IconName::Check).color(Color::Success))
745                        .child(Label::new(if env_var_set {
746                            format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
747                        } else {
748                            "API key configured.".to_string()
749                        })),
750                )
751                .child(
752                    Button::new("reset-key", "Reset key")
753                        .icon(Some(IconName::Trash))
754                        .icon_size(IconSize::Small)
755                        .icon_position(IconPosition::Start)
756                        .disabled(env_var_set)
757                        .when(env_var_set, |this| {
758                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
759                        })
760                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
761                )
762                .into_any()
763        }
764    }
765}