open_ai.rs

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