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 provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
187        let mut models = BTreeMap::default();
188
189        // Add base models from anthropic::Model::iter()
190        for model in anthropic::Model::iter() {
191            if !matches!(model, anthropic::Model::Custom { .. }) {
192                models.insert(model.id().to_string(), model);
193            }
194        }
195
196        // Override with available models from settings
197        for model in AllLanguageModelSettings::get_global(cx)
198            .anthropic
199            .available_models
200            .iter()
201        {
202            models.insert(
203                model.name.clone(),
204                anthropic::Model::Custom {
205                    name: model.name.clone(),
206                    display_name: model.display_name.clone(),
207                    max_tokens: model.max_tokens,
208                    tool_override: model.tool_override.clone(),
209                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
210                        anthropic::AnthropicModelCacheConfiguration {
211                            max_cache_anchors: config.max_cache_anchors,
212                            should_speculate: config.should_speculate,
213                            min_total_token: config.min_total_token,
214                        }
215                    }),
216                    max_output_tokens: model.max_output_tokens,
217                    default_temperature: model.default_temperature,
218                    extra_beta_headers: model.extra_beta_headers.clone(),
219                },
220            );
221        }
222
223        models
224            .into_values()
225            .map(|model| {
226                Arc::new(AnthropicModel {
227                    id: LanguageModelId::from(model.id().to_string()),
228                    model,
229                    state: self.state.clone(),
230                    http_client: self.http_client.clone(),
231                    request_limiter: RateLimiter::new(4),
232                }) as Arc<dyn LanguageModel>
233            })
234            .collect()
235    }
236
237    fn is_authenticated(&self, cx: &App) -> bool {
238        self.state.read(cx).is_authenticated()
239    }
240
241    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
242        self.state.update(cx, |state, cx| state.authenticate(cx))
243    }
244
245    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
246        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
247            .into()
248    }
249
250    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
251        self.state.update(cx, |state, cx| state.reset_api_key(cx))
252    }
253}
254
255pub struct AnthropicModel {
256    id: LanguageModelId,
257    model: anthropic::Model,
258    state: gpui::Entity<State>,
259    http_client: Arc<dyn HttpClient>,
260    request_limiter: RateLimiter,
261}
262
263pub fn count_anthropic_tokens(
264    request: LanguageModelRequest,
265    cx: &App,
266) -> BoxFuture<'static, Result<usize>> {
267    cx.background_spawn(async move {
268        let messages = request.messages;
269        let mut tokens_from_images = 0;
270        let mut string_messages = Vec::with_capacity(messages.len());
271
272        for message in messages {
273            use language_model::MessageContent;
274
275            let mut string_contents = String::new();
276
277            for content in message.content {
278                match content {
279                    MessageContent::Text(text) => {
280                        string_contents.push_str(&text);
281                    }
282                    MessageContent::Image(image) => {
283                        tokens_from_images += image.estimate_tokens();
284                    }
285                    MessageContent::ToolUse(_tool_use) => {
286                        // TODO: Estimate token usage from tool uses.
287                    }
288                    MessageContent::ToolResult(tool_result) => {
289                        string_contents.push_str(&tool_result.content);
290                    }
291                }
292            }
293
294            if !string_contents.is_empty() {
295                string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
296                    role: match message.role {
297                        Role::User => "user".into(),
298                        Role::Assistant => "assistant".into(),
299                        Role::System => "system".into(),
300                    },
301                    content: Some(string_contents),
302                    name: None,
303                    function_call: None,
304                });
305            }
306        }
307
308        // Tiktoken doesn't yet support these models, so we manually use the
309        // same tokenizer as GPT-4.
310        tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
311            .map(|tokens| tokens + tokens_from_images)
312    })
313    .boxed()
314}
315
316impl AnthropicModel {
317    fn stream_completion(
318        &self,
319        request: anthropic::Request,
320        cx: &AsyncApp,
321    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<anthropic::Event, AnthropicError>>>>
322    {
323        let http_client = self.http_client.clone();
324
325        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
326            let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
327            (state.api_key.clone(), settings.api_url.clone())
328        }) else {
329            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
330        };
331
332        async move {
333            let api_key = api_key.ok_or_else(|| anyhow!("Missing Anthropic API Key"))?;
334            let request =
335                anthropic::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
336            request.await.context("failed to stream completion")
337        }
338        .boxed()
339    }
340}
341
342impl LanguageModel for AnthropicModel {
343    fn id(&self) -> LanguageModelId {
344        self.id.clone()
345    }
346
347    fn name(&self) -> LanguageModelName {
348        LanguageModelName::from(self.model.display_name().to_string())
349    }
350
351    fn provider_id(&self) -> LanguageModelProviderId {
352        LanguageModelProviderId(PROVIDER_ID.into())
353    }
354
355    fn provider_name(&self) -> LanguageModelProviderName {
356        LanguageModelProviderName(PROVIDER_NAME.into())
357    }
358
359    fn telemetry_id(&self) -> String {
360        format!("anthropic/{}", self.model.id())
361    }
362
363    fn api_key(&self, cx: &App) -> Option<String> {
364        self.state.read(cx).api_key.clone()
365    }
366
367    fn max_token_count(&self) -> usize {
368        self.model.max_token_count()
369    }
370
371    fn max_output_tokens(&self) -> Option<u32> {
372        Some(self.model.max_output_tokens())
373    }
374
375    fn count_tokens(
376        &self,
377        request: LanguageModelRequest,
378        cx: &App,
379    ) -> BoxFuture<'static, Result<usize>> {
380        count_anthropic_tokens(request, cx)
381    }
382
383    fn stream_completion(
384        &self,
385        request: LanguageModelRequest,
386        cx: &AsyncApp,
387    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
388        let request = request.into_anthropic(
389            self.model.id().into(),
390            self.model.default_temperature(),
391            self.model.max_output_tokens(),
392        );
393        let request = self.stream_completion(request, cx);
394        let future = self.request_limiter.stream(async move {
395            let response = request.await.map_err(|err| anyhow!(err))?;
396            Ok(map_to_language_model_completion_events(response))
397        });
398        async move { Ok(future.await?.boxed()) }.boxed()
399    }
400
401    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
402        self.model
403            .cache_configuration()
404            .map(|config| LanguageModelCacheConfiguration {
405                max_cache_anchors: config.max_cache_anchors,
406                should_speculate: config.should_speculate,
407                min_total_token: config.min_total_token,
408            })
409    }
410
411    fn use_any_tool(
412        &self,
413        request: LanguageModelRequest,
414        tool_name: String,
415        tool_description: String,
416        input_schema: serde_json::Value,
417        cx: &AsyncApp,
418    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
419        let mut request = request.into_anthropic(
420            self.model.tool_model_id().into(),
421            self.model.default_temperature(),
422            self.model.max_output_tokens(),
423        );
424        request.tool_choice = Some(anthropic::ToolChoice::Tool {
425            name: tool_name.clone(),
426        });
427        request.tools = vec![anthropic::Tool {
428            name: tool_name.clone(),
429            description: tool_description,
430            input_schema,
431        }];
432
433        let response = self.stream_completion(request, cx);
434        self.request_limiter
435            .run(async move {
436                let response = response.await?;
437                Ok(anthropic::extract_tool_args_from_events(
438                    tool_name,
439                    Box::pin(response.map_err(|e| anyhow!(e))),
440                )
441                .await?
442                .boxed())
443            })
444            .boxed()
445    }
446}
447
448pub fn map_to_language_model_completion_events(
449    events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
450) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
451    struct RawToolUse {
452        id: String,
453        name: String,
454        input_json: String,
455    }
456
457    struct State {
458        events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
459        tool_uses_by_index: HashMap<usize, RawToolUse>,
460    }
461
462    futures::stream::unfold(
463        State {
464            events,
465            tool_uses_by_index: HashMap::default(),
466        },
467        |mut state| async move {
468            while let Some(event) = state.events.next().await {
469                match event {
470                    Ok(event) => match event {
471                        Event::ContentBlockStart {
472                            index,
473                            content_block,
474                        } => match content_block {
475                            ResponseContent::Text { text } => {
476                                return Some((
477                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
478                                    state,
479                                ));
480                            }
481                            ResponseContent::ToolUse { id, name, .. } => {
482                                state.tool_uses_by_index.insert(
483                                    index,
484                                    RawToolUse {
485                                        id,
486                                        name,
487                                        input_json: String::new(),
488                                    },
489                                );
490
491                                return Some((None, state));
492                            }
493                        },
494                        Event::ContentBlockDelta { index, delta } => match delta {
495                            ContentDelta::TextDelta { text } => {
496                                return Some((
497                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
498                                    state,
499                                ));
500                            }
501                            ContentDelta::InputJsonDelta { partial_json } => {
502                                if let Some(tool_use) = state.tool_uses_by_index.get_mut(&index) {
503                                    tool_use.input_json.push_str(&partial_json);
504                                    return Some((None, state));
505                                }
506                            }
507                        },
508                        Event::ContentBlockStop { index } => {
509                            if let Some(tool_use) = state.tool_uses_by_index.remove(&index) {
510                                return Some((
511                                    Some(maybe!({
512                                        Ok(LanguageModelCompletionEvent::ToolUse(
513                                            LanguageModelToolUse {
514                                                id: tool_use.id.into(),
515                                                name: tool_use.name,
516                                                input: if tool_use.input_json.is_empty() {
517                                                    serde_json::Value::Null
518                                                } else {
519                                                    serde_json::Value::from_str(
520                                                        &tool_use.input_json,
521                                                    )
522                                                    .map_err(|err| anyhow!(err))?
523                                                },
524                                            },
525                                        ))
526                                    })),
527                                    state,
528                                ));
529                            }
530                        }
531                        Event::MessageStart { message } => {
532                            return Some((
533                                Some(Ok(LanguageModelCompletionEvent::StartMessage {
534                                    message_id: message.id,
535                                })),
536                                state,
537                            ))
538                        }
539                        Event::MessageDelta { delta, .. } => {
540                            if let Some(stop_reason) = delta.stop_reason.as_deref() {
541                                let stop_reason = match stop_reason {
542                                    "end_turn" => StopReason::EndTurn,
543                                    "max_tokens" => StopReason::MaxTokens,
544                                    "tool_use" => StopReason::ToolUse,
545                                    _ => StopReason::EndTurn,
546                                };
547
548                                return Some((
549                                    Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason))),
550                                    state,
551                                ));
552                            }
553                        }
554                        Event::Error { error } => {
555                            return Some((
556                                Some(Err(anyhow!(AnthropicError::ApiError(error)))),
557                                state,
558                            ));
559                        }
560                        _ => {}
561                    },
562                    Err(err) => {
563                        return Some((Some(Err(anyhow!(err))), state));
564                    }
565                }
566            }
567
568            None
569        },
570    )
571    .filter_map(|event| async move { event })
572}
573
574struct ConfigurationView {
575    api_key_editor: Entity<Editor>,
576    state: gpui::Entity<State>,
577    load_credentials_task: Option<Task<()>>,
578}
579
580impl ConfigurationView {
581    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
582
583    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
584        cx.observe(&state, |_, _, cx| {
585            cx.notify();
586        })
587        .detach();
588
589        let load_credentials_task = Some(cx.spawn({
590            let state = state.clone();
591            |this, mut cx| async move {
592                if let Some(task) = state
593                    .update(&mut cx, |state, cx| state.authenticate(cx))
594                    .log_err()
595                {
596                    // We don't log an error, because "not signed in" is also an error.
597                    let _ = task.await;
598                }
599                this.update(&mut cx, |this, cx| {
600                    this.load_credentials_task = None;
601                    cx.notify();
602                })
603                .log_err();
604            }
605        }));
606
607        Self {
608            api_key_editor: cx.new(|cx| {
609                let mut editor = Editor::single_line(window, cx);
610                editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
611                editor
612            }),
613            state,
614            load_credentials_task,
615        }
616    }
617
618    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
619        let api_key = self.api_key_editor.read(cx).text(cx);
620        if api_key.is_empty() {
621            return;
622        }
623
624        let state = self.state.clone();
625        cx.spawn_in(window, |_, mut cx| async move {
626            state
627                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
628                .await
629        })
630        .detach_and_log_err(cx);
631
632        cx.notify();
633    }
634
635    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
636        self.api_key_editor
637            .update(cx, |editor, cx| editor.set_text("", window, cx));
638
639        let state = self.state.clone();
640        cx.spawn_in(window, |_, mut cx| async move {
641            state
642                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
643                .await
644        })
645        .detach_and_log_err(cx);
646
647        cx.notify();
648    }
649
650    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
651        let settings = ThemeSettings::get_global(cx);
652        let text_style = TextStyle {
653            color: cx.theme().colors().text,
654            font_family: settings.ui_font.family.clone(),
655            font_features: settings.ui_font.features.clone(),
656            font_fallbacks: settings.ui_font.fallbacks.clone(),
657            font_size: rems(0.875).into(),
658            font_weight: settings.ui_font.weight,
659            font_style: FontStyle::Normal,
660            line_height: relative(1.3),
661            white_space: WhiteSpace::Normal,
662            ..Default::default()
663        };
664        EditorElement::new(
665            &self.api_key_editor,
666            EditorStyle {
667                background: cx.theme().colors().editor_background,
668                local_player: cx.theme().players().local(),
669                text: text_style,
670                ..Default::default()
671            },
672        )
673    }
674
675    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
676        !self.state.read(cx).is_authenticated()
677    }
678}
679
680impl Render for ConfigurationView {
681    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
682        const ANTHROPIC_CONSOLE_URL: &str = "https://console.anthropic.com/settings/keys";
683        const INSTRUCTIONS: [&str; 3] = [
684            "To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:",
685            "- Create one at:",
686            "- Paste your API key below and hit enter to use the assistant:",
687        ];
688        let env_var_set = self.state.read(cx).api_key_from_env;
689
690        if self.load_credentials_task.is_some() {
691            div().child(Label::new("Loading credentials...")).into_any()
692        } else if self.should_render_editor(cx) {
693            v_flex()
694                .size_full()
695                .on_action(cx.listener(Self::save_api_key))
696                .child(Label::new(INSTRUCTIONS[0]))
697                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
698                    Button::new("anthropic_console", ANTHROPIC_CONSOLE_URL)
699                        .style(ButtonStyle::Subtle)
700                        .icon(IconName::ArrowUpRight)
701                        .icon_size(IconSize::XSmall)
702                        .icon_color(Color::Muted)
703                        .on_click(move |_, _, cx| cx.open_url(ANTHROPIC_CONSOLE_URL))
704                    )
705                )
706                .child(Label::new(INSTRUCTIONS[2]))
707                .child(
708                    h_flex()
709                        .w_full()
710                        .my_2()
711                        .px_2()
712                        .py_1()
713                        .bg(cx.theme().colors().editor_background)
714                        .border_1()
715                        .border_color(cx.theme().colors().border_variant)
716                        .rounded_md()
717                        .child(self.render_api_key_editor(cx)),
718                )
719                .child(
720                    Label::new(
721                        format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
722                    )
723                    .size(LabelSize::Small),
724                )
725                .into_any()
726        } else {
727            h_flex()
728                .size_full()
729                .justify_between()
730                .child(
731                    h_flex()
732                        .gap_1()
733                        .child(Icon::new(IconName::Check).color(Color::Success))
734                        .child(Label::new(if env_var_set {
735                            format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
736                        } else {
737                            "API key configured.".to_string()
738                        })),
739                )
740                .child(
741                    Button::new("reset-key", "Reset key")
742                        .icon(Some(IconName::Trash))
743                        .icon_size(IconSize::Small)
744                        .icon_position(IconPosition::Start)
745                        .disabled(env_var_set)
746                        .when(env_var_set, |this| {
747                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
748                        })
749                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
750                )
751                .into_any()
752        }
753    }
754}