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 open_ai::stream_completion;
 11use schemars::JsonSchema;
 12use serde::{Deserialize, Serialize};
 13use settings::{Settings, SettingsStore};
 14use std::{future, sync::Arc, time::Duration};
 15use strum::IntoEnumIterator;
 16use theme::ThemeSettings;
 17use ui::{prelude::*, Indicator};
 18use util::ResultExt;
 19
 20use crate::{
 21    settings::AllLanguageModelSettings, LanguageModel, LanguageModelId, LanguageModelName,
 22    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 23    LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
 24};
 25
 26const PROVIDER_ID: &str = "openai";
 27const PROVIDER_NAME: &str = "OpenAI";
 28
 29#[derive(Default, Clone, Debug, PartialEq)]
 30pub struct OpenAiSettings {
 31    pub api_url: String,
 32    pub low_speed_timeout: Option<Duration>,
 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 max_tokens: usize,
 41}
 42
 43pub struct OpenAiLanguageModelProvider {
 44    http_client: Arc<dyn HttpClient>,
 45    state: gpui::Model<State>,
 46}
 47
 48pub struct State {
 49    api_key: Option<String>,
 50    _subscription: Subscription,
 51}
 52
 53impl State {
 54    fn is_authenticated(&self) -> bool {
 55        self.api_key.is_some()
 56    }
 57
 58    fn reset_api_key(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 59        let settings = &AllLanguageModelSettings::get_global(cx).openai;
 60        let delete_credentials = cx.delete_credentials(&settings.api_url);
 61        cx.spawn(|this, mut cx| async move {
 62            delete_credentials.await.log_err();
 63            this.update(&mut cx, |this, cx| {
 64                this.api_key = None;
 65                cx.notify();
 66            })
 67        })
 68    }
 69
 70    fn set_api_key(&mut self, api_key: String, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 71        let settings = &AllLanguageModelSettings::get_global(cx).openai;
 72        let write_credentials =
 73            cx.write_credentials(&settings.api_url, "Bearer", api_key.as_bytes());
 74
 75        cx.spawn(|this, mut cx| async move {
 76            write_credentials.await?;
 77            this.update(&mut cx, |this, cx| {
 78                this.api_key = Some(api_key);
 79                cx.notify();
 80            })
 81        })
 82    }
 83
 84    fn authenticate(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 85        if self.is_authenticated() {
 86            Task::ready(Ok(()))
 87        } else {
 88            let api_url = AllLanguageModelSettings::get_global(cx)
 89                .openai
 90                .api_url
 91                .clone();
 92            cx.spawn(|this, mut cx| async move {
 93                let api_key = if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
 94                    api_key
 95                } else {
 96                    let (_, api_key) = cx
 97                        .update(|cx| cx.read_credentials(&api_url))?
 98                        .await?
 99                        .ok_or_else(|| anyhow!("credentials not found"))?;
100                    String::from_utf8(api_key)?
101                };
102                this.update(&mut cx, |this, cx| {
103                    this.api_key = Some(api_key);
104                    cx.notify();
105                })
106            })
107        }
108    }
109}
110
111impl OpenAiLanguageModelProvider {
112    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Self {
113        let state = cx.new_model(|cx| State {
114            api_key: None,
115            _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
116                cx.notify();
117            }),
118        });
119
120        Self { http_client, state }
121    }
122}
123
124impl LanguageModelProviderState for OpenAiLanguageModelProvider {
125    type ObservableEntity = State;
126
127    fn observable_entity(&self) -> Option<gpui::Model<Self::ObservableEntity>> {
128        Some(self.state.clone())
129    }
130}
131
132impl LanguageModelProvider for OpenAiLanguageModelProvider {
133    fn id(&self) -> LanguageModelProviderId {
134        LanguageModelProviderId(PROVIDER_ID.into())
135    }
136
137    fn name(&self) -> LanguageModelProviderName {
138        LanguageModelProviderName(PROVIDER_NAME.into())
139    }
140
141    fn icon(&self) -> IconName {
142        IconName::AiOpenAi
143    }
144
145    fn provided_models(&self, cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
146        let mut models = BTreeMap::default();
147
148        // Add base models from open_ai::Model::iter()
149        for model in open_ai::Model::iter() {
150            if !matches!(model, open_ai::Model::Custom { .. }) {
151                models.insert(model.id().to_string(), model);
152            }
153        }
154
155        // Override with available models from settings
156        for model in &AllLanguageModelSettings::get_global(cx)
157            .openai
158            .available_models
159        {
160            models.insert(
161                model.name.clone(),
162                open_ai::Model::Custom {
163                    name: model.name.clone(),
164                    max_tokens: model.max_tokens,
165                },
166            );
167        }
168
169        models
170            .into_values()
171            .map(|model| {
172                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                }) as Arc<dyn LanguageModel>
179            })
180            .collect()
181    }
182
183    fn is_authenticated(&self, cx: &AppContext) -> bool {
184        self.state.read(cx).is_authenticated()
185    }
186
187    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
188        self.state.update(cx, |state, cx| state.authenticate(cx))
189    }
190
191    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
192        cx.new_view(|cx| ConfigurationView::new(self.state.clone(), cx))
193            .into()
194    }
195
196    fn reset_credentials(&self, cx: &mut AppContext) -> Task<Result<()>> {
197        self.state.update(cx, |state, cx| state.reset_api_key(cx))
198    }
199}
200
201pub struct OpenAiLanguageModel {
202    id: LanguageModelId,
203    model: open_ai::Model,
204    state: gpui::Model<State>,
205    http_client: Arc<dyn HttpClient>,
206    request_limiter: RateLimiter,
207}
208
209impl LanguageModel for OpenAiLanguageModel {
210    fn id(&self) -> LanguageModelId {
211        self.id.clone()
212    }
213
214    fn name(&self) -> LanguageModelName {
215        LanguageModelName::from(self.model.display_name().to_string())
216    }
217
218    fn provider_id(&self) -> LanguageModelProviderId {
219        LanguageModelProviderId(PROVIDER_ID.into())
220    }
221
222    fn provider_name(&self) -> LanguageModelProviderName {
223        LanguageModelProviderName(PROVIDER_NAME.into())
224    }
225
226    fn telemetry_id(&self) -> String {
227        format!("openai/{}", self.model.id())
228    }
229
230    fn max_token_count(&self) -> usize {
231        self.model.max_token_count()
232    }
233
234    fn count_tokens(
235        &self,
236        request: LanguageModelRequest,
237        cx: &AppContext,
238    ) -> BoxFuture<'static, Result<usize>> {
239        count_open_ai_tokens(request, self.model.clone(), cx)
240    }
241
242    fn stream_completion(
243        &self,
244        request: LanguageModelRequest,
245        cx: &AsyncAppContext,
246    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
247        let request = request.into_open_ai(self.model.id().into());
248
249        let http_client = self.http_client.clone();
250        let Ok((api_key, api_url, low_speed_timeout)) = cx.read_model(&self.state, |state, cx| {
251            let settings = &AllLanguageModelSettings::get_global(cx).openai;
252            (
253                state.api_key.clone(),
254                settings.api_url.clone(),
255                settings.low_speed_timeout,
256            )
257        }) else {
258            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
259        };
260
261        let future = self.request_limiter.stream(async move {
262            let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
263            let request = stream_completion(
264                http_client.as_ref(),
265                &api_url,
266                &api_key,
267                request,
268                low_speed_timeout,
269            );
270            let response = request.await?;
271            Ok(open_ai::extract_text_from_events(response).boxed())
272        });
273
274        async move { Ok(future.await?.boxed()) }.boxed()
275    }
276
277    fn use_any_tool(
278        &self,
279        _request: LanguageModelRequest,
280        _name: String,
281        _description: String,
282        _schema: serde_json::Value,
283        _cx: &AsyncAppContext,
284    ) -> BoxFuture<'static, Result<serde_json::Value>> {
285        future::ready(Err(anyhow!("not implemented"))).boxed()
286    }
287}
288
289pub fn count_open_ai_tokens(
290    request: LanguageModelRequest,
291    model: open_ai::Model,
292    cx: &AppContext,
293) -> BoxFuture<'static, Result<usize>> {
294    cx.background_executor()
295        .spawn(async move {
296            let messages = request
297                .messages
298                .into_iter()
299                .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
300                    role: match message.role {
301                        Role::User => "user".into(),
302                        Role::Assistant => "assistant".into(),
303                        Role::System => "system".into(),
304                    },
305                    content: Some(message.content),
306                    name: None,
307                    function_call: None,
308                })
309                .collect::<Vec<_>>();
310
311            if let open_ai::Model::Custom { .. } = model {
312                tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
313            } else {
314                tiktoken_rs::num_tokens_from_messages(model.id(), &messages)
315            }
316        })
317        .boxed()
318}
319
320struct ConfigurationView {
321    api_key_editor: View<Editor>,
322    state: gpui::Model<State>,
323    load_credentials_task: Option<Task<()>>,
324}
325
326impl ConfigurationView {
327    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
328        let api_key_editor = cx.new_view(|cx| {
329            let mut editor = Editor::single_line(cx);
330            editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
331            editor
332        });
333
334        cx.observe(&state, |_, _, cx| {
335            cx.notify();
336        })
337        .detach();
338
339        let load_credentials_task = Some(cx.spawn({
340            let state = state.clone();
341            |this, mut cx| async move {
342                if let Some(task) = state
343                    .update(&mut cx, |state, cx| state.authenticate(cx))
344                    .log_err()
345                {
346                    // We don't log an error, because "not signed in" is also an error.
347                    let _ = task.await;
348                }
349
350                this.update(&mut cx, |this, cx| {
351                    this.load_credentials_task = None;
352                    cx.notify();
353                })
354                .log_err();
355            }
356        }));
357
358        Self {
359            api_key_editor,
360            state,
361            load_credentials_task,
362        }
363    }
364
365    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
366        let api_key = self.api_key_editor.read(cx).text(cx);
367        if api_key.is_empty() {
368            return;
369        }
370
371        let state = self.state.clone();
372        cx.spawn(|_, mut cx| async move {
373            state
374                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
375                .await
376        })
377        .detach_and_log_err(cx);
378
379        cx.notify();
380    }
381
382    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
383        self.api_key_editor
384            .update(cx, |editor, cx| editor.set_text("", cx));
385
386        let state = self.state.clone();
387        cx.spawn(|_, mut cx| async move {
388            state
389                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
390                .await
391        })
392        .detach_and_log_err(cx);
393
394        cx.notify();
395    }
396
397    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
398        let settings = ThemeSettings::get_global(cx);
399        let text_style = TextStyle {
400            color: cx.theme().colors().text,
401            font_family: settings.ui_font.family.clone(),
402            font_features: settings.ui_font.features.clone(),
403            font_fallbacks: settings.ui_font.fallbacks.clone(),
404            font_size: rems(0.875).into(),
405            font_weight: settings.ui_font.weight,
406            font_style: FontStyle::Normal,
407            line_height: relative(1.3),
408            background_color: None,
409            underline: None,
410            strikethrough: None,
411            white_space: WhiteSpace::Normal,
412        };
413        EditorElement::new(
414            &self.api_key_editor,
415            EditorStyle {
416                background: cx.theme().colors().editor_background,
417                local_player: cx.theme().players().local(),
418                text: text_style,
419                ..Default::default()
420            },
421        )
422    }
423
424    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
425        !self.state.read(cx).is_authenticated()
426    }
427}
428
429impl Render for ConfigurationView {
430    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
431        const INSTRUCTIONS: [&str; 6] = [
432            "To use the assistant panel or inline assistant, you need to add your OpenAI API key.",
433            " - You can create an API key at: platform.openai.com/api-keys",
434            " - Make sure your OpenAI account has credits",
435            " - Having a subscription for another service like GitHub Copilot won't work.",
436            "",
437            "Paste your OpenAI API key below and hit enter to use the assistant:",
438        ];
439
440        if self.load_credentials_task.is_some() {
441            div().child(Label::new("Loading credentials...")).into_any()
442        } else if self.should_render_editor(cx) {
443            v_flex()
444                .size_full()
445                .on_action(cx.listener(Self::save_api_key))
446                .children(
447                    INSTRUCTIONS.map(|instruction| Label::new(instruction).size(LabelSize::Small)),
448                )
449                .child(
450                    h_flex()
451                        .w_full()
452                        .my_2()
453                        .px_2()
454                        .py_1()
455                        .bg(cx.theme().colors().editor_background)
456                        .rounded_md()
457                        .child(self.render_api_key_editor(cx)),
458                )
459                .child(
460                    Label::new(
461                        "You can also assign the OPENAI_API_KEY environment variable and restart Zed.",
462                    )
463                    .size(LabelSize::Small),
464                )
465                .into_any()
466        } else {
467            h_flex()
468                .size_full()
469                .justify_between()
470                .child(
471                    h_flex()
472                        .gap_2()
473                        .child(Indicator::dot().color(Color::Success))
474                        .child(Label::new("API key configured").size(LabelSize::Small)),
475                )
476                .child(
477                    Button::new("reset-key", "Reset key")
478                        .icon(Some(IconName::Trash))
479                        .icon_size(IconSize::Small)
480                        .icon_position(IconPosition::Start)
481                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
482                )
483                .into_any()
484        }
485    }
486}