1use anyhow::{Context as _, Result, anyhow};
2use collections::{BTreeMap, HashMap};
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::Stream;
6use futures::{FutureExt, StreamExt, future::BoxFuture};
7use gpui::{
8 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
9};
10use http_client::HttpClient;
11use language_model::{
12 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
13 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
14 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
15 LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
16 RateLimiter, Role, StopReason,
17};
18use open_ai::{ImageUrl, Model, ResponseStreamEvent, stream_completion};
19use schemars::JsonSchema;
20use serde::{Deserialize, Serialize};
21use settings::{Settings, SettingsStore};
22use std::pin::Pin;
23use std::str::FromStr as _;
24use std::sync::Arc;
25use strum::IntoEnumIterator;
26use theme::ThemeSettings;
27use ui::{Icon, IconName, List, Tooltip, prelude::*};
28use util::ResultExt;
29
30use crate::{AllLanguageModelSettings, ui::InstructionListItem};
31
32const PROVIDER_ID: &str = "openai";
33const PROVIDER_NAME: &str = "OpenAI";
34
35#[derive(Default, Clone, Debug, PartialEq)]
36pub struct OpenAiSettings {
37 pub api_url: String,
38 pub available_models: Vec<AvailableModel>,
39 pub needs_setting_migration: bool,
40}
41
42#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
43pub struct AvailableModel {
44 pub name: String,
45 pub display_name: Option<String>,
46 pub max_tokens: usize,
47 pub max_output_tokens: Option<u32>,
48 pub max_completion_tokens: Option<u32>,
49}
50
51pub struct OpenAiLanguageModelProvider {
52 http_client: Arc<dyn HttpClient>,
53 state: gpui::Entity<State>,
54}
55
56pub struct State {
57 api_key: Option<String>,
58 api_key_from_env: bool,
59 _subscription: Subscription,
60}
61
62const OPENAI_API_KEY_VAR: &str = "OPENAI_API_KEY";
63
64impl State {
65 fn is_authenticated(&self) -> bool {
66 self.api_key.is_some()
67 }
68
69 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
70 let credentials_provider = <dyn CredentialsProvider>::global(cx);
71 let api_url = AllLanguageModelSettings::get_global(cx)
72 .openai
73 .api_url
74 .clone();
75 cx.spawn(async move |this, cx| {
76 credentials_provider
77 .delete_credentials(&api_url, &cx)
78 .await
79 .log_err();
80 this.update(cx, |this, cx| {
81 this.api_key = None;
82 this.api_key_from_env = false;
83 cx.notify();
84 })
85 })
86 }
87
88 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
89 let credentials_provider = <dyn CredentialsProvider>::global(cx);
90 let api_url = AllLanguageModelSettings::get_global(cx)
91 .openai
92 .api_url
93 .clone();
94 cx.spawn(async move |this, cx| {
95 credentials_provider
96 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
97 .await
98 .log_err();
99 this.update(cx, |this, cx| {
100 this.api_key = Some(api_key);
101 cx.notify();
102 })
103 })
104 }
105
106 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
107 if self.is_authenticated() {
108 return Task::ready(Ok(()));
109 }
110
111 let credentials_provider = <dyn CredentialsProvider>::global(cx);
112 let api_url = AllLanguageModelSettings::get_global(cx)
113 .openai
114 .api_url
115 .clone();
116 cx.spawn(async move |this, cx| {
117 let (api_key, from_env) = if let Ok(api_key) = std::env::var(OPENAI_API_KEY_VAR) {
118 (api_key, true)
119 } else {
120 let (_, api_key) = credentials_provider
121 .read_credentials(&api_url, &cx)
122 .await?
123 .ok_or(AuthenticateError::CredentialsNotFound)?;
124 (
125 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
126 false,
127 )
128 };
129 this.update(cx, |this, cx| {
130 this.api_key = Some(api_key);
131 this.api_key_from_env = from_env;
132 cx.notify();
133 })?;
134
135 Ok(())
136 })
137 }
138}
139
140impl OpenAiLanguageModelProvider {
141 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
142 let state = cx.new(|cx| State {
143 api_key: None,
144 api_key_from_env: false,
145 _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
146 cx.notify();
147 }),
148 });
149
150 Self { http_client, state }
151 }
152
153 fn create_language_model(&self, model: open_ai::Model) -> Arc<dyn LanguageModel> {
154 Arc::new(OpenAiLanguageModel {
155 id: LanguageModelId::from(model.id().to_string()),
156 model,
157 state: self.state.clone(),
158 http_client: self.http_client.clone(),
159 request_limiter: RateLimiter::new(4),
160 })
161 }
162}
163
164impl LanguageModelProviderState for OpenAiLanguageModelProvider {
165 type ObservableEntity = State;
166
167 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
168 Some(self.state.clone())
169 }
170}
171
172impl LanguageModelProvider for OpenAiLanguageModelProvider {
173 fn id(&self) -> LanguageModelProviderId {
174 LanguageModelProviderId(PROVIDER_ID.into())
175 }
176
177 fn name(&self) -> LanguageModelProviderName {
178 LanguageModelProviderName(PROVIDER_NAME.into())
179 }
180
181 fn icon(&self) -> IconName {
182 IconName::AiOpenAi
183 }
184
185 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
186 Some(self.create_language_model(open_ai::Model::default()))
187 }
188
189 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
190 Some(self.create_language_model(open_ai::Model::default_fast()))
191 }
192
193 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
194 let mut models = BTreeMap::default();
195
196 // Add base models from open_ai::Model::iter()
197 for model in open_ai::Model::iter() {
198 if !matches!(model, open_ai::Model::Custom { .. }) {
199 models.insert(model.id().to_string(), model);
200 }
201 }
202
203 // Override with available models from settings
204 for model in &AllLanguageModelSettings::get_global(cx)
205 .openai
206 .available_models
207 {
208 models.insert(
209 model.name.clone(),
210 open_ai::Model::Custom {
211 name: model.name.clone(),
212 display_name: model.display_name.clone(),
213 max_tokens: model.max_tokens,
214 max_output_tokens: model.max_output_tokens,
215 max_completion_tokens: model.max_completion_tokens,
216 },
217 );
218 }
219
220 models
221 .into_values()
222 .map(|model| self.create_language_model(model))
223 .collect()
224 }
225
226 fn is_authenticated(&self, cx: &App) -> bool {
227 self.state.read(cx).is_authenticated()
228 }
229
230 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
231 self.state.update(cx, |state, cx| state.authenticate(cx))
232 }
233
234 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
235 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
236 .into()
237 }
238
239 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
240 self.state.update(cx, |state, cx| state.reset_api_key(cx))
241 }
242}
243
244pub struct OpenAiLanguageModel {
245 id: LanguageModelId,
246 model: open_ai::Model,
247 state: gpui::Entity<State>,
248 http_client: Arc<dyn HttpClient>,
249 request_limiter: RateLimiter,
250}
251
252impl OpenAiLanguageModel {
253 fn stream_completion(
254 &self,
255 request: open_ai::Request,
256 cx: &AsyncApp,
257 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
258 {
259 let http_client = self.http_client.clone();
260 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
261 let settings = &AllLanguageModelSettings::get_global(cx).openai;
262 (state.api_key.clone(), settings.api_url.clone())
263 }) else {
264 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
265 };
266
267 let future = self.request_limiter.stream(async move {
268 let api_key = api_key.ok_or_else(|| anyhow!("Missing OpenAI API Key"))?;
269 let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
270 let response = request.await?;
271 Ok(response)
272 });
273
274 async move { Ok(future.await?.boxed()) }.boxed()
275 }
276}
277
278impl LanguageModel for OpenAiLanguageModel {
279 fn id(&self) -> LanguageModelId {
280 self.id.clone()
281 }
282
283 fn name(&self) -> LanguageModelName {
284 LanguageModelName::from(self.model.display_name().to_string())
285 }
286
287 fn provider_id(&self) -> LanguageModelProviderId {
288 LanguageModelProviderId(PROVIDER_ID.into())
289 }
290
291 fn provider_name(&self) -> LanguageModelProviderName {
292 LanguageModelProviderName(PROVIDER_NAME.into())
293 }
294
295 fn supports_tools(&self) -> bool {
296 true
297 }
298
299 fn supports_images(&self) -> bool {
300 false
301 }
302
303 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
304 match choice {
305 LanguageModelToolChoice::Auto => true,
306 LanguageModelToolChoice::Any => true,
307 LanguageModelToolChoice::None => true,
308 }
309 }
310
311 fn telemetry_id(&self) -> String {
312 format!("openai/{}", self.model.id())
313 }
314
315 fn max_token_count(&self) -> usize {
316 self.model.max_token_count()
317 }
318
319 fn max_output_tokens(&self) -> Option<u32> {
320 self.model.max_output_tokens()
321 }
322
323 fn count_tokens(
324 &self,
325 request: LanguageModelRequest,
326 cx: &App,
327 ) -> BoxFuture<'static, Result<usize>> {
328 count_open_ai_tokens(request, self.model.clone(), cx)
329 }
330
331 fn stream_completion(
332 &self,
333 request: LanguageModelRequest,
334 cx: &AsyncApp,
335 ) -> BoxFuture<
336 'static,
337 Result<
338 futures::stream::BoxStream<
339 'static,
340 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
341 >,
342 >,
343 > {
344 let request = into_open_ai(request, &self.model, self.max_output_tokens());
345 let completions = self.stream_completion(request, cx);
346 async move {
347 let mapper = OpenAiEventMapper::new();
348 Ok(mapper.map_stream(completions.await?).boxed())
349 }
350 .boxed()
351 }
352}
353
354pub fn into_open_ai(
355 request: LanguageModelRequest,
356 model: &Model,
357 max_output_tokens: Option<u32>,
358) -> open_ai::Request {
359 let stream = !model.id().starts_with("o1-");
360
361 let mut messages = Vec::new();
362 for message in request.messages {
363 for content in message.content {
364 match content {
365 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
366 add_message_content_part(
367 open_ai::MessagePart::Text { text: text },
368 message.role,
369 &mut messages,
370 )
371 }
372 MessageContent::RedactedThinking(_) => {}
373 MessageContent::Image(image) => {
374 add_message_content_part(
375 open_ai::MessagePart::Image {
376 image_url: ImageUrl {
377 url: image.to_base64_url(),
378 detail: None,
379 },
380 },
381 message.role,
382 &mut messages,
383 );
384 }
385 MessageContent::ToolUse(tool_use) => {
386 let tool_call = open_ai::ToolCall {
387 id: tool_use.id.to_string(),
388 content: open_ai::ToolCallContent::Function {
389 function: open_ai::FunctionContent {
390 name: tool_use.name.to_string(),
391 arguments: serde_json::to_string(&tool_use.input)
392 .unwrap_or_default(),
393 },
394 },
395 };
396
397 if let Some(open_ai::RequestMessage::Assistant { tool_calls, .. }) =
398 messages.last_mut()
399 {
400 tool_calls.push(tool_call);
401 } else {
402 messages.push(open_ai::RequestMessage::Assistant {
403 content: open_ai::MessageContent::empty(),
404 tool_calls: vec![tool_call],
405 });
406 }
407 }
408 MessageContent::ToolResult(tool_result) => {
409 let content = match &tool_result.content {
410 LanguageModelToolResultContent::Text(text) => {
411 vec![open_ai::MessagePart::Text {
412 text: text.to_string(),
413 }]
414 }
415 LanguageModelToolResultContent::Image(image) => {
416 vec![open_ai::MessagePart::Image {
417 image_url: ImageUrl {
418 url: image.to_base64_url(),
419 detail: None,
420 },
421 }]
422 }
423 };
424
425 messages.push(open_ai::RequestMessage::Tool {
426 content: content.into(),
427 tool_call_id: tool_result.tool_use_id.to_string(),
428 });
429 }
430 }
431 }
432 }
433
434 open_ai::Request {
435 model: model.id().into(),
436 messages,
437 stream,
438 stop: request.stop,
439 temperature: request.temperature.unwrap_or(1.0),
440 max_tokens: max_output_tokens,
441 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
442 // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
443 Some(false)
444 } else {
445 None
446 },
447 tools: request
448 .tools
449 .into_iter()
450 .map(|tool| open_ai::ToolDefinition::Function {
451 function: open_ai::FunctionDefinition {
452 name: tool.name,
453 description: Some(tool.description),
454 parameters: Some(tool.input_schema),
455 },
456 })
457 .collect(),
458 tool_choice: request.tool_choice.map(|choice| match choice {
459 LanguageModelToolChoice::Auto => open_ai::ToolChoice::Auto,
460 LanguageModelToolChoice::Any => open_ai::ToolChoice::Required,
461 LanguageModelToolChoice::None => open_ai::ToolChoice::None,
462 }),
463 }
464}
465
466fn add_message_content_part(
467 new_part: open_ai::MessagePart,
468 role: Role,
469 messages: &mut Vec<open_ai::RequestMessage>,
470) {
471 match (role, messages.last_mut()) {
472 (Role::User, Some(open_ai::RequestMessage::User { content }))
473 | (Role::Assistant, Some(open_ai::RequestMessage::Assistant { content, .. }))
474 | (Role::System, Some(open_ai::RequestMessage::System { content, .. })) => {
475 content.push_part(new_part);
476 }
477 _ => {
478 messages.push(match role {
479 Role::User => open_ai::RequestMessage::User {
480 content: open_ai::MessageContent::empty(),
481 },
482 Role::Assistant => open_ai::RequestMessage::Assistant {
483 content: open_ai::MessageContent::empty(),
484 tool_calls: Vec::new(),
485 },
486 Role::System => open_ai::RequestMessage::System {
487 content: open_ai::MessageContent::empty(),
488 },
489 });
490 }
491 }
492}
493
494pub struct OpenAiEventMapper {
495 tool_calls_by_index: HashMap<usize, RawToolCall>,
496}
497
498impl OpenAiEventMapper {
499 pub fn new() -> Self {
500 Self {
501 tool_calls_by_index: HashMap::default(),
502 }
503 }
504
505 pub fn map_stream(
506 mut self,
507 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
508 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
509 {
510 events.flat_map(move |event| {
511 futures::stream::iter(match event {
512 Ok(event) => self.map_event(event),
513 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
514 })
515 })
516 }
517
518 pub fn map_event(
519 &mut self,
520 event: ResponseStreamEvent,
521 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
522 let Some(choice) = event.choices.first() else {
523 return vec![Err(LanguageModelCompletionError::Other(anyhow!(
524 "Response contained no choices"
525 )))];
526 };
527
528 let mut events = Vec::new();
529 if let Some(content) = choice.delta.content.clone() {
530 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
531 }
532
533 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
534 for tool_call in tool_calls {
535 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
536
537 if let Some(tool_id) = tool_call.id.clone() {
538 entry.id = tool_id;
539 }
540
541 if let Some(function) = tool_call.function.as_ref() {
542 if let Some(name) = function.name.clone() {
543 entry.name = name;
544 }
545
546 if let Some(arguments) = function.arguments.clone() {
547 entry.arguments.push_str(&arguments);
548 }
549 }
550 }
551 }
552
553 match choice.finish_reason.as_deref() {
554 Some("stop") => {
555 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
556 }
557 Some("tool_calls") => {
558 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
559 match serde_json::Value::from_str(&tool_call.arguments) {
560 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
561 LanguageModelToolUse {
562 id: tool_call.id.clone().into(),
563 name: tool_call.name.as_str().into(),
564 is_input_complete: true,
565 input,
566 raw_input: tool_call.arguments.clone(),
567 },
568 )),
569 Err(error) => Err(LanguageModelCompletionError::BadInputJson {
570 id: tool_call.id.into(),
571 tool_name: tool_call.name.as_str().into(),
572 raw_input: tool_call.arguments.into(),
573 json_parse_error: error.to_string(),
574 }),
575 }
576 }));
577
578 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
579 }
580 Some(stop_reason) => {
581 log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
582 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
583 }
584 None => {}
585 }
586
587 events
588 }
589}
590
591#[derive(Default)]
592struct RawToolCall {
593 id: String,
594 name: String,
595 arguments: String,
596}
597
598pub fn count_open_ai_tokens(
599 request: LanguageModelRequest,
600 model: Model,
601 cx: &App,
602) -> BoxFuture<'static, Result<usize>> {
603 cx.background_spawn(async move {
604 let messages = request
605 .messages
606 .into_iter()
607 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
608 role: match message.role {
609 Role::User => "user".into(),
610 Role::Assistant => "assistant".into(),
611 Role::System => "system".into(),
612 },
613 content: Some(message.string_contents()),
614 name: None,
615 function_call: None,
616 })
617 .collect::<Vec<_>>();
618
619 match model {
620 Model::Custom { max_tokens, .. } => {
621 let model = if max_tokens >= 100_000 {
622 // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
623 "gpt-4o"
624 } else {
625 // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
626 // supported with this tiktoken method
627 "gpt-4"
628 };
629 tiktoken_rs::num_tokens_from_messages(model, &messages)
630 }
631 // Not currently supported by tiktoken_rs. All use the same tokenizer as gpt-4o (o200k_base)
632 Model::O1
633 | Model::FourPointOne
634 | Model::FourPointOneMini
635 | Model::FourPointOneNano
636 | Model::O3Mini
637 | Model::O3
638 | Model::O4Mini => tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages),
639 // Currently supported by tiktoken_rs
640 Model::ThreePointFiveTurbo
641 | Model::Four
642 | Model::FourTurbo
643 | Model::FourOmni
644 | Model::FourOmniMini
645 | Model::O1Preview
646 | Model::O1Mini => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
647 }
648 })
649 .boxed()
650}
651
652struct ConfigurationView {
653 api_key_editor: Entity<Editor>,
654 state: gpui::Entity<State>,
655 load_credentials_task: Option<Task<()>>,
656}
657
658impl ConfigurationView {
659 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
660 let api_key_editor = cx.new(|cx| {
661 let mut editor = Editor::single_line(window, cx);
662 editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
663 editor
664 });
665
666 cx.observe(&state, |_, _, cx| {
667 cx.notify();
668 })
669 .detach();
670
671 let load_credentials_task = Some(cx.spawn_in(window, {
672 let state = state.clone();
673 async move |this, cx| {
674 if let Some(task) = state
675 .update(cx, |state, cx| state.authenticate(cx))
676 .log_err()
677 {
678 // We don't log an error, because "not signed in" is also an error.
679 let _ = task.await;
680 }
681
682 this.update(cx, |this, cx| {
683 this.load_credentials_task = None;
684 cx.notify();
685 })
686 .log_err();
687 }
688 }));
689
690 Self {
691 api_key_editor,
692 state,
693 load_credentials_task,
694 }
695 }
696
697 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
698 let api_key = self.api_key_editor.read(cx).text(cx);
699 if api_key.is_empty() {
700 return;
701 }
702
703 let state = self.state.clone();
704 cx.spawn_in(window, async move |_, cx| {
705 state
706 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
707 .await
708 })
709 .detach_and_log_err(cx);
710
711 cx.notify();
712 }
713
714 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
715 self.api_key_editor
716 .update(cx, |editor, cx| editor.set_text("", window, cx));
717
718 let state = self.state.clone();
719 cx.spawn_in(window, async move |_, cx| {
720 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
721 })
722 .detach_and_log_err(cx);
723
724 cx.notify();
725 }
726
727 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
728 let settings = ThemeSettings::get_global(cx);
729 let text_style = TextStyle {
730 color: cx.theme().colors().text,
731 font_family: settings.ui_font.family.clone(),
732 font_features: settings.ui_font.features.clone(),
733 font_fallbacks: settings.ui_font.fallbacks.clone(),
734 font_size: rems(0.875).into(),
735 font_weight: settings.ui_font.weight,
736 font_style: FontStyle::Normal,
737 line_height: relative(1.3),
738 white_space: WhiteSpace::Normal,
739 ..Default::default()
740 };
741 EditorElement::new(
742 &self.api_key_editor,
743 EditorStyle {
744 background: cx.theme().colors().editor_background,
745 local_player: cx.theme().players().local(),
746 text: text_style,
747 ..Default::default()
748 },
749 )
750 }
751
752 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
753 !self.state.read(cx).is_authenticated()
754 }
755}
756
757impl Render for ConfigurationView {
758 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
759 let env_var_set = self.state.read(cx).api_key_from_env;
760
761 if self.load_credentials_task.is_some() {
762 div().child(Label::new("Loading credentials...")).into_any()
763 } else if self.should_render_editor(cx) {
764 v_flex()
765 .size_full()
766 .on_action(cx.listener(Self::save_api_key))
767 .child(Label::new("To use Zed's assistant with OpenAI, you need to add an API key. Follow these steps:"))
768 .child(
769 List::new()
770 .child(InstructionListItem::new(
771 "Create one by visiting",
772 Some("OpenAI's console"),
773 Some("https://platform.openai.com/api-keys"),
774 ))
775 .child(InstructionListItem::text_only(
776 "Ensure your OpenAI account has credits",
777 ))
778 .child(InstructionListItem::text_only(
779 "Paste your API key below and hit enter to start using the assistant",
780 )),
781 )
782 .child(
783 h_flex()
784 .w_full()
785 .my_2()
786 .px_2()
787 .py_1()
788 .bg(cx.theme().colors().editor_background)
789 .border_1()
790 .border_color(cx.theme().colors().border)
791 .rounded_sm()
792 .child(self.render_api_key_editor(cx)),
793 )
794 .child(
795 Label::new(
796 format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
797 )
798 .size(LabelSize::Small).color(Color::Muted),
799 )
800 .child(
801 Label::new(
802 "Note that having a subscription for another service like GitHub Copilot won't work.".to_string(),
803 )
804 .size(LabelSize::Small).color(Color::Muted),
805 )
806 .into_any()
807 } else {
808 h_flex()
809 .mt_1()
810 .p_1()
811 .justify_between()
812 .rounded_md()
813 .border_1()
814 .border_color(cx.theme().colors().border)
815 .bg(cx.theme().colors().background)
816 .child(
817 h_flex()
818 .gap_1()
819 .child(Icon::new(IconName::Check).color(Color::Success))
820 .child(Label::new(if env_var_set {
821 format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
822 } else {
823 "API key configured.".to_string()
824 })),
825 )
826 .child(
827 Button::new("reset-key", "Reset Key")
828 .label_size(LabelSize::Small)
829 .icon(Some(IconName::Trash))
830 .icon_size(IconSize::Small)
831 .icon_position(IconPosition::Start)
832 .disabled(env_var_set)
833 .when(env_var_set, |this| {
834 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
835 })
836 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
837 )
838 .into_any()
839 }
840 }
841}