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