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