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