1use anthropic::{stream_completion, Request, RequestMessage};
2use anyhow::{anyhow, Result};
3use collections::BTreeMap;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
6use gpui::{
7 AnyView, AppContext, AsyncAppContext, FontStyle, Subscription, Task, TextStyle, View,
8 WhiteSpace,
9};
10use http_client::HttpClient;
11use settings::{Settings, SettingsStore};
12use std::{sync::Arc, time::Duration};
13use strum::IntoEnumIterator;
14use theme::ThemeSettings;
15use ui::prelude::*;
16use util::ResultExt;
17
18use crate::{
19 settings::AllLanguageModelSettings, LanguageModel, LanguageModelId, LanguageModelName,
20 LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
21 LanguageModelProviderState, LanguageModelRequest, LanguageModelRequestMessage, Role,
22};
23
24const PROVIDER_ID: &str = "anthropic";
25const PROVIDER_NAME: &str = "Anthropic";
26
27#[derive(Default, Clone, Debug, PartialEq)]
28pub struct AnthropicSettings {
29 pub api_url: String,
30 pub low_speed_timeout: Option<Duration>,
31 pub available_models: Vec<anthropic::Model>,
32}
33
34pub struct AnthropicLanguageModelProvider {
35 http_client: Arc<dyn HttpClient>,
36 state: gpui::Model<State>,
37}
38
39struct State {
40 api_key: Option<String>,
41 _subscription: Subscription,
42}
43
44impl AnthropicLanguageModelProvider {
45 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Self {
46 let state = cx.new_model(|cx| State {
47 api_key: None,
48 _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
49 cx.notify();
50 }),
51 });
52
53 Self { http_client, state }
54 }
55}
56impl LanguageModelProviderState for AnthropicLanguageModelProvider {
57 fn subscribe<T: 'static>(&self, cx: &mut gpui::ModelContext<T>) -> Option<gpui::Subscription> {
58 Some(cx.observe(&self.state, |_, _, cx| {
59 cx.notify();
60 }))
61 }
62}
63
64impl LanguageModelProvider for AnthropicLanguageModelProvider {
65 fn id(&self) -> LanguageModelProviderId {
66 LanguageModelProviderId(PROVIDER_ID.into())
67 }
68
69 fn name(&self) -> LanguageModelProviderName {
70 LanguageModelProviderName(PROVIDER_NAME.into())
71 }
72
73 fn provided_models(&self, cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
74 let mut models = BTreeMap::default();
75
76 // Add base models from anthropic::Model::iter()
77 for model in anthropic::Model::iter() {
78 if !matches!(model, anthropic::Model::Custom { .. }) {
79 models.insert(model.id().to_string(), model);
80 }
81 }
82
83 // Override with available models from settings
84 for model in AllLanguageModelSettings::get_global(cx)
85 .anthropic
86 .available_models
87 .iter()
88 {
89 models.insert(model.id().to_string(), model.clone());
90 }
91
92 models
93 .into_values()
94 .map(|model| {
95 Arc::new(AnthropicModel {
96 id: LanguageModelId::from(model.id().to_string()),
97 model,
98 state: self.state.clone(),
99 http_client: self.http_client.clone(),
100 }) as Arc<dyn LanguageModel>
101 })
102 .collect()
103 }
104
105 fn is_authenticated(&self, cx: &AppContext) -> bool {
106 self.state.read(cx).api_key.is_some()
107 }
108
109 fn authenticate(&self, cx: &AppContext) -> Task<Result<()>> {
110 if self.is_authenticated(cx) {
111 Task::ready(Ok(()))
112 } else {
113 let api_url = AllLanguageModelSettings::get_global(cx)
114 .anthropic
115 .api_url
116 .clone();
117 let state = self.state.clone();
118 cx.spawn(|mut cx| async move {
119 let api_key = if let Ok(api_key) = std::env::var("ANTHROPIC_API_KEY") {
120 api_key
121 } else {
122 let (_, api_key) = cx
123 .update(|cx| cx.read_credentials(&api_url))?
124 .await?
125 .ok_or_else(|| anyhow!("credentials not found"))?;
126 String::from_utf8(api_key)?
127 };
128
129 state.update(&mut cx, |this, cx| {
130 this.api_key = Some(api_key);
131 cx.notify();
132 })
133 })
134 }
135 }
136
137 fn authentication_prompt(&self, cx: &mut WindowContext) -> AnyView {
138 cx.new_view(|cx| AuthenticationPrompt::new(self.state.clone(), cx))
139 .into()
140 }
141
142 fn reset_credentials(&self, cx: &AppContext) -> Task<Result<()>> {
143 let state = self.state.clone();
144 let delete_credentials =
145 cx.delete_credentials(&AllLanguageModelSettings::get_global(cx).anthropic.api_url);
146 cx.spawn(|mut cx| async move {
147 delete_credentials.await.log_err();
148 state.update(&mut cx, |this, cx| {
149 this.api_key = None;
150 cx.notify();
151 })
152 })
153 }
154}
155
156pub struct AnthropicModel {
157 id: LanguageModelId,
158 model: anthropic::Model,
159 state: gpui::Model<State>,
160 http_client: Arc<dyn HttpClient>,
161}
162
163impl AnthropicModel {
164 fn to_anthropic_request(&self, mut request: LanguageModelRequest) -> Request {
165 preprocess_anthropic_request(&mut request);
166
167 let mut system_message = String::new();
168 if request
169 .messages
170 .first()
171 .map_or(false, |message| message.role == Role::System)
172 {
173 system_message = request.messages.remove(0).content;
174 }
175
176 Request {
177 model: self.model.clone(),
178 messages: request
179 .messages
180 .iter()
181 .map(|msg| RequestMessage {
182 role: match msg.role {
183 Role::User => anthropic::Role::User,
184 Role::Assistant => anthropic::Role::Assistant,
185 Role::System => unreachable!("filtered out by preprocess_request"),
186 },
187 content: msg.content.clone(),
188 })
189 .collect(),
190 stream: true,
191 system: system_message,
192 max_tokens: 4092,
193 }
194 }
195}
196
197pub fn count_anthropic_tokens(
198 request: LanguageModelRequest,
199 cx: &AppContext,
200) -> BoxFuture<'static, Result<usize>> {
201 cx.background_executor()
202 .spawn(async move {
203 let messages = request
204 .messages
205 .into_iter()
206 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
207 role: match message.role {
208 Role::User => "user".into(),
209 Role::Assistant => "assistant".into(),
210 Role::System => "system".into(),
211 },
212 content: Some(message.content),
213 name: None,
214 function_call: None,
215 })
216 .collect::<Vec<_>>();
217
218 // Tiktoken doesn't yet support these models, so we manually use the
219 // same tokenizer as GPT-4.
220 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
221 })
222 .boxed()
223}
224
225impl LanguageModel for AnthropicModel {
226 fn id(&self) -> LanguageModelId {
227 self.id.clone()
228 }
229
230 fn name(&self) -> LanguageModelName {
231 LanguageModelName::from(self.model.display_name().to_string())
232 }
233
234 fn provider_id(&self) -> LanguageModelProviderId {
235 LanguageModelProviderId(PROVIDER_ID.into())
236 }
237
238 fn provider_name(&self) -> LanguageModelProviderName {
239 LanguageModelProviderName(PROVIDER_NAME.into())
240 }
241
242 fn telemetry_id(&self) -> String {
243 format!("anthropic/{}", self.model.id())
244 }
245
246 fn max_token_count(&self) -> usize {
247 self.model.max_token_count()
248 }
249
250 fn count_tokens(
251 &self,
252 request: LanguageModelRequest,
253 cx: &AppContext,
254 ) -> BoxFuture<'static, Result<usize>> {
255 count_anthropic_tokens(request, cx)
256 }
257
258 fn stream_completion(
259 &self,
260 request: LanguageModelRequest,
261 cx: &AsyncAppContext,
262 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
263 let request = self.to_anthropic_request(request);
264
265 let http_client = self.http_client.clone();
266
267 let Ok((api_key, api_url, low_speed_timeout)) = cx.read_model(&self.state, |state, cx| {
268 let settings = &AllLanguageModelSettings::get_global(cx).anthropic;
269 (
270 state.api_key.clone(),
271 settings.api_url.clone(),
272 settings.low_speed_timeout,
273 )
274 }) else {
275 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
276 };
277
278 async move {
279 let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
280 let request = stream_completion(
281 http_client.as_ref(),
282 &api_url,
283 &api_key,
284 request,
285 low_speed_timeout,
286 );
287 let response = request.await?;
288 let stream = response
289 .filter_map(|response| async move {
290 match response {
291 Ok(response) => match response {
292 anthropic::ResponseEvent::ContentBlockStart {
293 content_block, ..
294 } => match content_block {
295 anthropic::ContentBlock::Text { text } => Some(Ok(text)),
296 },
297 anthropic::ResponseEvent::ContentBlockDelta { delta, .. } => {
298 match delta {
299 anthropic::TextDelta::TextDelta { text } => Some(Ok(text)),
300 }
301 }
302 _ => None,
303 },
304 Err(error) => Some(Err(error)),
305 }
306 })
307 .boxed();
308 Ok(stream)
309 }
310 .boxed()
311 }
312}
313
314pub fn preprocess_anthropic_request(request: &mut LanguageModelRequest) {
315 let mut new_messages: Vec<LanguageModelRequestMessage> = Vec::new();
316 let mut system_message = String::new();
317
318 for message in request.messages.drain(..) {
319 if message.content.is_empty() {
320 continue;
321 }
322
323 match message.role {
324 Role::User | Role::Assistant => {
325 if let Some(last_message) = new_messages.last_mut() {
326 if last_message.role == message.role {
327 last_message.content.push_str("\n\n");
328 last_message.content.push_str(&message.content);
329 continue;
330 }
331 }
332
333 new_messages.push(message);
334 }
335 Role::System => {
336 if !system_message.is_empty() {
337 system_message.push_str("\n\n");
338 }
339 system_message.push_str(&message.content);
340 }
341 }
342 }
343
344 if !system_message.is_empty() {
345 new_messages.insert(
346 0,
347 LanguageModelRequestMessage {
348 role: Role::System,
349 content: system_message,
350 },
351 );
352 }
353
354 request.messages = new_messages;
355}
356
357struct AuthenticationPrompt {
358 api_key: View<Editor>,
359 state: gpui::Model<State>,
360}
361
362impl AuthenticationPrompt {
363 fn new(state: gpui::Model<State>, cx: &mut WindowContext) -> Self {
364 Self {
365 api_key: cx.new_view(|cx| {
366 let mut editor = Editor::single_line(cx);
367 editor.set_placeholder_text(
368 "sk-000000000000000000000000000000000000000000000000",
369 cx,
370 );
371 editor
372 }),
373 state,
374 }
375 }
376
377 fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
378 let api_key = self.api_key.read(cx).text(cx);
379 if api_key.is_empty() {
380 return;
381 }
382
383 let write_credentials = cx.write_credentials(
384 AllLanguageModelSettings::get_global(cx)
385 .anthropic
386 .api_url
387 .as_str(),
388 "Bearer",
389 api_key.as_bytes(),
390 );
391 let state = self.state.clone();
392 cx.spawn(|_, mut cx| async move {
393 write_credentials.await?;
394
395 state.update(&mut cx, |this, cx| {
396 this.api_key = Some(api_key);
397 cx.notify();
398 })
399 })
400 .detach_and_log_err(cx);
401 }
402
403 fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
404 let settings = ThemeSettings::get_global(cx);
405 let text_style = TextStyle {
406 color: cx.theme().colors().text,
407 font_family: settings.ui_font.family.clone(),
408 font_features: settings.ui_font.features.clone(),
409 font_size: rems(0.875).into(),
410 font_weight: settings.ui_font.weight,
411 font_style: FontStyle::Normal,
412 line_height: relative(1.3),
413 background_color: None,
414 underline: None,
415 strikethrough: None,
416 white_space: WhiteSpace::Normal,
417 };
418 EditorElement::new(
419 &self.api_key,
420 EditorStyle {
421 background: cx.theme().colors().editor_background,
422 local_player: cx.theme().players().local(),
423 text: text_style,
424 ..Default::default()
425 },
426 )
427 }
428}
429
430impl Render for AuthenticationPrompt {
431 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
432 const INSTRUCTIONS: [&str; 4] = [
433 "To use the assistant panel or inline assistant, you need to add your Anthropic API key.",
434 "You can create an API key at: https://console.anthropic.com/settings/keys",
435 "",
436 "Paste your Anthropic API key below and hit enter to use the assistant:",
437 ];
438
439 v_flex()
440 .p_4()
441 .size_full()
442 .on_action(cx.listener(Self::save_api_key))
443 .children(
444 INSTRUCTIONS.map(|instruction| Label::new(instruction).size(LabelSize::Small)),
445 )
446 .child(
447 h_flex()
448 .w_full()
449 .my_2()
450 .px_2()
451 .py_1()
452 .bg(cx.theme().colors().editor_background)
453 .rounded_md()
454 .child(self.render_api_key_editor(cx)),
455 )
456 .child(
457 Label::new(
458 "You can also assign the ANTHROPIC_API_KEY environment variable and restart Zed.",
459 )
460 .size(LabelSize::Small),
461 )
462 .child(
463 h_flex()
464 .gap_2()
465 .child(Label::new("Click on").size(LabelSize::Small))
466 .child(Icon::new(IconName::ZedAssistant).size(IconSize::XSmall))
467 .child(
468 Label::new("in the status bar to close this panel.").size(LabelSize::Small),
469 ),
470 )
471 .into_any()
472 }
473}