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, MessageContent, 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
 30const PROVIDER_ID: &str = language_model::ANTHROPIC_PROVIDER_ID;
 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 = into_anthropic(
400            request,
401            self.model.id().into(),
402            self.model.default_temperature(),
403            self.model.max_output_tokens(),
404        );
405        let request = self.stream_completion(request, cx);
406        let future = self.request_limiter.stream(async move {
407            let response = request.await.map_err(|err| anyhow!(err))?;
408            Ok(map_to_language_model_completion_events(response))
409        });
410        async move { Ok(future.await?.boxed()) }.boxed()
411    }
412
413    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
414        self.model
415            .cache_configuration()
416            .map(|config| LanguageModelCacheConfiguration {
417                max_cache_anchors: config.max_cache_anchors,
418                should_speculate: config.should_speculate,
419                min_total_token: config.min_total_token,
420            })
421    }
422
423    fn use_any_tool(
424        &self,
425        request: LanguageModelRequest,
426        tool_name: String,
427        tool_description: String,
428        input_schema: serde_json::Value,
429        cx: &AsyncApp,
430    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
431        let mut request = into_anthropic(
432            request,
433            self.model.tool_model_id().into(),
434            self.model.default_temperature(),
435            self.model.max_output_tokens(),
436        );
437        request.tool_choice = Some(anthropic::ToolChoice::Tool {
438            name: tool_name.clone(),
439        });
440        request.tools = vec![anthropic::Tool {
441            name: tool_name.clone(),
442            description: tool_description,
443            input_schema,
444        }];
445
446        let response = self.stream_completion(request, cx);
447        self.request_limiter
448            .run(async move {
449                let response = response.await?;
450                Ok(anthropic::extract_tool_args_from_events(
451                    tool_name,
452                    Box::pin(response.map_err(|e| anyhow!(e))),
453                )
454                .await?
455                .boxed())
456            })
457            .boxed()
458    }
459}
460
461pub fn into_anthropic(
462    request: LanguageModelRequest,
463    model: String,
464    default_temperature: f32,
465    max_output_tokens: u32,
466) -> anthropic::Request {
467    let mut new_messages: Vec<anthropic::Message> = Vec::new();
468    let mut system_message = String::new();
469
470    for message in request.messages {
471        if message.contents_empty() {
472            continue;
473        }
474
475        match message.role {
476            Role::User | Role::Assistant => {
477                let cache_control = if message.cache {
478                    Some(anthropic::CacheControl {
479                        cache_type: anthropic::CacheControlType::Ephemeral,
480                    })
481                } else {
482                    None
483                };
484                let anthropic_message_content: Vec<anthropic::RequestContent> = message
485                    .content
486                    .into_iter()
487                    .filter_map(|content| match content {
488                        MessageContent::Text(text) => {
489                            if !text.is_empty() {
490                                Some(anthropic::RequestContent::Text {
491                                    text,
492                                    cache_control,
493                                })
494                            } else {
495                                None
496                            }
497                        }
498                        MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
499                            source: anthropic::ImageSource {
500                                source_type: "base64".to_string(),
501                                media_type: "image/png".to_string(),
502                                data: image.source.to_string(),
503                            },
504                            cache_control,
505                        }),
506                        MessageContent::ToolUse(tool_use) => {
507                            Some(anthropic::RequestContent::ToolUse {
508                                id: tool_use.id.to_string(),
509                                name: tool_use.name.to_string(),
510                                input: tool_use.input,
511                                cache_control,
512                            })
513                        }
514                        MessageContent::ToolResult(tool_result) => {
515                            Some(anthropic::RequestContent::ToolResult {
516                                tool_use_id: tool_result.tool_use_id.to_string(),
517                                is_error: tool_result.is_error,
518                                content: tool_result.content.to_string(),
519                                cache_control,
520                            })
521                        }
522                    })
523                    .collect();
524                let anthropic_role = match message.role {
525                    Role::User => anthropic::Role::User,
526                    Role::Assistant => anthropic::Role::Assistant,
527                    Role::System => unreachable!("System role should never occur here"),
528                };
529                if let Some(last_message) = new_messages.last_mut() {
530                    if last_message.role == anthropic_role {
531                        last_message.content.extend(anthropic_message_content);
532                        continue;
533                    }
534                }
535                new_messages.push(anthropic::Message {
536                    role: anthropic_role,
537                    content: anthropic_message_content,
538                });
539            }
540            Role::System => {
541                if !system_message.is_empty() {
542                    system_message.push_str("\n\n");
543                }
544                system_message.push_str(&message.string_contents());
545            }
546        }
547    }
548
549    anthropic::Request {
550        model,
551        messages: new_messages,
552        max_tokens: max_output_tokens,
553        system: Some(system_message),
554        tools: request
555            .tools
556            .into_iter()
557            .map(|tool| anthropic::Tool {
558                name: tool.name,
559                description: tool.description,
560                input_schema: tool.input_schema,
561            })
562            .collect(),
563        tool_choice: None,
564        metadata: None,
565        stop_sequences: Vec::new(),
566        temperature: request.temperature.or(Some(default_temperature)),
567        top_k: None,
568        top_p: None,
569    }
570}
571
572pub fn map_to_language_model_completion_events(
573    events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
574) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
575    struct RawToolUse {
576        id: String,
577        name: String,
578        input_json: String,
579    }
580
581    struct State {
582        events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
583        tool_uses_by_index: HashMap<usize, RawToolUse>,
584    }
585
586    futures::stream::unfold(
587        State {
588            events,
589            tool_uses_by_index: HashMap::default(),
590        },
591        |mut state| async move {
592            while let Some(event) = state.events.next().await {
593                match event {
594                    Ok(event) => match event {
595                        Event::ContentBlockStart {
596                            index,
597                            content_block,
598                        } => match content_block {
599                            ResponseContent::Text { text } => {
600                                return Some((
601                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
602                                    state,
603                                ));
604                            }
605                            ResponseContent::ToolUse { id, name, .. } => {
606                                state.tool_uses_by_index.insert(
607                                    index,
608                                    RawToolUse {
609                                        id,
610                                        name,
611                                        input_json: String::new(),
612                                    },
613                                );
614
615                                return Some((None, state));
616                            }
617                        },
618                        Event::ContentBlockDelta { index, delta } => match delta {
619                            ContentDelta::TextDelta { text } => {
620                                return Some((
621                                    Some(Ok(LanguageModelCompletionEvent::Text(text))),
622                                    state,
623                                ));
624                            }
625                            ContentDelta::InputJsonDelta { partial_json } => {
626                                if let Some(tool_use) = state.tool_uses_by_index.get_mut(&index) {
627                                    tool_use.input_json.push_str(&partial_json);
628                                    return Some((None, state));
629                                }
630                            }
631                        },
632                        Event::ContentBlockStop { index } => {
633                            if let Some(tool_use) = state.tool_uses_by_index.remove(&index) {
634                                return Some((
635                                    Some(maybe!({
636                                        Ok(LanguageModelCompletionEvent::ToolUse(
637                                            LanguageModelToolUse {
638                                                id: tool_use.id.into(),
639                                                name: tool_use.name.into(),
640                                                input: if tool_use.input_json.is_empty() {
641                                                    serde_json::Value::Null
642                                                } else {
643                                                    serde_json::Value::from_str(
644                                                        &tool_use.input_json,
645                                                    )
646                                                    .map_err(|err| anyhow!(err))?
647                                                },
648                                            },
649                                        ))
650                                    })),
651                                    state,
652                                ));
653                            }
654                        }
655                        Event::MessageStart { message } => {
656                            return Some((
657                                Some(Ok(LanguageModelCompletionEvent::StartMessage {
658                                    message_id: message.id,
659                                })),
660                                state,
661                            ))
662                        }
663                        Event::MessageDelta { delta, .. } => {
664                            if let Some(stop_reason) = delta.stop_reason.as_deref() {
665                                let stop_reason = match stop_reason {
666                                    "end_turn" => StopReason::EndTurn,
667                                    "max_tokens" => StopReason::MaxTokens,
668                                    "tool_use" => StopReason::ToolUse,
669                                    _ => StopReason::EndTurn,
670                                };
671
672                                return Some((
673                                    Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason))),
674                                    state,
675                                ));
676                            }
677                        }
678                        Event::Error { error } => {
679                            return Some((
680                                Some(Err(anyhow!(AnthropicError::ApiError(error)))),
681                                state,
682                            ));
683                        }
684                        _ => {}
685                    },
686                    Err(err) => {
687                        return Some((Some(Err(anyhow!(err))), state));
688                    }
689                }
690            }
691
692            None
693        },
694    )
695    .filter_map(|event| async move { event })
696}
697
698struct ConfigurationView {
699    api_key_editor: Entity<Editor>,
700    state: gpui::Entity<State>,
701    load_credentials_task: Option<Task<()>>,
702}
703
704impl ConfigurationView {
705    const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
706
707    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
708        cx.observe(&state, |_, _, cx| {
709            cx.notify();
710        })
711        .detach();
712
713        let load_credentials_task = Some(cx.spawn({
714            let state = state.clone();
715            |this, mut cx| async move {
716                if let Some(task) = state
717                    .update(&mut cx, |state, cx| state.authenticate(cx))
718                    .log_err()
719                {
720                    // We don't log an error, because "not signed in" is also an error.
721                    let _ = task.await;
722                }
723                this.update(&mut cx, |this, cx| {
724                    this.load_credentials_task = None;
725                    cx.notify();
726                })
727                .log_err();
728            }
729        }));
730
731        Self {
732            api_key_editor: cx.new(|cx| {
733                let mut editor = Editor::single_line(window, cx);
734                editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
735                editor
736            }),
737            state,
738            load_credentials_task,
739        }
740    }
741
742    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
743        let api_key = self.api_key_editor.read(cx).text(cx);
744        if api_key.is_empty() {
745            return;
746        }
747
748        let state = self.state.clone();
749        cx.spawn_in(window, |_, mut cx| async move {
750            state
751                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
752                .await
753        })
754        .detach_and_log_err(cx);
755
756        cx.notify();
757    }
758
759    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
760        self.api_key_editor
761            .update(cx, |editor, cx| editor.set_text("", window, cx));
762
763        let state = self.state.clone();
764        cx.spawn_in(window, |_, mut cx| async move {
765            state
766                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
767                .await
768        })
769        .detach_and_log_err(cx);
770
771        cx.notify();
772    }
773
774    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
775        let settings = ThemeSettings::get_global(cx);
776        let text_style = TextStyle {
777            color: cx.theme().colors().text,
778            font_family: settings.ui_font.family.clone(),
779            font_features: settings.ui_font.features.clone(),
780            font_fallbacks: settings.ui_font.fallbacks.clone(),
781            font_size: rems(0.875).into(),
782            font_weight: settings.ui_font.weight,
783            font_style: FontStyle::Normal,
784            line_height: relative(1.3),
785            white_space: WhiteSpace::Normal,
786            ..Default::default()
787        };
788        EditorElement::new(
789            &self.api_key_editor,
790            EditorStyle {
791                background: cx.theme().colors().editor_background,
792                local_player: cx.theme().players().local(),
793                text: text_style,
794                ..Default::default()
795            },
796        )
797    }
798
799    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
800        !self.state.read(cx).is_authenticated()
801    }
802}
803
804impl Render for ConfigurationView {
805    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
806        const ANTHROPIC_CONSOLE_URL: &str = "https://console.anthropic.com/settings/keys";
807        const INSTRUCTIONS: [&str; 3] = [
808            "To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:",
809            "- Create one at:",
810            "- Paste your API key below and hit enter to use the assistant:",
811        ];
812        let env_var_set = self.state.read(cx).api_key_from_env;
813
814        if self.load_credentials_task.is_some() {
815            div().child(Label::new("Loading credentials...")).into_any()
816        } else if self.should_render_editor(cx) {
817            v_flex()
818                .size_full()
819                .on_action(cx.listener(Self::save_api_key))
820                .child(Label::new(INSTRUCTIONS[0]))
821                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
822                    Button::new("anthropic_console", ANTHROPIC_CONSOLE_URL)
823                        .style(ButtonStyle::Subtle)
824                        .icon(IconName::ArrowUpRight)
825                        .icon_size(IconSize::XSmall)
826                        .icon_color(Color::Muted)
827                        .on_click(move |_, _, cx| cx.open_url(ANTHROPIC_CONSOLE_URL))
828                    )
829                )
830                .child(Label::new(INSTRUCTIONS[2]))
831                .child(
832                    h_flex()
833                        .w_full()
834                        .my_2()
835                        .px_2()
836                        .py_1()
837                        .bg(cx.theme().colors().editor_background)
838                        .border_1()
839                        .border_color(cx.theme().colors().border_variant)
840                        .rounded_md()
841                        .child(self.render_api_key_editor(cx)),
842                )
843                .child(
844                    Label::new(
845                        format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
846                    )
847                    .size(LabelSize::Small),
848                )
849                .into_any()
850        } else {
851            h_flex()
852                .size_full()
853                .justify_between()
854                .child(
855                    h_flex()
856                        .gap_1()
857                        .child(Icon::new(IconName::Check).color(Color::Success))
858                        .child(Label::new(if env_var_set {
859                            format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
860                        } else {
861                            "API key configured.".to_string()
862                        })),
863                )
864                .child(
865                    Button::new("reset-key", "Reset key")
866                        .icon(Some(IconName::Trash))
867                        .icon_size(IconSize::Small)
868                        .icon_position(IconPosition::Start)
869                        .disabled(env_var_set)
870                        .when(env_var_set, |this| {
871                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
872                        })
873                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
874                )
875                .into_any()
876        }
877    }
878}