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