open_ai.rs

  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::{
 16    FunctionDefinition, ResponseStreamEvent, ToolChoice, ToolDefinition, stream_completion,
 17};
 18use schemars::JsonSchema;
 19use serde::{Deserialize, Serialize};
 20use settings::{Settings, SettingsStore};
 21use std::sync::Arc;
 22use strum::IntoEnumIterator;
 23use theme::ThemeSettings;
 24use ui::{Icon, IconName, List, Tooltip, prelude::*};
 25use util::ResultExt;
 26
 27use crate::{AllLanguageModelSettings, ui::InstructionListItem};
 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(async move |this, cx| {
 73            credentials_provider
 74                .delete_credentials(&api_url, &cx)
 75                .await
 76                .log_err();
 77            this.update(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(async move |this, cx| {
 92            credentials_provider
 93                .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
 94                .await
 95                .log_err();
 96            this.update(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(async move |this, cx| {
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(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 default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
173        let model = open_ai::Model::default();
174        Some(Arc::new(OpenAiLanguageModel {
175            id: LanguageModelId::from(model.id().to_string()),
176            model,
177            state: self.state.clone(),
178            http_client: self.http_client.clone(),
179            request_limiter: RateLimiter::new(4),
180        }))
181    }
182
183    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
184        let mut models = BTreeMap::default();
185
186        // Add base models from open_ai::Model::iter()
187        for model in open_ai::Model::iter() {
188            if !matches!(model, open_ai::Model::Custom { .. }) {
189                models.insert(model.id().to_string(), model);
190            }
191        }
192
193        // Override with available models from settings
194        for model in &AllLanguageModelSettings::get_global(cx)
195            .openai
196            .available_models
197        {
198            models.insert(
199                model.name.clone(),
200                open_ai::Model::Custom {
201                    name: model.name.clone(),
202                    display_name: model.display_name.clone(),
203                    max_tokens: model.max_tokens,
204                    max_output_tokens: model.max_output_tokens,
205                    max_completion_tokens: model.max_completion_tokens,
206                },
207            );
208        }
209
210        models
211            .into_values()
212            .map(|model| {
213                Arc::new(OpenAiLanguageModel {
214                    id: LanguageModelId::from(model.id().to_string()),
215                    model,
216                    state: self.state.clone(),
217                    http_client: self.http_client.clone(),
218                    request_limiter: RateLimiter::new(4),
219                }) as Arc<dyn LanguageModel>
220            })
221            .collect()
222    }
223
224    fn is_authenticated(&self, cx: &App) -> bool {
225        self.state.read(cx).is_authenticated()
226    }
227
228    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
229        self.state.update(cx, |state, cx| state.authenticate(cx))
230    }
231
232    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
233        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
234            .into()
235    }
236
237    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
238        self.state.update(cx, |state, cx| state.reset_api_key(cx))
239    }
240}
241
242pub struct OpenAiLanguageModel {
243    id: LanguageModelId,
244    model: open_ai::Model,
245    state: gpui::Entity<State>,
246    http_client: Arc<dyn HttpClient>,
247    request_limiter: RateLimiter,
248}
249
250impl OpenAiLanguageModel {
251    fn stream_completion(
252        &self,
253        request: open_ai::Request,
254        cx: &AsyncApp,
255    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
256    {
257        let http_client = self.http_client.clone();
258        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
259            let settings = &AllLanguageModelSettings::get_global(cx).openai;
260            (state.api_key.clone(), settings.api_url.clone())
261        }) else {
262            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
263        };
264
265        let future = self.request_limiter.stream(async move {
266            let api_key = api_key.ok_or_else(|| anyhow!("Missing OpenAI API Key"))?;
267            let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
268            let response = request.await?;
269            Ok(response)
270        });
271
272        async move { Ok(future.await?.boxed()) }.boxed()
273    }
274}
275
276impl LanguageModel for OpenAiLanguageModel {
277    fn id(&self) -> LanguageModelId {
278        self.id.clone()
279    }
280
281    fn name(&self) -> LanguageModelName {
282        LanguageModelName::from(self.model.display_name().to_string())
283    }
284
285    fn provider_id(&self) -> LanguageModelProviderId {
286        LanguageModelProviderId(PROVIDER_ID.into())
287    }
288
289    fn provider_name(&self) -> LanguageModelProviderName {
290        LanguageModelProviderName(PROVIDER_NAME.into())
291    }
292
293    fn supports_tools(&self) -> bool {
294        false
295    }
296
297    fn telemetry_id(&self) -> String {
298        format!("openai/{}", self.model.id())
299    }
300
301    fn max_token_count(&self) -> usize {
302        self.model.max_token_count()
303    }
304
305    fn max_output_tokens(&self) -> Option<u32> {
306        self.model.max_output_tokens()
307    }
308
309    fn count_tokens(
310        &self,
311        request: LanguageModelRequest,
312        cx: &App,
313    ) -> BoxFuture<'static, Result<usize>> {
314        count_open_ai_tokens(request, self.model.clone(), cx)
315    }
316
317    fn stream_completion(
318        &self,
319        request: LanguageModelRequest,
320        cx: &AsyncApp,
321    ) -> BoxFuture<
322        'static,
323        Result<futures::stream::BoxStream<'static, Result<LanguageModelCompletionEvent>>>,
324    > {
325        let request = into_open_ai(request, self.model.id().into(), self.max_output_tokens());
326        let completions = self.stream_completion(request, cx);
327        async move {
328            Ok(open_ai::extract_text_from_events(completions.await?)
329                .map(|result| result.map(LanguageModelCompletionEvent::Text))
330                .boxed())
331        }
332        .boxed()
333    }
334
335    fn use_any_tool(
336        &self,
337        request: LanguageModelRequest,
338        tool_name: String,
339        tool_description: String,
340        schema: serde_json::Value,
341        cx: &AsyncApp,
342    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
343        let mut request = into_open_ai(request, self.model.id().into(), self.max_output_tokens());
344        request.tool_choice = Some(ToolChoice::Other(ToolDefinition::Function {
345            function: FunctionDefinition {
346                name: tool_name.clone(),
347                description: None,
348                parameters: None,
349            },
350        }));
351        request.tools = vec![ToolDefinition::Function {
352            function: FunctionDefinition {
353                name: tool_name.clone(),
354                description: Some(tool_description),
355                parameters: Some(schema),
356            },
357        }];
358
359        let response = self.stream_completion(request, cx);
360        self.request_limiter
361            .run(async move {
362                let response = response.await?;
363                Ok(
364                    open_ai::extract_tool_args_from_events(tool_name, Box::pin(response))
365                        .await?
366                        .boxed(),
367                )
368            })
369            .boxed()
370    }
371}
372
373pub fn into_open_ai(
374    request: LanguageModelRequest,
375    model: String,
376    max_output_tokens: Option<u32>,
377) -> open_ai::Request {
378    let stream = !model.starts_with("o1-");
379    open_ai::Request {
380        model,
381        messages: request
382            .messages
383            .into_iter()
384            .map(|msg| match msg.role {
385                Role::User => open_ai::RequestMessage::User {
386                    content: msg.string_contents(),
387                },
388                Role::Assistant => open_ai::RequestMessage::Assistant {
389                    content: Some(msg.string_contents()),
390                    tool_calls: Vec::new(),
391                },
392                Role::System => open_ai::RequestMessage::System {
393                    content: msg.string_contents(),
394                },
395            })
396            .collect(),
397        stream,
398        stop: request.stop,
399        temperature: request.temperature.unwrap_or(1.0),
400        max_tokens: max_output_tokens,
401        tools: Vec::new(),
402        tool_choice: None,
403    }
404}
405
406pub fn count_open_ai_tokens(
407    request: LanguageModelRequest,
408    model: open_ai::Model,
409    cx: &App,
410) -> BoxFuture<'static, Result<usize>> {
411    cx.background_spawn(async move {
412        let messages = request
413            .messages
414            .into_iter()
415            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
416                role: match message.role {
417                    Role::User => "user".into(),
418                    Role::Assistant => "assistant".into(),
419                    Role::System => "system".into(),
420                },
421                content: Some(message.string_contents()),
422                name: None,
423                function_call: None,
424            })
425            .collect::<Vec<_>>();
426
427        match model {
428            open_ai::Model::Custom { .. }
429            | open_ai::Model::O1Mini
430            | open_ai::Model::O1
431            | open_ai::Model::O3Mini => tiktoken_rs::num_tokens_from_messages("gpt-4", &messages),
432            _ => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
433        }
434    })
435    .boxed()
436}
437
438struct ConfigurationView {
439    api_key_editor: Entity<Editor>,
440    state: gpui::Entity<State>,
441    load_credentials_task: Option<Task<()>>,
442}
443
444impl ConfigurationView {
445    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
446        let api_key_editor = cx.new(|cx| {
447            let mut editor = Editor::single_line(window, cx);
448            editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
449            editor
450        });
451
452        cx.observe(&state, |_, _, cx| {
453            cx.notify();
454        })
455        .detach();
456
457        let load_credentials_task = Some(cx.spawn_in(window, {
458            let state = state.clone();
459            async move |this, cx| {
460                if let Some(task) = state
461                    .update(cx, |state, cx| state.authenticate(cx))
462                    .log_err()
463                {
464                    // We don't log an error, because "not signed in" is also an error.
465                    let _ = task.await;
466                }
467
468                this.update(cx, |this, cx| {
469                    this.load_credentials_task = None;
470                    cx.notify();
471                })
472                .log_err();
473            }
474        }));
475
476        Self {
477            api_key_editor,
478            state,
479            load_credentials_task,
480        }
481    }
482
483    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
484        let api_key = self.api_key_editor.read(cx).text(cx);
485        if api_key.is_empty() {
486            return;
487        }
488
489        let state = self.state.clone();
490        cx.spawn_in(window, async move |_, cx| {
491            state
492                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
493                .await
494        })
495        .detach_and_log_err(cx);
496
497        cx.notify();
498    }
499
500    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
501        self.api_key_editor
502            .update(cx, |editor, cx| editor.set_text("", window, cx));
503
504        let state = self.state.clone();
505        cx.spawn_in(window, async move |_, cx| {
506            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
507        })
508        .detach_and_log_err(cx);
509
510        cx.notify();
511    }
512
513    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
514        let settings = ThemeSettings::get_global(cx);
515        let text_style = TextStyle {
516            color: cx.theme().colors().text,
517            font_family: settings.ui_font.family.clone(),
518            font_features: settings.ui_font.features.clone(),
519            font_fallbacks: settings.ui_font.fallbacks.clone(),
520            font_size: rems(0.875).into(),
521            font_weight: settings.ui_font.weight,
522            font_style: FontStyle::Normal,
523            line_height: relative(1.3),
524            white_space: WhiteSpace::Normal,
525            ..Default::default()
526        };
527        EditorElement::new(
528            &self.api_key_editor,
529            EditorStyle {
530                background: cx.theme().colors().editor_background,
531                local_player: cx.theme().players().local(),
532                text: text_style,
533                ..Default::default()
534            },
535        )
536    }
537
538    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
539        !self.state.read(cx).is_authenticated()
540    }
541}
542
543impl Render for ConfigurationView {
544    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
545        let env_var_set = self.state.read(cx).api_key_from_env;
546
547        if self.load_credentials_task.is_some() {
548            div().child(Label::new("Loading credentials...")).into_any()
549        } else if self.should_render_editor(cx) {
550            v_flex()
551                .size_full()
552                .on_action(cx.listener(Self::save_api_key))
553                .child(Label::new("To use Zed's assistant with OpenAI, you need to add an API key. Follow these steps:"))
554                .child(
555                    List::new()
556                        .child(InstructionListItem::new(
557                            "Create one by visiting",
558                            Some("OpenAI's console"),
559                            Some("https://platform.openai.com/api-keys"),
560                        ))
561                        .child(InstructionListItem::text_only(
562                            "Ensure your OpenAI account has credits",
563                        ))
564                        .child(InstructionListItem::text_only(
565                            "Paste your API key below and hit enter to start using the assistant",
566                        )),
567                )
568                .child(
569                    h_flex()
570                        .w_full()
571                        .my_2()
572                        .px_2()
573                        .py_1()
574                        .bg(cx.theme().colors().editor_background)
575                        .border_1()
576                        .border_color(cx.theme().colors().border_variant)
577                        .rounded_sm()
578                        .child(self.render_api_key_editor(cx)),
579                )
580                .child(
581                    Label::new(
582                        format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
583                    )
584                    .size(LabelSize::Small).color(Color::Muted),
585                )
586                .child(
587                    Label::new(
588                        "Note that having a subscription for another service like GitHub Copilot won't work.".to_string(),
589                    )
590                    .size(LabelSize::Small).color(Color::Muted),
591                )
592                .into_any()
593        } else {
594            h_flex()
595                .size_full()
596                .justify_between()
597                .child(
598                    h_flex()
599                        .gap_1()
600                        .child(Icon::new(IconName::Check).color(Color::Success))
601                        .child(Label::new(if env_var_set {
602                            format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
603                        } else {
604                            "API key configured.".to_string()
605                        })),
606                )
607                .child(
608                    Button::new("reset-key", "Reset key")
609                        .icon(Some(IconName::Trash))
610                        .icon_size(IconSize::Small)
611                        .icon_position(IconPosition::Start)
612                        .disabled(env_var_set)
613                        .when(env_var_set, |this| {
614                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
615                        })
616                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
617                )
618                .into_any()
619        }
620    }
621}