open_ai.rs

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