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: u64,
 47    pub max_output_tokens: Option<u64>,
 48    pub max_completion_tokens: Option<u64>,
 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) -> u64 {
316        self.model.max_token_count()
317    }
318
319    fn max_output_tokens(&self) -> Option<u64> {
320        self.model.max_output_tokens()
321    }
322
323    fn count_tokens(
324        &self,
325        request: LanguageModelRequest,
326        cx: &App,
327    ) -> BoxFuture<'static, Result<u64>> {
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            LanguageModelCompletionError,
343        >,
344    > {
345        let request = into_open_ai(request, &self.model, self.max_output_tokens());
346        let completions = self.stream_completion(request, cx);
347        async move {
348            let mapper = OpenAiEventMapper::new();
349            Ok(mapper.map_stream(completions.await?).boxed())
350        }
351        .boxed()
352    }
353}
354
355pub fn into_open_ai(
356    request: LanguageModelRequest,
357    model: &Model,
358    max_output_tokens: Option<u64>,
359) -> open_ai::Request {
360    let stream = !model.id().starts_with("o1-");
361
362    let mut messages = Vec::new();
363    for message in request.messages {
364        for content in message.content {
365            match content {
366                MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
367                    add_message_content_part(
368                        open_ai::MessagePart::Text { text: text },
369                        message.role,
370                        &mut messages,
371                    )
372                }
373                MessageContent::RedactedThinking(_) => {}
374                MessageContent::Image(image) => {
375                    add_message_content_part(
376                        open_ai::MessagePart::Image {
377                            image_url: ImageUrl {
378                                url: image.to_base64_url(),
379                                detail: None,
380                            },
381                        },
382                        message.role,
383                        &mut messages,
384                    );
385                }
386                MessageContent::ToolUse(tool_use) => {
387                    let tool_call = open_ai::ToolCall {
388                        id: tool_use.id.to_string(),
389                        content: open_ai::ToolCallContent::Function {
390                            function: open_ai::FunctionContent {
391                                name: tool_use.name.to_string(),
392                                arguments: serde_json::to_string(&tool_use.input)
393                                    .unwrap_or_default(),
394                            },
395                        },
396                    };
397
398                    if let Some(open_ai::RequestMessage::Assistant { tool_calls, .. }) =
399                        messages.last_mut()
400                    {
401                        tool_calls.push(tool_call);
402                    } else {
403                        messages.push(open_ai::RequestMessage::Assistant {
404                            content: None,
405                            tool_calls: vec![tool_call],
406                        });
407                    }
408                }
409                MessageContent::ToolResult(tool_result) => {
410                    let content = match &tool_result.content {
411                        LanguageModelToolResultContent::Text(text) => {
412                            vec![open_ai::MessagePart::Text {
413                                text: text.to_string(),
414                            }]
415                        }
416                        LanguageModelToolResultContent::Image(image) => {
417                            vec![open_ai::MessagePart::Image {
418                                image_url: ImageUrl {
419                                    url: image.to_base64_url(),
420                                    detail: None,
421                                },
422                            }]
423                        }
424                    };
425
426                    messages.push(open_ai::RequestMessage::Tool {
427                        content: content.into(),
428                        tool_call_id: tool_result.tool_use_id.to_string(),
429                    });
430                }
431            }
432        }
433    }
434
435    open_ai::Request {
436        model: model.id().into(),
437        messages,
438        stream,
439        stop: request.stop,
440        temperature: request.temperature.unwrap_or(1.0),
441        max_completion_tokens: max_output_tokens,
442        parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
443            // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
444            Some(false)
445        } else {
446            None
447        },
448        tools: request
449            .tools
450            .into_iter()
451            .map(|tool| open_ai::ToolDefinition::Function {
452                function: open_ai::FunctionDefinition {
453                    name: tool.name,
454                    description: Some(tool.description),
455                    parameters: Some(tool.input_schema),
456                },
457            })
458            .collect(),
459        tool_choice: request.tool_choice.map(|choice| match choice {
460            LanguageModelToolChoice::Auto => open_ai::ToolChoice::Auto,
461            LanguageModelToolChoice::Any => open_ai::ToolChoice::Required,
462            LanguageModelToolChoice::None => open_ai::ToolChoice::None,
463        }),
464    }
465}
466
467fn add_message_content_part(
468    new_part: open_ai::MessagePart,
469    role: Role,
470    messages: &mut Vec<open_ai::RequestMessage>,
471) {
472    match (role, messages.last_mut()) {
473        (Role::User, Some(open_ai::RequestMessage::User { content }))
474        | (
475            Role::Assistant,
476            Some(open_ai::RequestMessage::Assistant {
477                content: Some(content),
478                ..
479            }),
480        )
481        | (Role::System, Some(open_ai::RequestMessage::System { content, .. })) => {
482            content.push_part(new_part);
483        }
484        _ => {
485            messages.push(match role {
486                Role::User => open_ai::RequestMessage::User {
487                    content: open_ai::MessageContent::from(vec![new_part]),
488                },
489                Role::Assistant => open_ai::RequestMessage::Assistant {
490                    content: Some(open_ai::MessageContent::from(vec![new_part])),
491                    tool_calls: Vec::new(),
492                },
493                Role::System => open_ai::RequestMessage::System {
494                    content: open_ai::MessageContent::from(vec![new_part]),
495                },
496            });
497        }
498    }
499}
500
501pub struct OpenAiEventMapper {
502    tool_calls_by_index: HashMap<usize, RawToolCall>,
503}
504
505impl OpenAiEventMapper {
506    pub fn new() -> Self {
507        Self {
508            tool_calls_by_index: HashMap::default(),
509        }
510    }
511
512    pub fn map_stream(
513        mut self,
514        events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
515    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
516    {
517        events.flat_map(move |event| {
518            futures::stream::iter(match event {
519                Ok(event) => self.map_event(event),
520                Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
521            })
522        })
523    }
524
525    pub fn map_event(
526        &mut self,
527        event: ResponseStreamEvent,
528    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
529        let Some(choice) = event.choices.first() else {
530            return vec![Err(LanguageModelCompletionError::Other(anyhow!(
531                "Response contained no choices"
532            )))];
533        };
534
535        let mut events = Vec::new();
536        if let Some(content) = choice.delta.content.clone() {
537            events.push(Ok(LanguageModelCompletionEvent::Text(content)));
538        }
539
540        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
541            for tool_call in tool_calls {
542                let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
543
544                if let Some(tool_id) = tool_call.id.clone() {
545                    entry.id = tool_id;
546                }
547
548                if let Some(function) = tool_call.function.as_ref() {
549                    if let Some(name) = function.name.clone() {
550                        entry.name = name;
551                    }
552
553                    if let Some(arguments) = function.arguments.clone() {
554                        entry.arguments.push_str(&arguments);
555                    }
556                }
557            }
558        }
559
560        match choice.finish_reason.as_deref() {
561            Some("stop") => {
562                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
563            }
564            Some("tool_calls") => {
565                events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
566                    match serde_json::Value::from_str(&tool_call.arguments) {
567                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
568                            LanguageModelToolUse {
569                                id: tool_call.id.clone().into(),
570                                name: tool_call.name.as_str().into(),
571                                is_input_complete: true,
572                                input,
573                                raw_input: tool_call.arguments.clone(),
574                            },
575                        )),
576                        Err(error) => Err(LanguageModelCompletionError::BadInputJson {
577                            id: tool_call.id.into(),
578                            tool_name: tool_call.name.as_str().into(),
579                            raw_input: tool_call.arguments.into(),
580                            json_parse_error: error.to_string(),
581                        }),
582                    }
583                }));
584
585                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
586            }
587            Some(stop_reason) => {
588                log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
589                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
590            }
591            None => {}
592        }
593
594        events
595    }
596}
597
598#[derive(Default)]
599struct RawToolCall {
600    id: String,
601    name: String,
602    arguments: String,
603}
604
605pub fn count_open_ai_tokens(
606    request: LanguageModelRequest,
607    model: Model,
608    cx: &App,
609) -> BoxFuture<'static, Result<u64>> {
610    cx.background_spawn(async move {
611        let messages = request
612            .messages
613            .into_iter()
614            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
615                role: match message.role {
616                    Role::User => "user".into(),
617                    Role::Assistant => "assistant".into(),
618                    Role::System => "system".into(),
619                },
620                content: Some(message.string_contents()),
621                name: None,
622                function_call: None,
623            })
624            .collect::<Vec<_>>();
625
626        match model {
627            Model::Custom { max_tokens, .. } => {
628                let model = if max_tokens >= 100_000 {
629                    // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
630                    "gpt-4o"
631                } else {
632                    // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
633                    // supported with this tiktoken method
634                    "gpt-4"
635                };
636                tiktoken_rs::num_tokens_from_messages(model, &messages)
637            }
638            // Currently supported by tiktoken_rs
639            // Sometimes tiktoken-rs is behind on model support. If that is the case, make a new branch
640            // arm with an override. We enumerate all supported models here so that we can check if new
641            // models are supported yet or not.
642            Model::ThreePointFiveTurbo
643            | Model::Four
644            | Model::FourTurbo
645            | Model::FourOmni
646            | Model::FourOmniMini
647            | Model::FourPointOne
648            | Model::FourPointOneMini
649            | Model::FourPointOneNano
650            | Model::O1
651            | Model::O3
652            | Model::O3Mini
653            | Model::O4Mini => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
654        }
655        .map(|tokens| tokens as u64)
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}