anthropic.rs

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