open_ai.rs

  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, 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}
 49
 50pub struct OpenAiLanguageModelProvider {
 51    http_client: Arc<dyn HttpClient>,
 52    state: gpui::Entity<State>,
 53}
 54
 55pub struct State {
 56    api_key: Option<String>,
 57    api_key_from_env: bool,
 58    _subscription: Subscription,
 59}
 60
 61const OPENAI_API_KEY_VAR: &str = "OPENAI_API_KEY";
 62
 63impl State {
 64    //
 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        PROVIDER_ID
175    }
176
177    fn name(&self) -> LanguageModelProviderName {
178        PROVIDER_NAME
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 Some(api_key) = api_key else {
269                return Err(LanguageModelCompletionError::NoApiKey {
270                    provider: PROVIDER_NAME,
271                });
272            };
273            let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
274            let response = request.await?;
275            Ok(response)
276        });
277
278        async move { Ok(future.await?.boxed()) }.boxed()
279    }
280}
281
282impl LanguageModel for OpenAiLanguageModel {
283    fn id(&self) -> LanguageModelId {
284        self.id.clone()
285    }
286
287    fn name(&self) -> LanguageModelName {
288        LanguageModelName::from(self.model.display_name().to_string())
289    }
290
291    fn provider_id(&self) -> LanguageModelProviderId {
292        PROVIDER_ID
293    }
294
295    fn provider_name(&self) -> LanguageModelProviderName {
296        PROVIDER_NAME
297    }
298
299    fn supports_tools(&self) -> bool {
300        true
301    }
302
303    fn supports_images(&self) -> bool {
304        false
305    }
306
307    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
308        match choice {
309            LanguageModelToolChoice::Auto => true,
310            LanguageModelToolChoice::Any => true,
311            LanguageModelToolChoice::None => true,
312        }
313    }
314
315    fn telemetry_id(&self) -> String {
316        format!("openai/{}", self.model.id())
317    }
318
319    fn max_token_count(&self) -> u64 {
320        self.model.max_token_count()
321    }
322
323    fn max_output_tokens(&self) -> Option<u64> {
324        self.model.max_output_tokens()
325    }
326
327    fn count_tokens(
328        &self,
329        request: LanguageModelRequest,
330        cx: &App,
331    ) -> BoxFuture<'static, Result<u64>> {
332        count_open_ai_tokens(request, self.model.clone(), cx)
333    }
334
335    fn stream_completion(
336        &self,
337        request: LanguageModelRequest,
338        cx: &AsyncApp,
339    ) -> BoxFuture<
340        'static,
341        Result<
342            futures::stream::BoxStream<
343                'static,
344                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
345            >,
346            LanguageModelCompletionError,
347        >,
348    > {
349        let request = into_open_ai(
350            request,
351            self.model.id(),
352            self.model.supports_parallel_tool_calls(),
353            self.max_output_tokens(),
354        );
355        let completions = self.stream_completion(request, cx);
356        async move {
357            let mapper = OpenAiEventMapper::new();
358            Ok(mapper.map_stream(completions.await?).boxed())
359        }
360        .boxed()
361    }
362}
363
364pub fn into_open_ai(
365    request: LanguageModelRequest,
366    model_id: &str,
367    supports_parallel_tool_calls: bool,
368    max_output_tokens: Option<u64>,
369) -> open_ai::Request {
370    let stream = !model_id.starts_with("o1-");
371
372    let mut messages = Vec::new();
373    for message in request.messages {
374        for content in message.content {
375            match content {
376                MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
377                    add_message_content_part(
378                        open_ai::MessagePart::Text { text: text },
379                        message.role,
380                        &mut messages,
381                    )
382                }
383                MessageContent::RedactedThinking(_) => {}
384                MessageContent::Image(image) => {
385                    add_message_content_part(
386                        open_ai::MessagePart::Image {
387                            image_url: ImageUrl {
388                                url: image.to_base64_url(),
389                                detail: None,
390                            },
391                        },
392                        message.role,
393                        &mut messages,
394                    );
395                }
396                MessageContent::ToolUse(tool_use) => {
397                    let tool_call = open_ai::ToolCall {
398                        id: tool_use.id.to_string(),
399                        content: open_ai::ToolCallContent::Function {
400                            function: open_ai::FunctionContent {
401                                name: tool_use.name.to_string(),
402                                arguments: serde_json::to_string(&tool_use.input)
403                                    .unwrap_or_default(),
404                            },
405                        },
406                    };
407
408                    if let Some(open_ai::RequestMessage::Assistant { tool_calls, .. }) =
409                        messages.last_mut()
410                    {
411                        tool_calls.push(tool_call);
412                    } else {
413                        messages.push(open_ai::RequestMessage::Assistant {
414                            content: None,
415                            tool_calls: vec![tool_call],
416                        });
417                    }
418                }
419                MessageContent::ToolResult(tool_result) => {
420                    let content = match &tool_result.content {
421                        LanguageModelToolResultContent::Text(text) => {
422                            vec![open_ai::MessagePart::Text {
423                                text: text.to_string(),
424                            }]
425                        }
426                        LanguageModelToolResultContent::Image(image) => {
427                            vec![open_ai::MessagePart::Image {
428                                image_url: ImageUrl {
429                                    url: image.to_base64_url(),
430                                    detail: None,
431                                },
432                            }]
433                        }
434                    };
435
436                    messages.push(open_ai::RequestMessage::Tool {
437                        content: content.into(),
438                        tool_call_id: tool_result.tool_use_id.to_string(),
439                    });
440                }
441            }
442        }
443    }
444
445    open_ai::Request {
446        model: model_id.into(),
447        messages,
448        stream,
449        stop: request.stop,
450        temperature: request.temperature.unwrap_or(1.0),
451        max_completion_tokens: max_output_tokens,
452        parallel_tool_calls: if supports_parallel_tool_calls && !request.tools.is_empty() {
453            // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
454            Some(false)
455        } else {
456            None
457        },
458        tools: request
459            .tools
460            .into_iter()
461            .map(|tool| open_ai::ToolDefinition::Function {
462                function: open_ai::FunctionDefinition {
463                    name: tool.name,
464                    description: Some(tool.description),
465                    parameters: Some(tool.input_schema),
466                },
467            })
468            .collect(),
469        tool_choice: request.tool_choice.map(|choice| match choice {
470            LanguageModelToolChoice::Auto => open_ai::ToolChoice::Auto,
471            LanguageModelToolChoice::Any => open_ai::ToolChoice::Required,
472            LanguageModelToolChoice::None => open_ai::ToolChoice::None,
473        }),
474    }
475}
476
477fn add_message_content_part(
478    new_part: open_ai::MessagePart,
479    role: Role,
480    messages: &mut Vec<open_ai::RequestMessage>,
481) {
482    match (role, messages.last_mut()) {
483        (Role::User, Some(open_ai::RequestMessage::User { content }))
484        | (
485            Role::Assistant,
486            Some(open_ai::RequestMessage::Assistant {
487                content: Some(content),
488                ..
489            }),
490        )
491        | (Role::System, Some(open_ai::RequestMessage::System { content, .. })) => {
492            content.push_part(new_part);
493        }
494        _ => {
495            messages.push(match role {
496                Role::User => open_ai::RequestMessage::User {
497                    content: open_ai::MessageContent::from(vec![new_part]),
498                },
499                Role::Assistant => open_ai::RequestMessage::Assistant {
500                    content: Some(open_ai::MessageContent::from(vec![new_part])),
501                    tool_calls: Vec::new(),
502                },
503                Role::System => open_ai::RequestMessage::System {
504                    content: open_ai::MessageContent::from(vec![new_part]),
505                },
506            });
507        }
508    }
509}
510
511pub struct OpenAiEventMapper {
512    tool_calls_by_index: HashMap<usize, RawToolCall>,
513}
514
515impl OpenAiEventMapper {
516    pub fn new() -> Self {
517        Self {
518            tool_calls_by_index: HashMap::default(),
519        }
520    }
521
522    pub fn map_stream(
523        mut self,
524        events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
525    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
526    {
527        events.flat_map(move |event| {
528            futures::stream::iter(match event {
529                Ok(event) => self.map_event(event),
530                Err(error) => vec![Err(LanguageModelCompletionError::from(anyhow!(error)))],
531            })
532        })
533    }
534
535    pub fn map_event(
536        &mut self,
537        event: ResponseStreamEvent,
538    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
539        let mut events = Vec::new();
540        if let Some(usage) = event.usage {
541            events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
542                input_tokens: usage.prompt_tokens,
543                output_tokens: usage.completion_tokens,
544                cache_creation_input_tokens: 0,
545                cache_read_input_tokens: 0,
546            })));
547        }
548
549        let Some(choice) = event.choices.first() else {
550            return events;
551        };
552
553        if let Some(content) = choice.delta.content.clone() {
554            events.push(Ok(LanguageModelCompletionEvent::Text(content)));
555        }
556
557        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
558            for tool_call in tool_calls {
559                let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
560
561                if let Some(tool_id) = tool_call.id.clone() {
562                    entry.id = tool_id;
563                }
564
565                if let Some(function) = tool_call.function.as_ref() {
566                    if let Some(name) = function.name.clone() {
567                        entry.name = name;
568                    }
569
570                    if let Some(arguments) = function.arguments.clone() {
571                        entry.arguments.push_str(&arguments);
572                    }
573                }
574            }
575        }
576
577        match choice.finish_reason.as_deref() {
578            Some("stop") => {
579                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
580            }
581            Some("tool_calls") => {
582                events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
583                    match serde_json::Value::from_str(&tool_call.arguments) {
584                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
585                            LanguageModelToolUse {
586                                id: tool_call.id.clone().into(),
587                                name: tool_call.name.as_str().into(),
588                                is_input_complete: true,
589                                input,
590                                raw_input: tool_call.arguments.clone(),
591                            },
592                        )),
593                        Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
594                            id: tool_call.id.into(),
595                            tool_name: tool_call.name.into(),
596                            raw_input: tool_call.arguments.clone().into(),
597                            json_parse_error: error.to_string(),
598                        }),
599                    }
600                }));
601
602                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
603            }
604            Some(stop_reason) => {
605                log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
606                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
607            }
608            None => {}
609        }
610
611        events
612    }
613}
614
615#[derive(Default)]
616struct RawToolCall {
617    id: String,
618    name: String,
619    arguments: String,
620}
621
622pub(crate) fn collect_tiktoken_messages(
623    request: LanguageModelRequest,
624) -> Vec<tiktoken_rs::ChatCompletionRequestMessage> {
625    request
626        .messages
627        .into_iter()
628        .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
629            role: match message.role {
630                Role::User => "user".into(),
631                Role::Assistant => "assistant".into(),
632                Role::System => "system".into(),
633            },
634            content: Some(message.string_contents()),
635            name: None,
636            function_call: None,
637        })
638        .collect::<Vec<_>>()
639}
640
641pub fn count_open_ai_tokens(
642    request: LanguageModelRequest,
643    model: Model,
644    cx: &App,
645) -> BoxFuture<'static, Result<u64>> {
646    cx.background_spawn(async move {
647        let messages = collect_tiktoken_messages(request);
648
649        match model {
650            Model::Custom { max_tokens, .. } => {
651                let model = if max_tokens >= 100_000 {
652                    // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
653                    "gpt-4o"
654                } else {
655                    // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
656                    // supported with this tiktoken method
657                    "gpt-4"
658                };
659                tiktoken_rs::num_tokens_from_messages(model, &messages)
660            }
661            // Currently supported by tiktoken_rs
662            // Sometimes tiktoken-rs is behind on model support. If that is the case, make a new branch
663            // arm with an override. We enumerate all supported models here so that we can check if new
664            // models are supported yet or not.
665            Model::ThreePointFiveTurbo
666            | Model::Four
667            | Model::FourTurbo
668            | Model::FourOmni
669            | Model::FourOmniMini
670            | Model::FourPointOne
671            | Model::FourPointOneMini
672            | Model::FourPointOneNano
673            | Model::O1
674            | Model::O3
675            | Model::O3Mini
676            | Model::O4Mini => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
677            // GPT-5 models don't have tiktoken support yet; fall back on gpt-4o tokenizer
678            Model::Five | Model::FiveMini | Model::FiveNano => {
679                tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages)
680            }
681        }
682        .map(|tokens| tokens as u64)
683    })
684    .boxed()
685}
686
687struct ConfigurationView {
688    api_key_editor: Entity<SingleLineInput>,
689    state: gpui::Entity<State>,
690    load_credentials_task: Option<Task<()>>,
691}
692
693impl ConfigurationView {
694    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
695        let api_key_editor = cx.new(|cx| {
696            SingleLineInput::new(
697                window,
698                cx,
699                "sk-000000000000000000000000000000000000000000000000",
700            )
701        });
702
703        cx.observe(&state, |_, _, cx| {
704            cx.notify();
705        })
706        .detach();
707
708        let load_credentials_task = Some(cx.spawn_in(window, {
709            let state = state.clone();
710            async move |this, cx| {
711                if let Some(task) = state
712                    .update(cx, |state, cx| state.authenticate(cx))
713                    .log_err()
714                {
715                    // We don't log an error, because "not signed in" is also an error.
716                    let _ = task.await;
717                }
718                this.update(cx, |this, cx| {
719                    this.load_credentials_task = None;
720                    cx.notify();
721                })
722                .log_err();
723            }
724        }));
725
726        Self {
727            api_key_editor,
728            state,
729            load_credentials_task,
730        }
731    }
732
733    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
734        let api_key = self
735            .api_key_editor
736            .read(cx)
737            .editor()
738            .read(cx)
739            .text(cx)
740            .trim()
741            .to_string();
742
743        // Don't proceed if no API key is provided and we're not authenticated
744        if api_key.is_empty() && !self.state.read(cx).is_authenticated() {
745            return;
746        }
747
748        let state = self.state.clone();
749        cx.spawn_in(window, async move |_, cx| {
750            state
751                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
752                .await
753        })
754        .detach_and_log_err(cx);
755
756        cx.notify();
757    }
758
759    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
760        self.api_key_editor.update(cx, |input, cx| {
761            input.editor.update(cx, |editor, cx| {
762                editor.set_text("", window, cx);
763            });
764        });
765
766        let state = self.state.clone();
767        cx.spawn_in(window, async move |_, cx| {
768            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
769        })
770        .detach_and_log_err(cx);
771
772        cx.notify();
773    }
774
775    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
776        !self.state.read(cx).is_authenticated()
777    }
778}
779
780impl Render for ConfigurationView {
781    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
782        let env_var_set = self.state.read(cx).api_key_from_env;
783
784        let api_key_section = if self.should_render_editor(cx) {
785            v_flex()
786                .on_action(cx.listener(Self::save_api_key))
787                .child(Label::new("To use Zed's agent with OpenAI, you need to add an API key. Follow these steps:"))
788                .child(
789                    List::new()
790                        .child(InstructionListItem::new(
791                            "Create one by visiting",
792                            Some("OpenAI's console"),
793                            Some("https://platform.openai.com/api-keys"),
794                        ))
795                        .child(InstructionListItem::text_only(
796                            "Ensure your OpenAI account has credits",
797                        ))
798                        .child(InstructionListItem::text_only(
799                            "Paste your API key below and hit enter to start using the assistant",
800                        )),
801                )
802                .child(self.api_key_editor.clone())
803                .child(
804                    Label::new(
805                        format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
806                    )
807                    .size(LabelSize::Small).color(Color::Muted),
808                )
809                .child(
810                    Label::new(
811                        "Note that having a subscription for another service like GitHub Copilot won't work.",
812                    )
813                    .size(LabelSize::Small).color(Color::Muted),
814                )
815                .into_any()
816        } else {
817            h_flex()
818                .mt_1()
819                .p_1()
820                .justify_between()
821                .rounded_md()
822                .border_1()
823                .border_color(cx.theme().colors().border)
824                .bg(cx.theme().colors().background)
825                .child(
826                    h_flex()
827                        .gap_1()
828                        .child(Icon::new(IconName::Check).color(Color::Success))
829                        .child(Label::new(if env_var_set {
830                            format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
831                        } else {
832                            "API key configured.".to_string()
833                        })),
834                )
835                .child(
836                    Button::new("reset-api-key", "Reset API Key")
837                        .label_size(LabelSize::Small)
838                        .icon(IconName::Undo)
839                        .icon_size(IconSize::Small)
840                        .icon_position(IconPosition::Start)
841                        .layer(ElevationIndex::ModalSurface)
842                        .when(env_var_set, |this| {
843                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
844                        })
845                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
846                )
847                .into_any()
848        };
849
850        let compatible_api_section = h_flex()
851            .mt_1p5()
852            .gap_0p5()
853            .flex_wrap()
854            .when(self.should_render_editor(cx), |this| {
855                this.pt_1p5()
856                    .border_t_1()
857                    .border_color(cx.theme().colors().border_variant)
858            })
859            .child(
860                h_flex()
861                    .gap_2()
862                    .child(
863                        Icon::new(IconName::Info)
864                            .size(IconSize::XSmall)
865                            .color(Color::Muted),
866                    )
867                    .child(Label::new("Zed also supports OpenAI-compatible models.")),
868            )
869            .child(
870                Button::new("docs", "Learn More")
871                    .icon(IconName::ArrowUpRight)
872                    .icon_size(IconSize::XSmall)
873                    .icon_color(Color::Muted)
874                    .on_click(move |_, _window, cx| {
875                        cx.open_url("https://zed.dev/docs/ai/llm-providers#openai-api-compatible")
876                    }),
877            );
878
879        if self.load_credentials_task.is_some() {
880            div().child(Label::new("Loading credentials…")).into_any()
881        } else {
882            v_flex()
883                .size_full()
884                .child(api_key_section)
885                .child(compatible_api_section)
886                .into_any()
887        }
888    }
889}
890
891#[cfg(test)]
892mod tests {
893    use gpui::TestAppContext;
894    use language_model::LanguageModelRequestMessage;
895
896    use super::*;
897
898    #[gpui::test]
899    fn tiktoken_rs_support(cx: &TestAppContext) {
900        let request = LanguageModelRequest {
901            thread_id: None,
902            prompt_id: None,
903            intent: None,
904            mode: None,
905            messages: vec![LanguageModelRequestMessage {
906                role: Role::User,
907                content: vec![MessageContent::Text("message".into())],
908                cache: false,
909            }],
910            tools: vec![],
911            tool_choice: None,
912            stop: vec![],
913            temperature: None,
914            thinking_allowed: true,
915        };
916
917        // Validate that all models are supported by tiktoken-rs
918        for model in Model::iter() {
919            let count = cx
920                .executor()
921                .block(count_open_ai_tokens(
922                    request.clone(),
923                    model,
924                    &cx.app.borrow(),
925                ))
926                .unwrap();
927            assert!(count > 0);
928        }
929    }
930}