1use crate::AllLanguageModelSettings;
2use crate::ui::InstructionListItem;
3use anthropic::{
4 AnthropicError, AnthropicModelMode, ContentDelta, Event, ResponseContent, ToolResultContent,
5 ToolResultPart, Usage,
6};
7use anyhow::{Context as _, Result, anyhow};
8use collections::{BTreeMap, HashMap};
9use credentials_provider::CredentialsProvider;
10use editor::{Editor, EditorElement, EditorStyle};
11use futures::Stream;
12use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
13use gpui::{
14 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
15};
16use http_client::HttpClient;
17use language_model::{
18 AuthenticateError, LanguageModel, LanguageModelCacheConfiguration,
19 LanguageModelCompletionError, LanguageModelId, LanguageModelKnownError, LanguageModelName,
20 LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
21 LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
22 LanguageModelToolResultContent, MessageContent, RateLimiter, Role,
23};
24use language_model::{LanguageModelCompletionEvent, LanguageModelToolUse, StopReason};
25use schemars::JsonSchema;
26use serde::{Deserialize, Serialize};
27use settings::{Settings, SettingsStore};
28use std::pin::Pin;
29use std::str::FromStr;
30use std::sync::Arc;
31use strum::IntoEnumIterator;
32use theme::ThemeSettings;
33use ui::{Icon, IconName, List, Tooltip, prelude::*};
34use util::ResultExt;
35
36const PROVIDER_ID: &str = language_model::ANTHROPIC_PROVIDER_ID;
37const PROVIDER_NAME: &str = "Anthropic";
38
39#[derive(Default, Clone, Debug, PartialEq)]
40pub struct AnthropicSettings {
41 pub api_url: String,
42 /// Extend Zed's list of Anthropic models.
43 pub available_models: Vec<AvailableModel>,
44 pub needs_setting_migration: bool,
45}
46
47#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
48pub struct AvailableModel {
49 /// The model's name in the Anthropic API. e.g. claude-3-5-sonnet-latest, claude-3-opus-20240229, etc
50 pub name: String,
51 /// The model's name in Zed's UI, such as in the model selector dropdown menu in the assistant panel.
52 pub display_name: Option<String>,
53 /// The model's context window size.
54 pub max_tokens: usize,
55 /// A model `name` to substitute when calling tools, in case the primary model doesn't support tool calling.
56 pub tool_override: Option<String>,
57 /// Configuration of Anthropic's caching API.
58 pub cache_configuration: Option<LanguageModelCacheConfiguration>,
59 pub max_output_tokens: Option<u32>,
60 pub default_temperature: Option<f32>,
61 #[serde(default)]
62 pub extra_beta_headers: Vec<String>,
63 /// The model's mode (e.g. thinking)
64 pub mode: Option<ModelMode>,
65}
66
67#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
68#[serde(tag = "type", rename_all = "lowercase")]
69pub enum ModelMode {
70 #[default]
71 Default,
72 Thinking {
73 /// The maximum number of tokens to use for reasoning. Must be lower than the model's `max_output_tokens`.
74 budget_tokens: Option<u32>,
75 },
76}
77
78impl From<ModelMode> for AnthropicModelMode {
79 fn from(value: ModelMode) -> Self {
80 match value {
81 ModelMode::Default => AnthropicModelMode::Default,
82 ModelMode::Thinking { budget_tokens } => AnthropicModelMode::Thinking { budget_tokens },
83 }
84 }
85}
86
87impl From<AnthropicModelMode> for ModelMode {
88 fn from(value: AnthropicModelMode) -> Self {
89 match value {
90 AnthropicModelMode::Default => ModelMode::Default,
91 AnthropicModelMode::Thinking { budget_tokens } => ModelMode::Thinking { budget_tokens },
92 }
93 }
94}
95
96pub struct AnthropicLanguageModelProvider {
97 http_client: Arc<dyn HttpClient>,
98 state: gpui::Entity<State>,
99}
100
101const ANTHROPIC_API_KEY_VAR: &str = "ANTHROPIC_API_KEY";
102
103pub struct State {
104 api_key: Option<String>,
105 api_key_from_env: bool,
106 _subscription: Subscription,
107}
108
109impl State {
110 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
111 let credentials_provider = <dyn CredentialsProvider>::global(cx);
112 let api_url = AllLanguageModelSettings::get_global(cx)
113 .anthropic
114 .api_url
115 .clone();
116 cx.spawn(async move |this, cx| {
117 credentials_provider
118 .delete_credentials(&api_url, &cx)
119 .await
120 .ok();
121 this.update(cx, |this, cx| {
122 this.api_key = None;
123 this.api_key_from_env = false;
124 cx.notify();
125 })
126 })
127 }
128
129 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
130 let credentials_provider = <dyn CredentialsProvider>::global(cx);
131 let api_url = AllLanguageModelSettings::get_global(cx)
132 .anthropic
133 .api_url
134 .clone();
135 cx.spawn(async move |this, cx| {
136 credentials_provider
137 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
138 .await
139 .ok();
140
141 this.update(cx, |this, cx| {
142 this.api_key = Some(api_key);
143 cx.notify();
144 })
145 })
146 }
147
148 fn is_authenticated(&self) -> bool {
149 self.api_key.is_some()
150 }
151
152 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
153 if self.is_authenticated() {
154 return Task::ready(Ok(()));
155 }
156
157 let credentials_provider = <dyn CredentialsProvider>::global(cx);
158 let api_url = AllLanguageModelSettings::get_global(cx)
159 .anthropic
160 .api_url
161 .clone();
162
163 cx.spawn(async move |this, cx| {
164 let (api_key, from_env) = if let Ok(api_key) = std::env::var(ANTHROPIC_API_KEY_VAR) {
165 (api_key, true)
166 } else {
167 let (_, api_key) = credentials_provider
168 .read_credentials(&api_url, &cx)
169 .await?
170 .ok_or(AuthenticateError::CredentialsNotFound)?;
171 (
172 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
173 false,
174 )
175 };
176
177 this.update(cx, |this, cx| {
178 this.api_key = Some(api_key);
179 this.api_key_from_env = from_env;
180 cx.notify();
181 })?;
182
183 Ok(())
184 })
185 }
186}
187
188impl AnthropicLanguageModelProvider {
189 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
190 let state = cx.new(|cx| State {
191 api_key: None,
192 api_key_from_env: false,
193 _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
194 cx.notify();
195 }),
196 });
197
198 Self { http_client, state }
199 }
200
201 fn create_language_model(&self, model: anthropic::Model) -> Arc<dyn LanguageModel> {
202 Arc::new(AnthropicModel {
203 id: LanguageModelId::from(model.id().to_string()),
204 model,
205 state: self.state.clone(),
206 http_client: self.http_client.clone(),
207 request_limiter: RateLimiter::new(4),
208 })
209 }
210}
211
212impl LanguageModelProviderState for AnthropicLanguageModelProvider {
213 type ObservableEntity = State;
214
215 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
216 Some(self.state.clone())
217 }
218}
219
220impl LanguageModelProvider for AnthropicLanguageModelProvider {
221 fn id(&self) -> LanguageModelProviderId {
222 LanguageModelProviderId(PROVIDER_ID.into())
223 }
224
225 fn name(&self) -> LanguageModelProviderName {
226 LanguageModelProviderName(PROVIDER_NAME.into())
227 }
228
229 fn icon(&self) -> IconName {
230 IconName::AiAnthropic
231 }
232
233 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
234 Some(self.create_language_model(anthropic::Model::default()))
235 }
236
237 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
238 Some(self.create_language_model(anthropic::Model::default_fast()))
239 }
240
241 fn recommended_models(&self, _cx: &App) -> Vec<Arc<dyn LanguageModel>> {
242 [
243 anthropic::Model::ClaudeSonnet4,
244 anthropic::Model::ClaudeSonnet4Thinking,
245 ]
246 .into_iter()
247 .map(|model| self.create_language_model(model))
248 .collect()
249 }
250
251 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
252 let mut models = BTreeMap::default();
253
254 // Add base models from anthropic::Model::iter()
255 for model in anthropic::Model::iter() {
256 if !matches!(model, anthropic::Model::Custom { .. }) {
257 models.insert(model.id().to_string(), model);
258 }
259 }
260
261 // Override with available models from settings
262 for model in AllLanguageModelSettings::get_global(cx)
263 .anthropic
264 .available_models
265 .iter()
266 {
267 models.insert(
268 model.name.clone(),
269 anthropic::Model::Custom {
270 name: model.name.clone(),
271 display_name: model.display_name.clone(),
272 max_tokens: model.max_tokens,
273 tool_override: model.tool_override.clone(),
274 cache_configuration: model.cache_configuration.as_ref().map(|config| {
275 anthropic::AnthropicModelCacheConfiguration {
276 max_cache_anchors: config.max_cache_anchors,
277 should_speculate: config.should_speculate,
278 min_total_token: config.min_total_token,
279 }
280 }),
281 max_output_tokens: model.max_output_tokens,
282 default_temperature: model.default_temperature,
283 extra_beta_headers: model.extra_beta_headers.clone(),
284 mode: model.mode.clone().unwrap_or_default().into(),
285 },
286 );
287 }
288
289 models
290 .into_values()
291 .map(|model| self.create_language_model(model))
292 .collect()
293 }
294
295 fn is_authenticated(&self, cx: &App) -> bool {
296 self.state.read(cx).is_authenticated()
297 }
298
299 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
300 self.state.update(cx, |state, cx| state.authenticate(cx))
301 }
302
303 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
304 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
305 .into()
306 }
307
308 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
309 self.state.update(cx, |state, cx| state.reset_api_key(cx))
310 }
311}
312
313pub struct AnthropicModel {
314 id: LanguageModelId,
315 model: anthropic::Model,
316 state: gpui::Entity<State>,
317 http_client: Arc<dyn HttpClient>,
318 request_limiter: RateLimiter,
319}
320
321pub fn count_anthropic_tokens(
322 request: LanguageModelRequest,
323 cx: &App,
324) -> BoxFuture<'static, Result<usize>> {
325 cx.background_spawn(async move {
326 let messages = request.messages;
327 let mut tokens_from_images = 0;
328 let mut string_messages = Vec::with_capacity(messages.len());
329
330 for message in messages {
331 use language_model::MessageContent;
332
333 let mut string_contents = String::new();
334
335 for content in message.content {
336 match content {
337 MessageContent::Text(text) => {
338 string_contents.push_str(&text);
339 }
340 MessageContent::Thinking { .. } => {
341 // Thinking blocks are not included in the input token count.
342 }
343 MessageContent::RedactedThinking(_) => {
344 // Thinking blocks are not included in the input token count.
345 }
346 MessageContent::Image(image) => {
347 tokens_from_images += image.estimate_tokens();
348 }
349 MessageContent::ToolUse(_tool_use) => {
350 // TODO: Estimate token usage from tool uses.
351 }
352 MessageContent::ToolResult(tool_result) => match &tool_result.content {
353 LanguageModelToolResultContent::Text(text) => {
354 string_contents.push_str(text);
355 }
356 LanguageModelToolResultContent::Image(image) => {
357 tokens_from_images += image.estimate_tokens();
358 }
359 },
360 }
361 }
362
363 if !string_contents.is_empty() {
364 string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
365 role: match message.role {
366 Role::User => "user".into(),
367 Role::Assistant => "assistant".into(),
368 Role::System => "system".into(),
369 },
370 content: Some(string_contents),
371 name: None,
372 function_call: None,
373 });
374 }
375 }
376
377 // Tiktoken doesn't yet support these models, so we manually use the
378 // same tokenizer as GPT-4.
379 tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
380 .map(|tokens| tokens + tokens_from_images)
381 })
382 .boxed()
383}
384
385impl AnthropicModel {
386 fn stream_completion(
387 &self,
388 request: anthropic::Request,
389 cx: &AsyncApp,
390 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<anthropic::Event, AnthropicError>>>>
391 {
392 let http_client = self.http_client.clone();
393
394 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
395 let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
396 (state.api_key.clone(), settings.api_url.clone())
397 }) else {
398 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
399 };
400
401 async move {
402 let api_key = api_key.context("Missing Anthropic API Key")?;
403 let request =
404 anthropic::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
405 request.await.context("failed to stream completion")
406 }
407 .boxed()
408 }
409}
410
411impl LanguageModel for AnthropicModel {
412 fn id(&self) -> LanguageModelId {
413 self.id.clone()
414 }
415
416 fn name(&self) -> LanguageModelName {
417 LanguageModelName::from(self.model.display_name().to_string())
418 }
419
420 fn provider_id(&self) -> LanguageModelProviderId {
421 LanguageModelProviderId(PROVIDER_ID.into())
422 }
423
424 fn provider_name(&self) -> LanguageModelProviderName {
425 LanguageModelProviderName(PROVIDER_NAME.into())
426 }
427
428 fn supports_tools(&self) -> bool {
429 true
430 }
431
432 fn supports_images(&self) -> bool {
433 true
434 }
435
436 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
437 match choice {
438 LanguageModelToolChoice::Auto
439 | LanguageModelToolChoice::Any
440 | LanguageModelToolChoice::None => true,
441 }
442 }
443
444 fn telemetry_id(&self) -> String {
445 format!("anthropic/{}", self.model.id())
446 }
447
448 fn api_key(&self, cx: &App) -> Option<String> {
449 self.state.read(cx).api_key.clone()
450 }
451
452 fn max_token_count(&self) -> usize {
453 self.model.max_token_count()
454 }
455
456 fn max_output_tokens(&self) -> Option<u32> {
457 Some(self.model.max_output_tokens())
458 }
459
460 fn count_tokens(
461 &self,
462 request: LanguageModelRequest,
463 cx: &App,
464 ) -> BoxFuture<'static, Result<usize>> {
465 count_anthropic_tokens(request, cx)
466 }
467
468 fn stream_completion(
469 &self,
470 request: LanguageModelRequest,
471 cx: &AsyncApp,
472 ) -> BoxFuture<
473 'static,
474 Result<
475 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
476 >,
477 > {
478 let request = into_anthropic(
479 request,
480 self.model.request_id().into(),
481 self.model.default_temperature(),
482 self.model.max_output_tokens(),
483 self.model.mode(),
484 );
485 let request = self.stream_completion(request, cx);
486 let future = self.request_limiter.stream(async move {
487 let response = request
488 .await
489 .map_err(|err| match err.downcast::<AnthropicError>() {
490 Ok(anthropic_err) => anthropic_err_to_anyhow(anthropic_err),
491 Err(err) => anyhow!(err),
492 })?;
493 Ok(AnthropicEventMapper::new().map_stream(response))
494 });
495 async move { Ok(future.await?.boxed()) }.boxed()
496 }
497
498 fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
499 self.model
500 .cache_configuration()
501 .map(|config| LanguageModelCacheConfiguration {
502 max_cache_anchors: config.max_cache_anchors,
503 should_speculate: config.should_speculate,
504 min_total_token: config.min_total_token,
505 })
506 }
507}
508
509pub fn into_anthropic(
510 request: LanguageModelRequest,
511 model: String,
512 default_temperature: f32,
513 max_output_tokens: u32,
514 mode: AnthropicModelMode,
515) -> anthropic::Request {
516 let mut new_messages: Vec<anthropic::Message> = Vec::new();
517 let mut system_message = String::new();
518
519 for message in request.messages {
520 if message.contents_empty() {
521 continue;
522 }
523
524 match message.role {
525 Role::User | Role::Assistant => {
526 let cache_control = if message.cache {
527 Some(anthropic::CacheControl {
528 cache_type: anthropic::CacheControlType::Ephemeral,
529 })
530 } else {
531 None
532 };
533 let anthropic_message_content: Vec<anthropic::RequestContent> = message
534 .content
535 .into_iter()
536 .filter_map(|content| match content {
537 MessageContent::Text(text) => {
538 if !text.is_empty() {
539 Some(anthropic::RequestContent::Text {
540 text,
541 cache_control,
542 })
543 } else {
544 None
545 }
546 }
547 MessageContent::Thinking {
548 text: thinking,
549 signature,
550 } => {
551 if !thinking.is_empty() {
552 Some(anthropic::RequestContent::Thinking {
553 thinking,
554 signature: signature.unwrap_or_default(),
555 cache_control,
556 })
557 } else {
558 None
559 }
560 }
561 MessageContent::RedactedThinking(data) => {
562 if !data.is_empty() {
563 Some(anthropic::RequestContent::RedactedThinking {
564 data: String::from_utf8(data).ok()?,
565 })
566 } else {
567 None
568 }
569 }
570 MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
571 source: anthropic::ImageSource {
572 source_type: "base64".to_string(),
573 media_type: "image/png".to_string(),
574 data: image.source.to_string(),
575 },
576 cache_control,
577 }),
578 MessageContent::ToolUse(tool_use) => {
579 Some(anthropic::RequestContent::ToolUse {
580 id: tool_use.id.to_string(),
581 name: tool_use.name.to_string(),
582 input: tool_use.input,
583 cache_control,
584 })
585 }
586 MessageContent::ToolResult(tool_result) => {
587 Some(anthropic::RequestContent::ToolResult {
588 tool_use_id: tool_result.tool_use_id.to_string(),
589 is_error: tool_result.is_error,
590 content: match tool_result.content {
591 LanguageModelToolResultContent::Text(text) => {
592 ToolResultContent::Plain(text.to_string())
593 }
594 LanguageModelToolResultContent::Image(image) => {
595 ToolResultContent::Multipart(vec![ToolResultPart::Image {
596 source: anthropic::ImageSource {
597 source_type: "base64".to_string(),
598 media_type: "image/png".to_string(),
599 data: image.source.to_string(),
600 },
601 }])
602 }
603 },
604 cache_control,
605 })
606 }
607 })
608 .collect();
609 let anthropic_role = match message.role {
610 Role::User => anthropic::Role::User,
611 Role::Assistant => anthropic::Role::Assistant,
612 Role::System => unreachable!("System role should never occur here"),
613 };
614 if let Some(last_message) = new_messages.last_mut() {
615 if last_message.role == anthropic_role {
616 last_message.content.extend(anthropic_message_content);
617 continue;
618 }
619 }
620 new_messages.push(anthropic::Message {
621 role: anthropic_role,
622 content: anthropic_message_content,
623 });
624 }
625 Role::System => {
626 if !system_message.is_empty() {
627 system_message.push_str("\n\n");
628 }
629 system_message.push_str(&message.string_contents());
630 }
631 }
632 }
633
634 anthropic::Request {
635 model,
636 messages: new_messages,
637 max_tokens: max_output_tokens,
638 system: if system_message.is_empty() {
639 None
640 } else {
641 Some(anthropic::StringOrContents::String(system_message))
642 },
643 thinking: if let AnthropicModelMode::Thinking { budget_tokens } = mode {
644 Some(anthropic::Thinking::Enabled { budget_tokens })
645 } else {
646 None
647 },
648 tools: request
649 .tools
650 .into_iter()
651 .map(|tool| anthropic::Tool {
652 name: tool.name,
653 description: tool.description,
654 input_schema: tool.input_schema,
655 })
656 .collect(),
657 tool_choice: request.tool_choice.map(|choice| match choice {
658 LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
659 LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
660 LanguageModelToolChoice::None => anthropic::ToolChoice::None,
661 }),
662 metadata: None,
663 stop_sequences: Vec::new(),
664 temperature: request.temperature.or(Some(default_temperature)),
665 top_k: None,
666 top_p: None,
667 }
668}
669
670pub struct AnthropicEventMapper {
671 tool_uses_by_index: HashMap<usize, RawToolUse>,
672 usage: Usage,
673 stop_reason: StopReason,
674}
675
676impl AnthropicEventMapper {
677 pub fn new() -> Self {
678 Self {
679 tool_uses_by_index: HashMap::default(),
680 usage: Usage::default(),
681 stop_reason: StopReason::EndTurn,
682 }
683 }
684
685 pub fn map_stream(
686 mut self,
687 events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
688 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
689 {
690 events.flat_map(move |event| {
691 futures::stream::iter(match event {
692 Ok(event) => self.map_event(event),
693 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
694 })
695 })
696 }
697
698 pub fn map_event(
699 &mut self,
700 event: Event,
701 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
702 match event {
703 Event::ContentBlockStart {
704 index,
705 content_block,
706 } => match content_block {
707 ResponseContent::Text { text } => {
708 vec![Ok(LanguageModelCompletionEvent::Text(text))]
709 }
710 ResponseContent::Thinking { thinking } => {
711 vec![Ok(LanguageModelCompletionEvent::Thinking {
712 text: thinking,
713 signature: None,
714 })]
715 }
716 ResponseContent::RedactedThinking { .. } => {
717 // Redacted thinking is encrypted and not accessible to the user, see:
718 // https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#suggestions-for-handling-redacted-thinking-in-production
719 Vec::new()
720 }
721 ResponseContent::ToolUse { id, name, .. } => {
722 self.tool_uses_by_index.insert(
723 index,
724 RawToolUse {
725 id,
726 name,
727 input_json: String::new(),
728 },
729 );
730 Vec::new()
731 }
732 },
733 Event::ContentBlockDelta { index, delta } => match delta {
734 ContentDelta::TextDelta { text } => {
735 vec![Ok(LanguageModelCompletionEvent::Text(text))]
736 }
737 ContentDelta::ThinkingDelta { thinking } => {
738 vec![Ok(LanguageModelCompletionEvent::Thinking {
739 text: thinking,
740 signature: None,
741 })]
742 }
743 ContentDelta::SignatureDelta { signature } => {
744 vec![Ok(LanguageModelCompletionEvent::Thinking {
745 text: "".to_string(),
746 signature: Some(signature),
747 })]
748 }
749 ContentDelta::InputJsonDelta { partial_json } => {
750 if let Some(tool_use) = self.tool_uses_by_index.get_mut(&index) {
751 tool_use.input_json.push_str(&partial_json);
752
753 // Try to convert invalid (incomplete) JSON into
754 // valid JSON that serde can accept, e.g. by closing
755 // unclosed delimiters. This way, we can update the
756 // UI with whatever has been streamed back so far.
757 if let Ok(input) = serde_json::Value::from_str(
758 &partial_json_fixer::fix_json(&tool_use.input_json),
759 ) {
760 return vec![Ok(LanguageModelCompletionEvent::ToolUse(
761 LanguageModelToolUse {
762 id: tool_use.id.clone().into(),
763 name: tool_use.name.clone().into(),
764 is_input_complete: false,
765 raw_input: tool_use.input_json.clone(),
766 input,
767 },
768 ))];
769 }
770 }
771 return vec![];
772 }
773 },
774 Event::ContentBlockStop { index } => {
775 if let Some(tool_use) = self.tool_uses_by_index.remove(&index) {
776 let input_json = tool_use.input_json.trim();
777 let input_value = if input_json.is_empty() {
778 Ok(serde_json::Value::Object(serde_json::Map::default()))
779 } else {
780 serde_json::Value::from_str(input_json)
781 };
782 let event_result = match input_value {
783 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
784 LanguageModelToolUse {
785 id: tool_use.id.into(),
786 name: tool_use.name.into(),
787 is_input_complete: true,
788 input,
789 raw_input: tool_use.input_json.clone(),
790 },
791 )),
792 Err(json_parse_err) => Err(LanguageModelCompletionError::BadInputJson {
793 id: tool_use.id.into(),
794 tool_name: tool_use.name.into(),
795 raw_input: input_json.into(),
796 json_parse_error: json_parse_err.to_string(),
797 }),
798 };
799
800 vec![event_result]
801 } else {
802 Vec::new()
803 }
804 }
805 Event::MessageStart { message } => {
806 update_usage(&mut self.usage, &message.usage);
807 vec![
808 Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
809 &self.usage,
810 ))),
811 Ok(LanguageModelCompletionEvent::StartMessage {
812 message_id: message.id,
813 }),
814 ]
815 }
816 Event::MessageDelta { delta, usage } => {
817 update_usage(&mut self.usage, &usage);
818 if let Some(stop_reason) = delta.stop_reason.as_deref() {
819 self.stop_reason = match stop_reason {
820 "end_turn" => StopReason::EndTurn,
821 "max_tokens" => StopReason::MaxTokens,
822 "tool_use" => StopReason::ToolUse,
823 "refusal" => StopReason::Refusal,
824 _ => {
825 log::error!("Unexpected anthropic stop_reason: {stop_reason}");
826 StopReason::EndTurn
827 }
828 };
829 }
830 vec![Ok(LanguageModelCompletionEvent::UsageUpdate(
831 convert_usage(&self.usage),
832 ))]
833 }
834 Event::MessageStop => {
835 vec![Ok(LanguageModelCompletionEvent::Stop(self.stop_reason))]
836 }
837 Event::Error { error } => {
838 vec![Err(LanguageModelCompletionError::Other(anyhow!(
839 AnthropicError::ApiError(error)
840 )))]
841 }
842 _ => Vec::new(),
843 }
844 }
845}
846
847struct RawToolUse {
848 id: String,
849 name: String,
850 input_json: String,
851}
852
853pub fn anthropic_err_to_anyhow(err: AnthropicError) -> anyhow::Error {
854 if let AnthropicError::ApiError(api_err) = &err {
855 if let Some(tokens) = api_err.match_window_exceeded() {
856 return anyhow!(LanguageModelKnownError::ContextWindowLimitExceeded { tokens });
857 }
858 }
859
860 anyhow!(err)
861}
862
863/// Updates usage data by preferring counts from `new`.
864fn update_usage(usage: &mut Usage, new: &Usage) {
865 if let Some(input_tokens) = new.input_tokens {
866 usage.input_tokens = Some(input_tokens);
867 }
868 if let Some(output_tokens) = new.output_tokens {
869 usage.output_tokens = Some(output_tokens);
870 }
871 if let Some(cache_creation_input_tokens) = new.cache_creation_input_tokens {
872 usage.cache_creation_input_tokens = Some(cache_creation_input_tokens);
873 }
874 if let Some(cache_read_input_tokens) = new.cache_read_input_tokens {
875 usage.cache_read_input_tokens = Some(cache_read_input_tokens);
876 }
877}
878
879fn convert_usage(usage: &Usage) -> language_model::TokenUsage {
880 language_model::TokenUsage {
881 input_tokens: usage.input_tokens.unwrap_or(0),
882 output_tokens: usage.output_tokens.unwrap_or(0),
883 cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or(0),
884 cache_read_input_tokens: usage.cache_read_input_tokens.unwrap_or(0),
885 }
886}
887
888struct ConfigurationView {
889 api_key_editor: Entity<Editor>,
890 state: gpui::Entity<State>,
891 load_credentials_task: Option<Task<()>>,
892}
893
894impl ConfigurationView {
895 const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
896
897 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
898 cx.observe(&state, |_, _, cx| {
899 cx.notify();
900 })
901 .detach();
902
903 let load_credentials_task = Some(cx.spawn({
904 let state = state.clone();
905 async move |this, cx| {
906 if let Some(task) = state
907 .update(cx, |state, cx| state.authenticate(cx))
908 .log_err()
909 {
910 // We don't log an error, because "not signed in" is also an error.
911 let _ = task.await;
912 }
913 this.update(cx, |this, cx| {
914 this.load_credentials_task = None;
915 cx.notify();
916 })
917 .log_err();
918 }
919 }));
920
921 Self {
922 api_key_editor: cx.new(|cx| {
923 let mut editor = Editor::single_line(window, cx);
924 editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
925 editor
926 }),
927 state,
928 load_credentials_task,
929 }
930 }
931
932 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
933 let api_key = self.api_key_editor.read(cx).text(cx);
934 if api_key.is_empty() {
935 return;
936 }
937
938 let state = self.state.clone();
939 cx.spawn_in(window, async move |_, cx| {
940 state
941 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
942 .await
943 })
944 .detach_and_log_err(cx);
945
946 cx.notify();
947 }
948
949 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
950 self.api_key_editor
951 .update(cx, |editor, cx| editor.set_text("", window, cx));
952
953 let state = self.state.clone();
954 cx.spawn_in(window, async move |_, cx| {
955 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
956 })
957 .detach_and_log_err(cx);
958
959 cx.notify();
960 }
961
962 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
963 let settings = ThemeSettings::get_global(cx);
964 let text_style = TextStyle {
965 color: cx.theme().colors().text,
966 font_family: settings.ui_font.family.clone(),
967 font_features: settings.ui_font.features.clone(),
968 font_fallbacks: settings.ui_font.fallbacks.clone(),
969 font_size: rems(0.875).into(),
970 font_weight: settings.ui_font.weight,
971 font_style: FontStyle::Normal,
972 line_height: relative(1.3),
973 white_space: WhiteSpace::Normal,
974 ..Default::default()
975 };
976 EditorElement::new(
977 &self.api_key_editor,
978 EditorStyle {
979 background: cx.theme().colors().editor_background,
980 local_player: cx.theme().players().local(),
981 text: text_style,
982 ..Default::default()
983 },
984 )
985 }
986
987 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
988 !self.state.read(cx).is_authenticated()
989 }
990}
991
992impl Render for ConfigurationView {
993 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
994 let env_var_set = self.state.read(cx).api_key_from_env;
995
996 if self.load_credentials_task.is_some() {
997 div().child(Label::new("Loading credentials...")).into_any()
998 } else if self.should_render_editor(cx) {
999 v_flex()
1000 .size_full()
1001 .on_action(cx.listener(Self::save_api_key))
1002 .child(Label::new("To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:"))
1003 .child(
1004 List::new()
1005 .child(
1006 InstructionListItem::new(
1007 "Create one by visiting",
1008 Some("Anthropic's settings"),
1009 Some("https://console.anthropic.com/settings/keys")
1010 )
1011 )
1012 .child(
1013 InstructionListItem::text_only("Paste your API key below and hit enter to start using the assistant")
1014 )
1015 )
1016 .child(
1017 h_flex()
1018 .w_full()
1019 .my_2()
1020 .px_2()
1021 .py_1()
1022 .bg(cx.theme().colors().editor_background)
1023 .border_1()
1024 .border_color(cx.theme().colors().border)
1025 .rounded_sm()
1026 .child(self.render_api_key_editor(cx)),
1027 )
1028 .child(
1029 Label::new(
1030 format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
1031 )
1032 .size(LabelSize::Small)
1033 .color(Color::Muted),
1034 )
1035 .into_any()
1036 } else {
1037 h_flex()
1038 .mt_1()
1039 .p_1()
1040 .justify_between()
1041 .rounded_md()
1042 .border_1()
1043 .border_color(cx.theme().colors().border)
1044 .bg(cx.theme().colors().background)
1045 .child(
1046 h_flex()
1047 .gap_1()
1048 .child(Icon::new(IconName::Check).color(Color::Success))
1049 .child(Label::new(if env_var_set {
1050 format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
1051 } else {
1052 "API key configured.".to_string()
1053 })),
1054 )
1055 .child(
1056 Button::new("reset-key", "Reset Key")
1057 .label_size(LabelSize::Small)
1058 .icon(Some(IconName::Trash))
1059 .icon_size(IconSize::Small)
1060 .icon_position(IconPosition::Start)
1061 .disabled(env_var_set)
1062 .when(env_var_set, |this| {
1063 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
1064 })
1065 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
1066 )
1067 .into_any()
1068 }
1069 }
1070}