1use anyhow::{Context as _, Result, anyhow};
2use collections::BTreeMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{FutureExt, StreamExt, future::BoxFuture};
6use gpui::{
7 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
8};
9use http_client::HttpClient;
10use language_model::{
11 AuthenticateError, LanguageModel, LanguageModelCompletionEvent, LanguageModelId,
12 LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
13 LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
14};
15use open_ai::{ResponseStreamEvent, stream_completion};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18use settings::{Settings, SettingsStore};
19use std::sync::Arc;
20use strum::IntoEnumIterator;
21use theme::ThemeSettings;
22use ui::{Icon, IconName, List, Tooltip, prelude::*};
23use util::ResultExt;
24
25use crate::{AllLanguageModelSettings, ui::InstructionListItem};
26
27const PROVIDER_ID: &str = "openai";
28const PROVIDER_NAME: &str = "OpenAI";
29
30#[derive(Default, Clone, Debug, PartialEq)]
31pub struct OpenAiSettings {
32 pub api_url: String,
33 pub available_models: Vec<AvailableModel>,
34 pub needs_setting_migration: bool,
35}
36
37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
38pub struct AvailableModel {
39 pub name: String,
40 pub display_name: Option<String>,
41 pub max_tokens: usize,
42 pub max_output_tokens: Option<u32>,
43 pub max_completion_tokens: Option<u32>,
44}
45
46pub struct OpenAiLanguageModelProvider {
47 http_client: Arc<dyn HttpClient>,
48 state: gpui::Entity<State>,
49}
50
51pub struct State {
52 api_key: Option<String>,
53 api_key_from_env: bool,
54 _subscription: Subscription,
55}
56
57const OPENAI_API_KEY_VAR: &str = "OPENAI_API_KEY";
58
59impl State {
60 fn is_authenticated(&self) -> bool {
61 self.api_key.is_some()
62 }
63
64 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
65 let credentials_provider = <dyn CredentialsProvider>::global(cx);
66 let api_url = AllLanguageModelSettings::get_global(cx)
67 .openai
68 .api_url
69 .clone();
70 cx.spawn(async move |this, cx| {
71 credentials_provider
72 .delete_credentials(&api_url, &cx)
73 .await
74 .log_err();
75 this.update(cx, |this, cx| {
76 this.api_key = None;
77 this.api_key_from_env = false;
78 cx.notify();
79 })
80 })
81 }
82
83 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
84 let credentials_provider = <dyn CredentialsProvider>::global(cx);
85 let api_url = AllLanguageModelSettings::get_global(cx)
86 .openai
87 .api_url
88 .clone();
89 cx.spawn(async move |this, cx| {
90 credentials_provider
91 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
92 .await
93 .log_err();
94 this.update(cx, |this, cx| {
95 this.api_key = Some(api_key);
96 cx.notify();
97 })
98 })
99 }
100
101 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
102 if self.is_authenticated() {
103 return Task::ready(Ok(()));
104 }
105
106 let credentials_provider = <dyn CredentialsProvider>::global(cx);
107 let api_url = AllLanguageModelSettings::get_global(cx)
108 .openai
109 .api_url
110 .clone();
111 cx.spawn(async move |this, cx| {
112 let (api_key, from_env) = if let Ok(api_key) = std::env::var(OPENAI_API_KEY_VAR) {
113 (api_key, true)
114 } else {
115 let (_, api_key) = credentials_provider
116 .read_credentials(&api_url, &cx)
117 .await?
118 .ok_or(AuthenticateError::CredentialsNotFound)?;
119 (
120 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
121 false,
122 )
123 };
124 this.update(cx, |this, cx| {
125 this.api_key = Some(api_key);
126 this.api_key_from_env = from_env;
127 cx.notify();
128 })?;
129
130 Ok(())
131 })
132 }
133}
134
135impl OpenAiLanguageModelProvider {
136 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
137 let state = cx.new(|cx| State {
138 api_key: None,
139 api_key_from_env: false,
140 _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
141 cx.notify();
142 }),
143 });
144
145 Self { http_client, state }
146 }
147}
148
149impl LanguageModelProviderState for OpenAiLanguageModelProvider {
150 type ObservableEntity = State;
151
152 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
153 Some(self.state.clone())
154 }
155}
156
157impl LanguageModelProvider for OpenAiLanguageModelProvider {
158 fn id(&self) -> LanguageModelProviderId {
159 LanguageModelProviderId(PROVIDER_ID.into())
160 }
161
162 fn name(&self) -> LanguageModelProviderName {
163 LanguageModelProviderName(PROVIDER_NAME.into())
164 }
165
166 fn icon(&self) -> IconName {
167 IconName::AiOpenAi
168 }
169
170 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
171 let model = open_ai::Model::default();
172 Some(Arc::new(OpenAiLanguageModel {
173 id: LanguageModelId::from(model.id().to_string()),
174 model,
175 state: self.state.clone(),
176 http_client: self.http_client.clone(),
177 request_limiter: RateLimiter::new(4),
178 }))
179 }
180
181 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
182 let mut models = BTreeMap::default();
183
184 // Add base models from open_ai::Model::iter()
185 for model in open_ai::Model::iter() {
186 if !matches!(model, open_ai::Model::Custom { .. }) {
187 models.insert(model.id().to_string(), model);
188 }
189 }
190
191 // Override with available models from settings
192 for model in &AllLanguageModelSettings::get_global(cx)
193 .openai
194 .available_models
195 {
196 models.insert(
197 model.name.clone(),
198 open_ai::Model::Custom {
199 name: model.name.clone(),
200 display_name: model.display_name.clone(),
201 max_tokens: model.max_tokens,
202 max_output_tokens: model.max_output_tokens,
203 max_completion_tokens: model.max_completion_tokens,
204 },
205 );
206 }
207
208 models
209 .into_values()
210 .map(|model| {
211 Arc::new(OpenAiLanguageModel {
212 id: LanguageModelId::from(model.id().to_string()),
213 model,
214 state: self.state.clone(),
215 http_client: self.http_client.clone(),
216 request_limiter: RateLimiter::new(4),
217 }) as Arc<dyn LanguageModel>
218 })
219 .collect()
220 }
221
222 fn is_authenticated(&self, cx: &App) -> bool {
223 self.state.read(cx).is_authenticated()
224 }
225
226 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
227 self.state.update(cx, |state, cx| state.authenticate(cx))
228 }
229
230 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
231 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
232 .into()
233 }
234
235 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
236 self.state.update(cx, |state, cx| state.reset_api_key(cx))
237 }
238}
239
240pub struct OpenAiLanguageModel {
241 id: LanguageModelId,
242 model: open_ai::Model,
243 state: gpui::Entity<State>,
244 http_client: Arc<dyn HttpClient>,
245 request_limiter: RateLimiter,
246}
247
248impl OpenAiLanguageModel {
249 fn stream_completion(
250 &self,
251 request: open_ai::Request,
252 cx: &AsyncApp,
253 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
254 {
255 let http_client = self.http_client.clone();
256 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
257 let settings = &AllLanguageModelSettings::get_global(cx).openai;
258 (state.api_key.clone(), settings.api_url.clone())
259 }) else {
260 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
261 };
262
263 let future = self.request_limiter.stream(async move {
264 let api_key = api_key.ok_or_else(|| anyhow!("Missing OpenAI API Key"))?;
265 let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
266 let response = request.await?;
267 Ok(response)
268 });
269
270 async move { Ok(future.await?.boxed()) }.boxed()
271 }
272}
273
274impl LanguageModel for OpenAiLanguageModel {
275 fn id(&self) -> LanguageModelId {
276 self.id.clone()
277 }
278
279 fn name(&self) -> LanguageModelName {
280 LanguageModelName::from(self.model.display_name().to_string())
281 }
282
283 fn provider_id(&self) -> LanguageModelProviderId {
284 LanguageModelProviderId(PROVIDER_ID.into())
285 }
286
287 fn provider_name(&self) -> LanguageModelProviderName {
288 LanguageModelProviderName(PROVIDER_NAME.into())
289 }
290
291 fn supports_tools(&self) -> bool {
292 false
293 }
294
295 fn telemetry_id(&self) -> String {
296 format!("openai/{}", self.model.id())
297 }
298
299 fn max_token_count(&self) -> usize {
300 self.model.max_token_count()
301 }
302
303 fn max_output_tokens(&self) -> Option<u32> {
304 self.model.max_output_tokens()
305 }
306
307 fn count_tokens(
308 &self,
309 request: LanguageModelRequest,
310 cx: &App,
311 ) -> BoxFuture<'static, Result<usize>> {
312 count_open_ai_tokens(request, self.model.clone(), cx)
313 }
314
315 fn stream_completion(
316 &self,
317 request: LanguageModelRequest,
318 cx: &AsyncApp,
319 ) -> BoxFuture<
320 'static,
321 Result<futures::stream::BoxStream<'static, Result<LanguageModelCompletionEvent>>>,
322 > {
323 let request = into_open_ai(request, self.model.id().into(), self.max_output_tokens());
324 let completions = self.stream_completion(request, cx);
325 async move {
326 Ok(open_ai::extract_text_from_events(completions.await?)
327 .map(|result| result.map(LanguageModelCompletionEvent::Text))
328 .boxed())
329 }
330 .boxed()
331 }
332}
333
334pub fn into_open_ai(
335 request: LanguageModelRequest,
336 model: String,
337 max_output_tokens: Option<u32>,
338) -> open_ai::Request {
339 let stream = !model.starts_with("o1-");
340 open_ai::Request {
341 model,
342 messages: request
343 .messages
344 .into_iter()
345 .map(|msg| match msg.role {
346 Role::User => open_ai::RequestMessage::User {
347 content: msg.string_contents(),
348 },
349 Role::Assistant => open_ai::RequestMessage::Assistant {
350 content: Some(msg.string_contents()),
351 tool_calls: Vec::new(),
352 },
353 Role::System => open_ai::RequestMessage::System {
354 content: msg.string_contents(),
355 },
356 })
357 .collect(),
358 stream,
359 stop: request.stop,
360 temperature: request.temperature.unwrap_or(1.0),
361 max_tokens: max_output_tokens,
362 tools: Vec::new(),
363 tool_choice: None,
364 }
365}
366
367pub fn count_open_ai_tokens(
368 request: LanguageModelRequest,
369 model: open_ai::Model,
370 cx: &App,
371) -> BoxFuture<'static, Result<usize>> {
372 cx.background_spawn(async move {
373 let messages = request
374 .messages
375 .into_iter()
376 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
377 role: match message.role {
378 Role::User => "user".into(),
379 Role::Assistant => "assistant".into(),
380 Role::System => "system".into(),
381 },
382 content: Some(message.string_contents()),
383 name: None,
384 function_call: None,
385 })
386 .collect::<Vec<_>>();
387
388 match model {
389 open_ai::Model::Custom { .. }
390 | open_ai::Model::O1Mini
391 | open_ai::Model::O1
392 | open_ai::Model::O3Mini => tiktoken_rs::num_tokens_from_messages("gpt-4", &messages),
393 _ => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
394 }
395 })
396 .boxed()
397}
398
399struct ConfigurationView {
400 api_key_editor: Entity<Editor>,
401 state: gpui::Entity<State>,
402 load_credentials_task: Option<Task<()>>,
403}
404
405impl ConfigurationView {
406 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
407 let api_key_editor = cx.new(|cx| {
408 let mut editor = Editor::single_line(window, cx);
409 editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
410 editor
411 });
412
413 cx.observe(&state, |_, _, cx| {
414 cx.notify();
415 })
416 .detach();
417
418 let load_credentials_task = Some(cx.spawn_in(window, {
419 let state = state.clone();
420 async move |this, cx| {
421 if let Some(task) = state
422 .update(cx, |state, cx| state.authenticate(cx))
423 .log_err()
424 {
425 // We don't log an error, because "not signed in" is also an error.
426 let _ = task.await;
427 }
428
429 this.update(cx, |this, cx| {
430 this.load_credentials_task = None;
431 cx.notify();
432 })
433 .log_err();
434 }
435 }));
436
437 Self {
438 api_key_editor,
439 state,
440 load_credentials_task,
441 }
442 }
443
444 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
445 let api_key = self.api_key_editor.read(cx).text(cx);
446 if api_key.is_empty() {
447 return;
448 }
449
450 let state = self.state.clone();
451 cx.spawn_in(window, async move |_, cx| {
452 state
453 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
454 .await
455 })
456 .detach_and_log_err(cx);
457
458 cx.notify();
459 }
460
461 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
462 self.api_key_editor
463 .update(cx, |editor, cx| editor.set_text("", window, cx));
464
465 let state = self.state.clone();
466 cx.spawn_in(window, async move |_, cx| {
467 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
468 })
469 .detach_and_log_err(cx);
470
471 cx.notify();
472 }
473
474 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
475 let settings = ThemeSettings::get_global(cx);
476 let text_style = TextStyle {
477 color: cx.theme().colors().text,
478 font_family: settings.ui_font.family.clone(),
479 font_features: settings.ui_font.features.clone(),
480 font_fallbacks: settings.ui_font.fallbacks.clone(),
481 font_size: rems(0.875).into(),
482 font_weight: settings.ui_font.weight,
483 font_style: FontStyle::Normal,
484 line_height: relative(1.3),
485 white_space: WhiteSpace::Normal,
486 ..Default::default()
487 };
488 EditorElement::new(
489 &self.api_key_editor,
490 EditorStyle {
491 background: cx.theme().colors().editor_background,
492 local_player: cx.theme().players().local(),
493 text: text_style,
494 ..Default::default()
495 },
496 )
497 }
498
499 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
500 !self.state.read(cx).is_authenticated()
501 }
502}
503
504impl Render for ConfigurationView {
505 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
506 let env_var_set = self.state.read(cx).api_key_from_env;
507
508 if self.load_credentials_task.is_some() {
509 div().child(Label::new("Loading credentials...")).into_any()
510 } else if self.should_render_editor(cx) {
511 v_flex()
512 .size_full()
513 .on_action(cx.listener(Self::save_api_key))
514 .child(Label::new("To use Zed's assistant with OpenAI, you need to add an API key. Follow these steps:"))
515 .child(
516 List::new()
517 .child(InstructionListItem::new(
518 "Create one by visiting",
519 Some("OpenAI's console"),
520 Some("https://platform.openai.com/api-keys"),
521 ))
522 .child(InstructionListItem::text_only(
523 "Ensure your OpenAI account has credits",
524 ))
525 .child(InstructionListItem::text_only(
526 "Paste your API key below and hit enter to start using the assistant",
527 )),
528 )
529 .child(
530 h_flex()
531 .w_full()
532 .my_2()
533 .px_2()
534 .py_1()
535 .bg(cx.theme().colors().editor_background)
536 .border_1()
537 .border_color(cx.theme().colors().border_variant)
538 .rounded_sm()
539 .child(self.render_api_key_editor(cx)),
540 )
541 .child(
542 Label::new(
543 format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
544 )
545 .size(LabelSize::Small).color(Color::Muted),
546 )
547 .child(
548 Label::new(
549 "Note that having a subscription for another service like GitHub Copilot won't work.".to_string(),
550 )
551 .size(LabelSize::Small).color(Color::Muted),
552 )
553 .into_any()
554 } else {
555 h_flex()
556 .size_full()
557 .justify_between()
558 .child(
559 h_flex()
560 .gap_1()
561 .child(Icon::new(IconName::Check).color(Color::Success))
562 .child(Label::new(if env_var_set {
563 format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
564 } else {
565 "API key configured.".to_string()
566 })),
567 )
568 .child(
569 Button::new("reset-key", "Reset key")
570 .icon(Some(IconName::Trash))
571 .icon_size(IconSize::Small)
572 .icon_position(IconPosition::Start)
573 .disabled(env_var_set)
574 .when(env_var_set, |this| {
575 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
576 })
577 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
578 )
579 .into_any()
580 }
581 }
582}