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: u64,
48 pub max_output_tokens: Option<u64>,
49 pub max_completion_tokens: Option<u64>,
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) -> u64 {
318 self.model.max_token_count()
319 }
320
321 fn max_output_tokens(&self) -> Option<u64> {
322 self.model.max_output_tokens()
323 }
324
325 fn count_tokens(
326 &self,
327 request: LanguageModelRequest,
328 cx: &App,
329 ) -> BoxFuture<'static, Result<u64>> {
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(
348 request,
349 self.model.id(),
350 self.model.supports_parallel_tool_calls(),
351 self.max_output_tokens(),
352 );
353 let completions = self.stream_completion(request, cx);
354 async move {
355 let mapper = OpenAiEventMapper::new();
356 Ok(mapper.map_stream(completions.await?).boxed())
357 }
358 .boxed()
359 }
360}
361
362pub fn into_open_ai(
363 request: LanguageModelRequest,
364 model_id: &str,
365 supports_parallel_tool_calls: bool,
366 max_output_tokens: Option<u64>,
367) -> open_ai::Request {
368 let stream = !model_id.starts_with("o1-");
369
370 let mut messages = Vec::new();
371 for message in request.messages {
372 for content in message.content {
373 match content {
374 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
375 add_message_content_part(
376 open_ai::MessagePart::Text { text: text },
377 message.role,
378 &mut messages,
379 )
380 }
381 MessageContent::RedactedThinking(_) => {}
382 MessageContent::Image(image) => {
383 add_message_content_part(
384 open_ai::MessagePart::Image {
385 image_url: ImageUrl {
386 url: image.to_base64_url(),
387 detail: None,
388 },
389 },
390 message.role,
391 &mut messages,
392 );
393 }
394 MessageContent::ToolUse(tool_use) => {
395 let tool_call = open_ai::ToolCall {
396 id: tool_use.id.to_string(),
397 content: open_ai::ToolCallContent::Function {
398 function: open_ai::FunctionContent {
399 name: tool_use.name.to_string(),
400 arguments: serde_json::to_string(&tool_use.input)
401 .unwrap_or_default(),
402 },
403 },
404 };
405
406 if let Some(open_ai::RequestMessage::Assistant { tool_calls, .. }) =
407 messages.last_mut()
408 {
409 tool_calls.push(tool_call);
410 } else {
411 messages.push(open_ai::RequestMessage::Assistant {
412 content: None,
413 tool_calls: vec![tool_call],
414 });
415 }
416 }
417 MessageContent::ToolResult(tool_result) => {
418 let content = match &tool_result.content {
419 LanguageModelToolResultContent::Text(text) => {
420 vec![open_ai::MessagePart::Text {
421 text: text.to_string(),
422 }]
423 }
424 LanguageModelToolResultContent::Image(image) => {
425 vec![open_ai::MessagePart::Image {
426 image_url: ImageUrl {
427 url: image.to_base64_url(),
428 detail: None,
429 },
430 }]
431 }
432 };
433
434 messages.push(open_ai::RequestMessage::Tool {
435 content: content.into(),
436 tool_call_id: tool_result.tool_use_id.to_string(),
437 });
438 }
439 }
440 }
441 }
442
443 open_ai::Request {
444 model: model_id.into(),
445 messages,
446 stream,
447 stop: request.stop,
448 temperature: request.temperature.unwrap_or(1.0),
449 max_completion_tokens: max_output_tokens,
450 parallel_tool_calls: if supports_parallel_tool_calls && !request.tools.is_empty() {
451 // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
452 Some(false)
453 } else {
454 None
455 },
456 tools: request
457 .tools
458 .into_iter()
459 .map(|tool| open_ai::ToolDefinition::Function {
460 function: open_ai::FunctionDefinition {
461 name: tool.name,
462 description: Some(tool.description),
463 parameters: Some(tool.input_schema),
464 },
465 })
466 .collect(),
467 tool_choice: request.tool_choice.map(|choice| match choice {
468 LanguageModelToolChoice::Auto => open_ai::ToolChoice::Auto,
469 LanguageModelToolChoice::Any => open_ai::ToolChoice::Required,
470 LanguageModelToolChoice::None => open_ai::ToolChoice::None,
471 }),
472 }
473}
474
475fn add_message_content_part(
476 new_part: open_ai::MessagePart,
477 role: Role,
478 messages: &mut Vec<open_ai::RequestMessage>,
479) {
480 match (role, messages.last_mut()) {
481 (Role::User, Some(open_ai::RequestMessage::User { content }))
482 | (
483 Role::Assistant,
484 Some(open_ai::RequestMessage::Assistant {
485 content: Some(content),
486 ..
487 }),
488 )
489 | (Role::System, Some(open_ai::RequestMessage::System { content, .. })) => {
490 content.push_part(new_part);
491 }
492 _ => {
493 messages.push(match role {
494 Role::User => open_ai::RequestMessage::User {
495 content: open_ai::MessageContent::from(vec![new_part]),
496 },
497 Role::Assistant => open_ai::RequestMessage::Assistant {
498 content: Some(open_ai::MessageContent::from(vec![new_part])),
499 tool_calls: Vec::new(),
500 },
501 Role::System => open_ai::RequestMessage::System {
502 content: open_ai::MessageContent::from(vec![new_part]),
503 },
504 });
505 }
506 }
507}
508
509pub struct OpenAiEventMapper {
510 tool_calls_by_index: HashMap<usize, RawToolCall>,
511}
512
513impl OpenAiEventMapper {
514 pub fn new() -> Self {
515 Self {
516 tool_calls_by_index: HashMap::default(),
517 }
518 }
519
520 pub fn map_stream(
521 mut self,
522 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
523 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
524 {
525 events.flat_map(move |event| {
526 futures::stream::iter(match event {
527 Ok(event) => self.map_event(event),
528 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
529 })
530 })
531 }
532
533 pub fn map_event(
534 &mut self,
535 event: ResponseStreamEvent,
536 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
537 let Some(choice) = event.choices.first() else {
538 return Vec::new();
539 };
540
541 let mut events = Vec::new();
542 if let Some(content) = choice.delta.content.clone() {
543 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
544 }
545
546 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
547 for tool_call in tool_calls {
548 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
549
550 if let Some(tool_id) = tool_call.id.clone() {
551 entry.id = tool_id;
552 }
553
554 if let Some(function) = tool_call.function.as_ref() {
555 if let Some(name) = function.name.clone() {
556 entry.name = name;
557 }
558
559 if let Some(arguments) = function.arguments.clone() {
560 entry.arguments.push_str(&arguments);
561 }
562 }
563 }
564 }
565
566 match choice.finish_reason.as_deref() {
567 Some("stop") => {
568 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
569 }
570 Some("tool_calls") => {
571 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
572 match serde_json::Value::from_str(&tool_call.arguments) {
573 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
574 LanguageModelToolUse {
575 id: tool_call.id.clone().into(),
576 name: tool_call.name.as_str().into(),
577 is_input_complete: true,
578 input,
579 raw_input: tool_call.arguments.clone(),
580 },
581 )),
582 Err(error) => Err(LanguageModelCompletionError::BadInputJson {
583 id: tool_call.id.into(),
584 tool_name: tool_call.name.as_str().into(),
585 raw_input: tool_call.arguments.into(),
586 json_parse_error: error.to_string(),
587 }),
588 }
589 }));
590
591 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
592 }
593 Some(stop_reason) => {
594 log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
595 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
596 }
597 None => {}
598 }
599
600 events
601 }
602}
603
604#[derive(Default)]
605struct RawToolCall {
606 id: String,
607 name: String,
608 arguments: String,
609}
610
611pub fn count_open_ai_tokens(
612 request: LanguageModelRequest,
613 model: Model,
614 cx: &App,
615) -> BoxFuture<'static, Result<u64>> {
616 cx.background_spawn(async move {
617 let messages = request
618 .messages
619 .into_iter()
620 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
621 role: match message.role {
622 Role::User => "user".into(),
623 Role::Assistant => "assistant".into(),
624 Role::System => "system".into(),
625 },
626 content: Some(message.string_contents()),
627 name: None,
628 function_call: None,
629 })
630 .collect::<Vec<_>>();
631
632 match model {
633 Model::Custom { max_tokens, .. } => {
634 let model = if max_tokens >= 100_000 {
635 // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
636 "gpt-4o"
637 } else {
638 // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
639 // supported with this tiktoken method
640 "gpt-4"
641 };
642 tiktoken_rs::num_tokens_from_messages(model, &messages)
643 }
644 // Currently supported by tiktoken_rs
645 // Sometimes tiktoken-rs is behind on model support. If that is the case, make a new branch
646 // arm with an override. We enumerate all supported models here so that we can check if new
647 // models are supported yet or not.
648 Model::ThreePointFiveTurbo
649 | Model::Four
650 | Model::FourTurbo
651 | Model::FourOmni
652 | Model::FourOmniMini
653 | Model::FourPointOne
654 | Model::FourPointOneMini
655 | Model::FourPointOneNano
656 | Model::O1
657 | Model::O3
658 | Model::O3Mini
659 | Model::O4Mini => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
660 }
661 .map(|tokens| tokens as u64)
662 })
663 .boxed()
664}
665
666struct ConfigurationView {
667 api_key_editor: Entity<SingleLineInput>,
668 api_url_editor: Entity<SingleLineInput>,
669 state: gpui::Entity<State>,
670 load_credentials_task: Option<Task<()>>,
671}
672
673impl ConfigurationView {
674 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
675 let api_key_editor = cx.new(|cx| {
676 SingleLineInput::new(
677 window,
678 cx,
679 "sk-000000000000000000000000000000000000000000000000",
680 )
681 .label("API key")
682 });
683
684 let api_url = AllLanguageModelSettings::get_global(cx)
685 .openai
686 .api_url
687 .clone();
688
689 let api_url_editor = cx.new(|cx| {
690 let input = SingleLineInput::new(window, cx, open_ai::OPEN_AI_API_URL).label("API URL");
691
692 if !api_url.is_empty() {
693 input.editor.update(cx, |editor, cx| {
694 editor.set_text(&*api_url, window, cx);
695 });
696 }
697 input
698 });
699
700 cx.observe(&state, |_, _, cx| {
701 cx.notify();
702 })
703 .detach();
704
705 let load_credentials_task = Some(cx.spawn_in(window, {
706 let state = state.clone();
707 async move |this, cx| {
708 if let Some(task) = state
709 .update(cx, |state, cx| state.authenticate(cx))
710 .log_err()
711 {
712 // We don't log an error, because "not signed in" is also an error.
713 let _ = task.await;
714 }
715 this.update(cx, |this, cx| {
716 this.load_credentials_task = None;
717 cx.notify();
718 })
719 .log_err();
720 }
721 }));
722
723 Self {
724 api_key_editor,
725 api_url_editor,
726 state,
727 load_credentials_task,
728 }
729 }
730
731 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
732 let api_key = self
733 .api_key_editor
734 .read(cx)
735 .editor()
736 .read(cx)
737 .text(cx)
738 .trim()
739 .to_string();
740
741 // Don't proceed if no API key is provided and we're not authenticated
742 if api_key.is_empty() && !self.state.read(cx).is_authenticated() {
743 return;
744 }
745
746 let state = self.state.clone();
747 cx.spawn_in(window, async move |_, cx| {
748 state
749 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
750 .await
751 })
752 .detach_and_log_err(cx);
753
754 cx.notify();
755 }
756
757 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
758 self.api_key_editor.update(cx, |input, cx| {
759 input.editor.update(cx, |editor, cx| {
760 editor.set_text("", window, cx);
761 });
762 });
763
764 let state = self.state.clone();
765 cx.spawn_in(window, async move |_, cx| {
766 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
767 })
768 .detach_and_log_err(cx);
769
770 cx.notify();
771 }
772
773 fn save_api_url(&mut self, cx: &mut Context<Self>) {
774 let api_url = self
775 .api_url_editor
776 .read(cx)
777 .editor()
778 .read(cx)
779 .text(cx)
780 .trim()
781 .to_string();
782
783 let current_url = AllLanguageModelSettings::get_global(cx)
784 .openai
785 .api_url
786 .clone();
787
788 let effective_current_url = if current_url.is_empty() {
789 open_ai::OPEN_AI_API_URL
790 } else {
791 ¤t_url
792 };
793
794 if !api_url.is_empty() && api_url != effective_current_url {
795 let fs = <dyn Fs>::global(cx);
796 update_settings_file::<AllLanguageModelSettings>(fs, cx, move |settings, _| {
797 use crate::settings::{OpenAiSettingsContent, VersionedOpenAiSettingsContent};
798
799 if settings.openai.is_none() {
800 settings.openai = Some(OpenAiSettingsContent::Versioned(
801 VersionedOpenAiSettingsContent::V1(
802 crate::settings::OpenAiSettingsContentV1 {
803 api_url: Some(api_url.clone()),
804 available_models: None,
805 },
806 ),
807 ));
808 } else {
809 if let Some(openai) = settings.openai.as_mut() {
810 match openai {
811 OpenAiSettingsContent::Versioned(versioned) => match versioned {
812 VersionedOpenAiSettingsContent::V1(v1) => {
813 v1.api_url = Some(api_url.clone());
814 }
815 },
816 OpenAiSettingsContent::Legacy(legacy) => {
817 legacy.api_url = Some(api_url.clone());
818 }
819 }
820 }
821 }
822 });
823 }
824 }
825
826 fn reset_api_url(&mut self, window: &mut Window, cx: &mut Context<Self>) {
827 self.api_url_editor.update(cx, |input, cx| {
828 input.editor.update(cx, |editor, cx| {
829 editor.set_text("", window, cx);
830 });
831 });
832 let fs = <dyn Fs>::global(cx);
833 update_settings_file::<AllLanguageModelSettings>(fs, cx, |settings, _cx| {
834 use crate::settings::{OpenAiSettingsContent, VersionedOpenAiSettingsContent};
835
836 if let Some(openai) = settings.openai.as_mut() {
837 match openai {
838 OpenAiSettingsContent::Versioned(versioned) => match versioned {
839 VersionedOpenAiSettingsContent::V1(v1) => {
840 v1.api_url = None;
841 }
842 },
843 OpenAiSettingsContent::Legacy(legacy) => {
844 legacy.api_url = None;
845 }
846 }
847 }
848 });
849 cx.notify();
850 }
851
852 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
853 !self.state.read(cx).is_authenticated()
854 }
855}
856
857impl Render for ConfigurationView {
858 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
859 let env_var_set = self.state.read(cx).api_key_from_env;
860
861 let api_key_section = if self.should_render_editor(cx) {
862 v_flex()
863 .on_action(cx.listener(Self::save_api_key))
864
865 .child(Label::new("To use Zed's assistant with OpenAI, you need to add an API key. Follow these steps:"))
866 .child(
867 List::new()
868 .child(InstructionListItem::new(
869 "Create one by visiting",
870 Some("OpenAI's console"),
871 Some("https://platform.openai.com/api-keys"),
872 ))
873 .child(InstructionListItem::text_only(
874 "Ensure your OpenAI account has credits",
875 ))
876 .child(InstructionListItem::text_only(
877 "Paste your API key below and hit enter to start using the assistant",
878 )),
879 )
880 .child(self.api_key_editor.clone())
881 .child(
882 Label::new(
883 format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
884 )
885 .size(LabelSize::Small).color(Color::Muted),
886 )
887 .child(
888 Label::new(
889 "Note that having a subscription for another service like GitHub Copilot won't work.",
890 )
891 .size(LabelSize::Small).color(Color::Muted),
892 )
893 .into_any()
894 } else {
895 h_flex()
896 .mt_1()
897 .p_1()
898 .justify_between()
899 .rounded_md()
900 .border_1()
901 .border_color(cx.theme().colors().border)
902 .bg(cx.theme().colors().background)
903 .child(
904 h_flex()
905 .gap_1()
906 .child(Icon::new(IconName::Check).color(Color::Success))
907 .child(Label::new(if env_var_set {
908 format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
909 } else {
910 "API key configured.".to_string()
911 })),
912 )
913 .child(
914 Button::new("reset-key", "Reset API Key")
915 .label_size(LabelSize::Small)
916 .icon(IconName::Undo)
917 .icon_size(IconSize::Small)
918 .icon_position(IconPosition::Start)
919 .layer(ElevationIndex::ModalSurface)
920 .when(env_var_set, |this| {
921 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
922 })
923 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
924 )
925 .into_any()
926 };
927
928 let custom_api_url_set =
929 AllLanguageModelSettings::get_global(cx).openai.api_url != open_ai::OPEN_AI_API_URL;
930
931 let api_url_section = if custom_api_url_set {
932 h_flex()
933 .mt_1()
934 .p_1()
935 .justify_between()
936 .rounded_md()
937 .border_1()
938 .border_color(cx.theme().colors().border)
939 .bg(cx.theme().colors().background)
940 .child(
941 h_flex()
942 .gap_1()
943 .child(Icon::new(IconName::Check).color(Color::Success))
944 .child(Label::new("Custom API URL configured.")),
945 )
946 .child(
947 Button::new("reset-key", "Reset API URL")
948 .label_size(LabelSize::Small)
949 .icon(IconName::Undo)
950 .icon_size(IconSize::Small)
951 .icon_position(IconPosition::Start)
952 .layer(ElevationIndex::ModalSurface)
953 .on_click(
954 cx.listener(|this, _, window, cx| this.reset_api_url(window, cx)),
955 ),
956 )
957 .into_any()
958 } else {
959 v_flex()
960 .on_action(cx.listener(|this, _: &menu::Confirm, _window, cx| {
961 this.save_api_url(cx);
962 cx.notify();
963 }))
964 .mt_2()
965 .pt_2()
966 .border_t_1()
967 .border_color(cx.theme().colors().border_variant)
968 .gap_1()
969 .child(
970 List::new()
971 .child(InstructionListItem::text_only(
972 "Optionally, you can change the base URL for the OpenAI API request.",
973 ))
974 .child(InstructionListItem::text_only(
975 "Paste the new API endpoint below and hit enter",
976 )),
977 )
978 .child(self.api_url_editor.clone())
979 .into_any()
980 };
981
982 if self.load_credentials_task.is_some() {
983 div().child(Label::new("Loading credentials…")).into_any()
984 } else {
985 v_flex()
986 .size_full()
987 .child(api_key_section)
988 .child(api_url_section)
989 .into_any()
990 }
991 }
992}
993
994#[cfg(test)]
995mod tests {
996 use gpui::TestAppContext;
997 use language_model::LanguageModelRequestMessage;
998
999 use super::*;
1000
1001 #[gpui::test]
1002 fn tiktoken_rs_support(cx: &TestAppContext) {
1003 let request = LanguageModelRequest {
1004 thread_id: None,
1005 prompt_id: None,
1006 intent: None,
1007 mode: None,
1008 messages: vec![LanguageModelRequestMessage {
1009 role: Role::User,
1010 content: vec![MessageContent::Text("message".into())],
1011 cache: false,
1012 }],
1013 tools: vec![],
1014 tool_choice: None,
1015 stop: vec![],
1016 temperature: None,
1017 };
1018
1019 // Validate that all models are supported by tiktoken-rs
1020 for model in Model::iter() {
1021 let count = cx
1022 .executor()
1023 .block(count_open_ai_tokens(
1024 request.clone(),
1025 model,
1026 &cx.app.borrow(),
1027 ))
1028 .unwrap();
1029 assert!(count > 0);
1030 }
1031 }
1032}