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 mut anthropic_message_content: Vec<anthropic::RequestContent> = message
527 .content
528 .into_iter()
529 .filter_map(|content| match content {
530 MessageContent::Text(text) => {
531 if !text.is_empty() {
532 Some(anthropic::RequestContent::Text {
533 text,
534 cache_control: None,
535 })
536 } else {
537 None
538 }
539 }
540 MessageContent::Thinking {
541 text: thinking,
542 signature,
543 } => {
544 if !thinking.is_empty() {
545 Some(anthropic::RequestContent::Thinking {
546 thinking,
547 signature: signature.unwrap_or_default(),
548 cache_control: None,
549 })
550 } else {
551 None
552 }
553 }
554 MessageContent::RedactedThinking(data) => {
555 if !data.is_empty() {
556 Some(anthropic::RequestContent::RedactedThinking {
557 data: String::from_utf8(data).ok()?,
558 })
559 } else {
560 None
561 }
562 }
563 MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
564 source: anthropic::ImageSource {
565 source_type: "base64".to_string(),
566 media_type: "image/png".to_string(),
567 data: image.source.to_string(),
568 },
569 cache_control: None,
570 }),
571 MessageContent::ToolUse(tool_use) => {
572 Some(anthropic::RequestContent::ToolUse {
573 id: tool_use.id.to_string(),
574 name: tool_use.name.to_string(),
575 input: tool_use.input,
576 cache_control: None,
577 })
578 }
579 MessageContent::ToolResult(tool_result) => {
580 Some(anthropic::RequestContent::ToolResult {
581 tool_use_id: tool_result.tool_use_id.to_string(),
582 is_error: tool_result.is_error,
583 content: match tool_result.content {
584 LanguageModelToolResultContent::Text(text) => {
585 ToolResultContent::Plain(text.to_string())
586 }
587 LanguageModelToolResultContent::Image(image) => {
588 ToolResultContent::Multipart(vec![ToolResultPart::Image {
589 source: anthropic::ImageSource {
590 source_type: "base64".to_string(),
591 media_type: "image/png".to_string(),
592 data: image.source.to_string(),
593 },
594 }])
595 }
596 },
597 cache_control: None,
598 })
599 }
600 })
601 .collect();
602 let anthropic_role = match message.role {
603 Role::User => anthropic::Role::User,
604 Role::Assistant => anthropic::Role::Assistant,
605 Role::System => unreachable!("System role should never occur here"),
606 };
607 if let Some(last_message) = new_messages.last_mut() {
608 if last_message.role == anthropic_role {
609 last_message.content.extend(anthropic_message_content);
610 continue;
611 }
612 }
613
614 // Mark the last segment of the message as cached
615 if message.cache {
616 let cache_control_value = Some(anthropic::CacheControl {
617 cache_type: anthropic::CacheControlType::Ephemeral,
618 });
619 for message_content in anthropic_message_content.iter_mut().rev() {
620 match message_content {
621 anthropic::RequestContent::RedactedThinking { .. } => {
622 // Caching is not possible, fallback to next message
623 }
624 anthropic::RequestContent::Text { cache_control, .. }
625 | anthropic::RequestContent::Thinking { cache_control, .. }
626 | anthropic::RequestContent::Image { cache_control, .. }
627 | anthropic::RequestContent::ToolUse { cache_control, .. }
628 | anthropic::RequestContent::ToolResult { cache_control, .. } => {
629 *cache_control = cache_control_value;
630 break;
631 }
632 }
633 }
634 }
635
636 new_messages.push(anthropic::Message {
637 role: anthropic_role,
638 content: anthropic_message_content,
639 });
640 }
641 Role::System => {
642 if !system_message.is_empty() {
643 system_message.push_str("\n\n");
644 }
645 system_message.push_str(&message.string_contents());
646 }
647 }
648 }
649
650 anthropic::Request {
651 model,
652 messages: new_messages,
653 max_tokens: max_output_tokens,
654 system: if system_message.is_empty() {
655 None
656 } else {
657 Some(anthropic::StringOrContents::String(system_message))
658 },
659 thinking: if let AnthropicModelMode::Thinking { budget_tokens } = mode {
660 Some(anthropic::Thinking::Enabled { budget_tokens })
661 } else {
662 None
663 },
664 tools: request
665 .tools
666 .into_iter()
667 .map(|tool| anthropic::Tool {
668 name: tool.name,
669 description: tool.description,
670 input_schema: tool.input_schema,
671 })
672 .collect(),
673 tool_choice: request.tool_choice.map(|choice| match choice {
674 LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
675 LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
676 LanguageModelToolChoice::None => anthropic::ToolChoice::None,
677 }),
678 metadata: None,
679 stop_sequences: Vec::new(),
680 temperature: request.temperature.or(Some(default_temperature)),
681 top_k: None,
682 top_p: None,
683 }
684}
685
686pub struct AnthropicEventMapper {
687 tool_uses_by_index: HashMap<usize, RawToolUse>,
688 usage: Usage,
689 stop_reason: StopReason,
690}
691
692impl AnthropicEventMapper {
693 pub fn new() -> Self {
694 Self {
695 tool_uses_by_index: HashMap::default(),
696 usage: Usage::default(),
697 stop_reason: StopReason::EndTurn,
698 }
699 }
700
701 pub fn map_stream(
702 mut self,
703 events: Pin<Box<dyn Send + Stream<Item = Result<Event, AnthropicError>>>>,
704 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
705 {
706 events.flat_map(move |event| {
707 futures::stream::iter(match event {
708 Ok(event) => self.map_event(event),
709 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
710 })
711 })
712 }
713
714 pub fn map_event(
715 &mut self,
716 event: Event,
717 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
718 match event {
719 Event::ContentBlockStart {
720 index,
721 content_block,
722 } => match content_block {
723 ResponseContent::Text { text } => {
724 vec![Ok(LanguageModelCompletionEvent::Text(text))]
725 }
726 ResponseContent::Thinking { thinking } => {
727 vec![Ok(LanguageModelCompletionEvent::Thinking {
728 text: thinking,
729 signature: None,
730 })]
731 }
732 ResponseContent::RedactedThinking { .. } => {
733 // Redacted thinking is encrypted and not accessible to the user, see:
734 // https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#suggestions-for-handling-redacted-thinking-in-production
735 Vec::new()
736 }
737 ResponseContent::ToolUse { id, name, .. } => {
738 self.tool_uses_by_index.insert(
739 index,
740 RawToolUse {
741 id,
742 name,
743 input_json: String::new(),
744 },
745 );
746 Vec::new()
747 }
748 },
749 Event::ContentBlockDelta { index, delta } => match delta {
750 ContentDelta::TextDelta { text } => {
751 vec![Ok(LanguageModelCompletionEvent::Text(text))]
752 }
753 ContentDelta::ThinkingDelta { thinking } => {
754 vec![Ok(LanguageModelCompletionEvent::Thinking {
755 text: thinking,
756 signature: None,
757 })]
758 }
759 ContentDelta::SignatureDelta { signature } => {
760 vec![Ok(LanguageModelCompletionEvent::Thinking {
761 text: "".to_string(),
762 signature: Some(signature),
763 })]
764 }
765 ContentDelta::InputJsonDelta { partial_json } => {
766 if let Some(tool_use) = self.tool_uses_by_index.get_mut(&index) {
767 tool_use.input_json.push_str(&partial_json);
768
769 // Try to convert invalid (incomplete) JSON into
770 // valid JSON that serde can accept, e.g. by closing
771 // unclosed delimiters. This way, we can update the
772 // UI with whatever has been streamed back so far.
773 if let Ok(input) = serde_json::Value::from_str(
774 &partial_json_fixer::fix_json(&tool_use.input_json),
775 ) {
776 return vec![Ok(LanguageModelCompletionEvent::ToolUse(
777 LanguageModelToolUse {
778 id: tool_use.id.clone().into(),
779 name: tool_use.name.clone().into(),
780 is_input_complete: false,
781 raw_input: tool_use.input_json.clone(),
782 input,
783 },
784 ))];
785 }
786 }
787 return vec![];
788 }
789 },
790 Event::ContentBlockStop { index } => {
791 if let Some(tool_use) = self.tool_uses_by_index.remove(&index) {
792 let input_json = tool_use.input_json.trim();
793 let input_value = if input_json.is_empty() {
794 Ok(serde_json::Value::Object(serde_json::Map::default()))
795 } else {
796 serde_json::Value::from_str(input_json)
797 };
798 let event_result = match input_value {
799 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
800 LanguageModelToolUse {
801 id: tool_use.id.into(),
802 name: tool_use.name.into(),
803 is_input_complete: true,
804 input,
805 raw_input: tool_use.input_json.clone(),
806 },
807 )),
808 Err(json_parse_err) => Err(LanguageModelCompletionError::BadInputJson {
809 id: tool_use.id.into(),
810 tool_name: tool_use.name.into(),
811 raw_input: input_json.into(),
812 json_parse_error: json_parse_err.to_string(),
813 }),
814 };
815
816 vec![event_result]
817 } else {
818 Vec::new()
819 }
820 }
821 Event::MessageStart { message } => {
822 update_usage(&mut self.usage, &message.usage);
823 vec![
824 Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
825 &self.usage,
826 ))),
827 Ok(LanguageModelCompletionEvent::StartMessage {
828 message_id: message.id,
829 }),
830 ]
831 }
832 Event::MessageDelta { delta, usage } => {
833 update_usage(&mut self.usage, &usage);
834 if let Some(stop_reason) = delta.stop_reason.as_deref() {
835 self.stop_reason = match stop_reason {
836 "end_turn" => StopReason::EndTurn,
837 "max_tokens" => StopReason::MaxTokens,
838 "tool_use" => StopReason::ToolUse,
839 "refusal" => StopReason::Refusal,
840 _ => {
841 log::error!("Unexpected anthropic stop_reason: {stop_reason}");
842 StopReason::EndTurn
843 }
844 };
845 }
846 vec![Ok(LanguageModelCompletionEvent::UsageUpdate(
847 convert_usage(&self.usage),
848 ))]
849 }
850 Event::MessageStop => {
851 vec![Ok(LanguageModelCompletionEvent::Stop(self.stop_reason))]
852 }
853 Event::Error { error } => {
854 vec![Err(LanguageModelCompletionError::Other(anyhow!(
855 AnthropicError::ApiError(error)
856 )))]
857 }
858 _ => Vec::new(),
859 }
860 }
861}
862
863struct RawToolUse {
864 id: String,
865 name: String,
866 input_json: String,
867}
868
869pub fn anthropic_err_to_anyhow(err: AnthropicError) -> anyhow::Error {
870 if let AnthropicError::ApiError(api_err) = &err {
871 if let Some(tokens) = api_err.match_window_exceeded() {
872 return anyhow!(LanguageModelKnownError::ContextWindowLimitExceeded { tokens });
873 }
874 }
875
876 anyhow!(err)
877}
878
879/// Updates usage data by preferring counts from `new`.
880fn update_usage(usage: &mut Usage, new: &Usage) {
881 if let Some(input_tokens) = new.input_tokens {
882 usage.input_tokens = Some(input_tokens);
883 }
884 if let Some(output_tokens) = new.output_tokens {
885 usage.output_tokens = Some(output_tokens);
886 }
887 if let Some(cache_creation_input_tokens) = new.cache_creation_input_tokens {
888 usage.cache_creation_input_tokens = Some(cache_creation_input_tokens);
889 }
890 if let Some(cache_read_input_tokens) = new.cache_read_input_tokens {
891 usage.cache_read_input_tokens = Some(cache_read_input_tokens);
892 }
893}
894
895fn convert_usage(usage: &Usage) -> language_model::TokenUsage {
896 language_model::TokenUsage {
897 input_tokens: usage.input_tokens.unwrap_or(0),
898 output_tokens: usage.output_tokens.unwrap_or(0),
899 cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or(0),
900 cache_read_input_tokens: usage.cache_read_input_tokens.unwrap_or(0),
901 }
902}
903
904struct ConfigurationView {
905 api_key_editor: Entity<Editor>,
906 state: gpui::Entity<State>,
907 load_credentials_task: Option<Task<()>>,
908}
909
910impl ConfigurationView {
911 const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
912
913 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
914 cx.observe(&state, |_, _, cx| {
915 cx.notify();
916 })
917 .detach();
918
919 let load_credentials_task = Some(cx.spawn({
920 let state = state.clone();
921 async move |this, cx| {
922 if let Some(task) = state
923 .update(cx, |state, cx| state.authenticate(cx))
924 .log_err()
925 {
926 // We don't log an error, because "not signed in" is also an error.
927 let _ = task.await;
928 }
929 this.update(cx, |this, cx| {
930 this.load_credentials_task = None;
931 cx.notify();
932 })
933 .log_err();
934 }
935 }));
936
937 Self {
938 api_key_editor: cx.new(|cx| {
939 let mut editor = Editor::single_line(window, cx);
940 editor.set_placeholder_text(Self::PLACEHOLDER_TEXT, cx);
941 editor
942 }),
943 state,
944 load_credentials_task,
945 }
946 }
947
948 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
949 let api_key = self.api_key_editor.read(cx).text(cx);
950 if api_key.is_empty() {
951 return;
952 }
953
954 let state = self.state.clone();
955 cx.spawn_in(window, async move |_, cx| {
956 state
957 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
958 .await
959 })
960 .detach_and_log_err(cx);
961
962 cx.notify();
963 }
964
965 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
966 self.api_key_editor
967 .update(cx, |editor, cx| editor.set_text("", window, cx));
968
969 let state = self.state.clone();
970 cx.spawn_in(window, async move |_, cx| {
971 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
972 })
973 .detach_and_log_err(cx);
974
975 cx.notify();
976 }
977
978 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
979 let settings = ThemeSettings::get_global(cx);
980 let text_style = TextStyle {
981 color: cx.theme().colors().text,
982 font_family: settings.ui_font.family.clone(),
983 font_features: settings.ui_font.features.clone(),
984 font_fallbacks: settings.ui_font.fallbacks.clone(),
985 font_size: rems(0.875).into(),
986 font_weight: settings.ui_font.weight,
987 font_style: FontStyle::Normal,
988 line_height: relative(1.3),
989 white_space: WhiteSpace::Normal,
990 ..Default::default()
991 };
992 EditorElement::new(
993 &self.api_key_editor,
994 EditorStyle {
995 background: cx.theme().colors().editor_background,
996 local_player: cx.theme().players().local(),
997 text: text_style,
998 ..Default::default()
999 },
1000 )
1001 }
1002
1003 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
1004 !self.state.read(cx).is_authenticated()
1005 }
1006}
1007
1008impl Render for ConfigurationView {
1009 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1010 let env_var_set = self.state.read(cx).api_key_from_env;
1011
1012 if self.load_credentials_task.is_some() {
1013 div().child(Label::new("Loading credentials...")).into_any()
1014 } else if self.should_render_editor(cx) {
1015 v_flex()
1016 .size_full()
1017 .on_action(cx.listener(Self::save_api_key))
1018 .child(Label::new("To use Zed's assistant with Anthropic, you need to add an API key. Follow these steps:"))
1019 .child(
1020 List::new()
1021 .child(
1022 InstructionListItem::new(
1023 "Create one by visiting",
1024 Some("Anthropic's settings"),
1025 Some("https://console.anthropic.com/settings/keys")
1026 )
1027 )
1028 .child(
1029 InstructionListItem::text_only("Paste your API key below and hit enter to start using the assistant")
1030 )
1031 )
1032 .child(
1033 h_flex()
1034 .w_full()
1035 .my_2()
1036 .px_2()
1037 .py_1()
1038 .bg(cx.theme().colors().editor_background)
1039 .border_1()
1040 .border_color(cx.theme().colors().border)
1041 .rounded_sm()
1042 .child(self.render_api_key_editor(cx)),
1043 )
1044 .child(
1045 Label::new(
1046 format!("You can also assign the {ANTHROPIC_API_KEY_VAR} environment variable and restart Zed."),
1047 )
1048 .size(LabelSize::Small)
1049 .color(Color::Muted),
1050 )
1051 .into_any()
1052 } else {
1053 h_flex()
1054 .mt_1()
1055 .p_1()
1056 .justify_between()
1057 .rounded_md()
1058 .border_1()
1059 .border_color(cx.theme().colors().border)
1060 .bg(cx.theme().colors().background)
1061 .child(
1062 h_flex()
1063 .gap_1()
1064 .child(Icon::new(IconName::Check).color(Color::Success))
1065 .child(Label::new(if env_var_set {
1066 format!("API key set in {ANTHROPIC_API_KEY_VAR} environment variable.")
1067 } else {
1068 "API key configured.".to_string()
1069 })),
1070 )
1071 .child(
1072 Button::new("reset-key", "Reset Key")
1073 .label_size(LabelSize::Small)
1074 .icon(Some(IconName::Trash))
1075 .icon_size(IconSize::Small)
1076 .icon_position(IconPosition::Start)
1077 .disabled(env_var_set)
1078 .when(env_var_set, |this| {
1079 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {ANTHROPIC_API_KEY_VAR} environment variable.")))
1080 })
1081 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
1082 )
1083 .into_any()
1084 }
1085 }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090 use super::*;
1091 use anthropic::AnthropicModelMode;
1092 use language_model::{LanguageModelRequestMessage, MessageContent};
1093
1094 #[test]
1095 fn test_cache_control_only_on_last_segment() {
1096 let request = LanguageModelRequest {
1097 messages: vec![LanguageModelRequestMessage {
1098 role: Role::User,
1099 content: vec![
1100 MessageContent::Text("Some prompt".to_string()),
1101 MessageContent::Image(language_model::LanguageModelImage::empty()),
1102 MessageContent::Image(language_model::LanguageModelImage::empty()),
1103 MessageContent::Image(language_model::LanguageModelImage::empty()),
1104 MessageContent::Image(language_model::LanguageModelImage::empty()),
1105 ],
1106 cache: true,
1107 }],
1108 thread_id: None,
1109 prompt_id: None,
1110 intent: None,
1111 mode: None,
1112 stop: vec![],
1113 temperature: None,
1114 tools: vec![],
1115 tool_choice: None,
1116 };
1117
1118 let anthropic_request = into_anthropic(
1119 request,
1120 "claude-3-5-sonnet".to_string(),
1121 0.7,
1122 4096,
1123 AnthropicModelMode::Default,
1124 );
1125
1126 assert_eq!(anthropic_request.messages.len(), 1);
1127
1128 let message = &anthropic_request.messages[0];
1129 assert_eq!(message.content.len(), 5);
1130
1131 assert!(matches!(
1132 message.content[0],
1133 anthropic::RequestContent::Text {
1134 cache_control: None,
1135 ..
1136 }
1137 ));
1138 for i in 1..3 {
1139 assert!(matches!(
1140 message.content[i],
1141 anthropic::RequestContent::Image {
1142 cache_control: None,
1143 ..
1144 }
1145 ));
1146 }
1147
1148 assert!(matches!(
1149 message.content[4],
1150 anthropic::RequestContent::Image {
1151 cache_control: Some(anthropic::CacheControl {
1152 cache_type: anthropic::CacheControlType::Ephemeral,
1153 }),
1154 ..
1155 }
1156 ));
1157 }
1158}