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