1use anyhow::{Context as _, Result, anyhow};
2use collections::HashMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{FutureExt, Stream, StreamExt, future::BoxFuture};
6use gpui::{
7 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
8};
9use http_client::HttpClient;
10use language_model::{
11 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
12 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
13 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
14 LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
15 RateLimiter, Role, StopReason,
16};
17use open_router::{Model, ResponseStreamEvent, list_models, 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 theme::ThemeSettings;
25use ui::{Icon, IconName, List, Tooltip, prelude::*};
26use util::ResultExt;
27
28use crate::{AllLanguageModelSettings, ui::InstructionListItem};
29
30const PROVIDER_ID: &str = "openrouter";
31const PROVIDER_NAME: &str = "OpenRouter";
32
33#[derive(Default, Clone, Debug, PartialEq)]
34pub struct OpenRouterSettings {
35 pub api_url: String,
36 pub available_models: Vec<AvailableModel>,
37}
38
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
40pub struct AvailableModel {
41 pub name: String,
42 pub display_name: Option<String>,
43 pub max_tokens: usize,
44 pub max_output_tokens: Option<u32>,
45 pub max_completion_tokens: Option<u32>,
46}
47
48pub struct OpenRouterLanguageModelProvider {
49 http_client: Arc<dyn HttpClient>,
50 state: gpui::Entity<State>,
51}
52
53pub struct State {
54 api_key: Option<String>,
55 api_key_from_env: bool,
56 http_client: Arc<dyn HttpClient>,
57 available_models: Vec<open_router::Model>,
58 fetch_models_task: Option<Task<Result<()>>>,
59 _subscription: Subscription,
60}
61
62const OPENROUTER_API_KEY_VAR: &str = "OPENROUTER_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 .open_router
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 .open_router
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 .open_router
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(OPENROUTER_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)
126 .context(format!("invalid {} API key", PROVIDER_NAME))?,
127 false,
128 )
129 };
130 this.update(cx, |this, cx| {
131 this.api_key = Some(api_key);
132 this.api_key_from_env = from_env;
133 cx.notify();
134 })?;
135
136 Ok(())
137 })
138 }
139
140 fn fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
141 let settings = &AllLanguageModelSettings::get_global(cx).open_router;
142 let http_client = self.http_client.clone();
143 let api_url = settings.api_url.clone();
144
145 cx.spawn(async move |this, cx| {
146 let models = list_models(http_client.as_ref(), &api_url).await?;
147
148 this.update(cx, |this, cx| {
149 this.available_models = models;
150 cx.notify();
151 })
152 })
153 }
154
155 fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
156 let task = self.fetch_models(cx);
157 self.fetch_models_task.replace(task);
158 }
159}
160
161impl OpenRouterLanguageModelProvider {
162 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
163 let state = cx.new(|cx| State {
164 api_key: None,
165 api_key_from_env: false,
166 http_client: http_client.clone(),
167 available_models: Vec::new(),
168 fetch_models_task: None,
169 _subscription: cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
170 this.restart_fetch_models_task(cx);
171 cx.notify();
172 }),
173 });
174
175 Self { http_client, state }
176 }
177
178 fn create_language_model(&self, model: open_router::Model) -> Arc<dyn LanguageModel> {
179 Arc::new(OpenRouterLanguageModel {
180 id: LanguageModelId::from(model.id().to_string()),
181 model,
182 state: self.state.clone(),
183 http_client: self.http_client.clone(),
184 request_limiter: RateLimiter::new(4),
185 })
186 }
187}
188
189impl LanguageModelProviderState for OpenRouterLanguageModelProvider {
190 type ObservableEntity = State;
191
192 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
193 Some(self.state.clone())
194 }
195}
196
197impl LanguageModelProvider for OpenRouterLanguageModelProvider {
198 fn id(&self) -> LanguageModelProviderId {
199 LanguageModelProviderId(PROVIDER_ID.into())
200 }
201
202 fn name(&self) -> LanguageModelProviderName {
203 LanguageModelProviderName(PROVIDER_NAME.into())
204 }
205
206 fn icon(&self) -> IconName {
207 IconName::AiOpenRouter
208 }
209
210 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
211 Some(self.create_language_model(open_router::Model::default()))
212 }
213
214 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
215 Some(self.create_language_model(open_router::Model::default_fast()))
216 }
217
218 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
219 let mut models_from_api = self.state.read(cx).available_models.clone();
220 let mut settings_models = Vec::new();
221
222 for model in &AllLanguageModelSettings::get_global(cx)
223 .open_router
224 .available_models
225 {
226 settings_models.push(open_router::Model {
227 name: model.name.clone(),
228 display_name: model.display_name.clone(),
229 max_tokens: model.max_tokens,
230 supports_tools: Some(false),
231 });
232 }
233
234 for settings_model in &settings_models {
235 if let Some(pos) = models_from_api
236 .iter()
237 .position(|m| m.name == settings_model.name)
238 {
239 models_from_api[pos] = settings_model.clone();
240 } else {
241 models_from_api.push(settings_model.clone());
242 }
243 }
244
245 models_from_api
246 .into_iter()
247 .map(|model| self.create_language_model(model))
248 .collect()
249 }
250
251 fn is_authenticated(&self, cx: &App) -> bool {
252 self.state.read(cx).is_authenticated()
253 }
254
255 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
256 self.state.update(cx, |state, cx| state.authenticate(cx))
257 }
258
259 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
260 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
261 .into()
262 }
263
264 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
265 self.state.update(cx, |state, cx| state.reset_api_key(cx))
266 }
267}
268
269pub struct OpenRouterLanguageModel {
270 id: LanguageModelId,
271 model: open_router::Model,
272 state: gpui::Entity<State>,
273 http_client: Arc<dyn HttpClient>,
274 request_limiter: RateLimiter,
275}
276
277impl OpenRouterLanguageModel {
278 fn stream_completion(
279 &self,
280 request: open_router::Request,
281 cx: &AsyncApp,
282 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
283 {
284 let http_client = self.http_client.clone();
285 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
286 let settings = &AllLanguageModelSettings::get_global(cx).open_router;
287 (state.api_key.clone(), settings.api_url.clone())
288 }) else {
289 return futures::future::ready(Err(anyhow!(
290 "App state dropped: Unable to read API key or API URL from the application state"
291 )))
292 .boxed();
293 };
294
295 let future = self.request_limiter.stream(async move {
296 let api_key = api_key.ok_or_else(|| anyhow!("Missing OpenRouter API Key"))?;
297 let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
298 let response = request.await?;
299 Ok(response)
300 });
301
302 async move { Ok(future.await?.boxed()) }.boxed()
303 }
304}
305
306impl LanguageModel for OpenRouterLanguageModel {
307 fn id(&self) -> LanguageModelId {
308 self.id.clone()
309 }
310
311 fn name(&self) -> LanguageModelName {
312 LanguageModelName::from(self.model.display_name().to_string())
313 }
314
315 fn provider_id(&self) -> LanguageModelProviderId {
316 LanguageModelProviderId(PROVIDER_ID.into())
317 }
318
319 fn provider_name(&self) -> LanguageModelProviderName {
320 LanguageModelProviderName(PROVIDER_NAME.into())
321 }
322
323 fn supports_tools(&self) -> bool {
324 self.model.supports_tool_calls()
325 }
326
327 fn telemetry_id(&self) -> String {
328 format!("openrouter/{}", self.model.id())
329 }
330
331 fn max_token_count(&self) -> usize {
332 self.model.max_token_count()
333 }
334
335 fn max_output_tokens(&self) -> Option<u32> {
336 self.model.max_output_tokens()
337 }
338
339 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
340 match choice {
341 LanguageModelToolChoice::Auto => true,
342 LanguageModelToolChoice::Any => true,
343 LanguageModelToolChoice::None => true,
344 }
345 }
346
347 fn supports_images(&self) -> bool {
348 false
349 }
350
351 fn count_tokens(
352 &self,
353 request: LanguageModelRequest,
354 cx: &App,
355 ) -> BoxFuture<'static, Result<usize>> {
356 count_open_router_tokens(request, self.model.clone(), cx)
357 }
358
359 fn stream_completion(
360 &self,
361 request: LanguageModelRequest,
362 cx: &AsyncApp,
363 ) -> BoxFuture<
364 'static,
365 Result<
366 futures::stream::BoxStream<
367 'static,
368 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
369 >,
370 LanguageModelCompletionError,
371 >,
372 > {
373 let request = into_open_router(request, &self.model, self.max_output_tokens());
374 let completions = self.stream_completion(request, cx);
375 async move {
376 let mapper = OpenRouterEventMapper::new();
377 Ok(mapper.map_stream(completions.await?).boxed())
378 }
379 .boxed()
380 }
381}
382
383pub fn into_open_router(
384 request: LanguageModelRequest,
385 model: &Model,
386 max_output_tokens: Option<u32>,
387) -> open_router::Request {
388 let mut messages = Vec::new();
389 for req_message in request.messages {
390 for content in req_message.content {
391 match content {
392 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => messages
393 .push(match req_message.role {
394 Role::User => open_router::RequestMessage::User { content: text },
395 Role::Assistant => open_router::RequestMessage::Assistant {
396 content: Some(text),
397 tool_calls: Vec::new(),
398 },
399 Role::System => open_router::RequestMessage::System { content: text },
400 }),
401 MessageContent::RedactedThinking(_) => {}
402 MessageContent::Image(_) => {}
403 MessageContent::ToolUse(tool_use) => {
404 let tool_call = open_router::ToolCall {
405 id: tool_use.id.to_string(),
406 content: open_router::ToolCallContent::Function {
407 function: open_router::FunctionContent {
408 name: tool_use.name.to_string(),
409 arguments: serde_json::to_string(&tool_use.input)
410 .unwrap_or_default(),
411 },
412 },
413 };
414
415 if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
416 messages.last_mut()
417 {
418 tool_calls.push(tool_call);
419 } else {
420 messages.push(open_router::RequestMessage::Assistant {
421 content: None,
422 tool_calls: vec![tool_call],
423 });
424 }
425 }
426 MessageContent::ToolResult(tool_result) => {
427 let content = match &tool_result.content {
428 LanguageModelToolResultContent::Text(text) => {
429 text.to_string()
430 }
431 LanguageModelToolResultContent::Image(_) => {
432 "[Tool responded with an image, but Zed doesn't support these in Open AI models yet]".to_string()
433 }
434 };
435
436 messages.push(open_router::RequestMessage::Tool {
437 content: content,
438 tool_call_id: tool_result.tool_use_id.to_string(),
439 });
440 }
441 }
442 }
443 }
444
445 open_router::Request {
446 model: model.id().into(),
447 messages,
448 stream: true,
449 stop: request.stop,
450 temperature: request.temperature.unwrap_or(0.4),
451 max_tokens: max_output_tokens,
452 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
453 Some(false)
454 } else {
455 None
456 },
457 tools: request
458 .tools
459 .into_iter()
460 .map(|tool| open_router::ToolDefinition::Function {
461 function: open_router::FunctionDefinition {
462 name: tool.name,
463 description: Some(tool.description),
464 parameters: Some(tool.input_schema),
465 },
466 })
467 .collect(),
468 tool_choice: request.tool_choice.map(|choice| match choice {
469 LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
470 LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
471 LanguageModelToolChoice::None => open_router::ToolChoice::None,
472 }),
473 }
474}
475
476pub struct OpenRouterEventMapper {
477 tool_calls_by_index: HashMap<usize, RawToolCall>,
478}
479
480impl OpenRouterEventMapper {
481 pub fn new() -> Self {
482 Self {
483 tool_calls_by_index: HashMap::default(),
484 }
485 }
486
487 pub fn map_stream(
488 mut self,
489 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
490 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
491 {
492 events.flat_map(move |event| {
493 futures::stream::iter(match event {
494 Ok(event) => self.map_event(event),
495 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
496 })
497 })
498 }
499
500 pub fn map_event(
501 &mut self,
502 event: ResponseStreamEvent,
503 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
504 let Some(choice) = event.choices.first() else {
505 return vec![Err(LanguageModelCompletionError::Other(anyhow!(
506 "Response contained no choices"
507 )))];
508 };
509
510 let mut events = Vec::new();
511 if let Some(content) = choice.delta.content.clone() {
512 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
513 }
514
515 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
516 for tool_call in tool_calls {
517 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
518
519 if let Some(tool_id) = tool_call.id.clone() {
520 entry.id = tool_id;
521 }
522
523 if let Some(function) = tool_call.function.as_ref() {
524 if let Some(name) = function.name.clone() {
525 entry.name = name;
526 }
527
528 if let Some(arguments) = function.arguments.clone() {
529 entry.arguments.push_str(&arguments);
530 }
531 }
532 }
533 }
534
535 match choice.finish_reason.as_deref() {
536 Some("stop") => {
537 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
538 }
539 Some("tool_calls") => {
540 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
541 match serde_json::Value::from_str(&tool_call.arguments) {
542 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
543 LanguageModelToolUse {
544 id: tool_call.id.clone().into(),
545 name: tool_call.name.as_str().into(),
546 is_input_complete: true,
547 input,
548 raw_input: tool_call.arguments.clone(),
549 },
550 )),
551 Err(error) => Err(LanguageModelCompletionError::BadInputJson {
552 id: tool_call.id.into(),
553 tool_name: tool_call.name.as_str().into(),
554 raw_input: tool_call.arguments.into(),
555 json_parse_error: error.to_string(),
556 }),
557 }
558 }));
559
560 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
561 }
562 Some(stop_reason) => {
563 log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
564 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
565 }
566 None => {}
567 }
568
569 events
570 }
571}
572
573#[derive(Default)]
574struct RawToolCall {
575 id: String,
576 name: String,
577 arguments: String,
578}
579
580pub fn count_open_router_tokens(
581 request: LanguageModelRequest,
582 _model: open_router::Model,
583 cx: &App,
584) -> BoxFuture<'static, Result<usize>> {
585 cx.background_spawn(async move {
586 let messages = request
587 .messages
588 .into_iter()
589 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
590 role: match message.role {
591 Role::User => "user".into(),
592 Role::Assistant => "assistant".into(),
593 Role::System => "system".into(),
594 },
595 content: Some(message.string_contents()),
596 name: None,
597 function_call: None,
598 })
599 .collect::<Vec<_>>();
600
601 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages)
602 })
603 .boxed()
604}
605
606struct ConfigurationView {
607 api_key_editor: Entity<Editor>,
608 state: gpui::Entity<State>,
609 load_credentials_task: Option<Task<()>>,
610}
611
612impl ConfigurationView {
613 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
614 let api_key_editor = cx.new(|cx| {
615 let mut editor = Editor::single_line(window, cx);
616 editor
617 .set_placeholder_text("sk_or_000000000000000000000000000000000000000000000000", cx);
618 editor
619 });
620
621 cx.observe(&state, |_, _, cx| {
622 cx.notify();
623 })
624 .detach();
625
626 let load_credentials_task = Some(cx.spawn_in(window, {
627 let state = state.clone();
628 async move |this, cx| {
629 if let Some(task) = state
630 .update(cx, |state, cx| state.authenticate(cx))
631 .log_err()
632 {
633 let _ = task.await;
634 }
635
636 this.update(cx, |this, cx| {
637 this.load_credentials_task = None;
638 cx.notify();
639 })
640 .log_err();
641 }
642 }));
643
644 Self {
645 api_key_editor,
646 state,
647 load_credentials_task,
648 }
649 }
650
651 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
652 let api_key = self.api_key_editor.read(cx).text(cx);
653 if api_key.is_empty() {
654 return;
655 }
656
657 let state = self.state.clone();
658 cx.spawn_in(window, async move |_, cx| {
659 state
660 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
661 .await
662 })
663 .detach_and_log_err(cx);
664
665 cx.notify();
666 }
667
668 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
669 self.api_key_editor
670 .update(cx, |editor, cx| editor.set_text("", window, cx));
671
672 let state = self.state.clone();
673 cx.spawn_in(window, async move |_, cx| {
674 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
675 })
676 .detach_and_log_err(cx);
677
678 cx.notify();
679 }
680
681 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
682 let settings = ThemeSettings::get_global(cx);
683 let text_style = TextStyle {
684 color: cx.theme().colors().text,
685 font_family: settings.ui_font.family.clone(),
686 font_features: settings.ui_font.features.clone(),
687 font_fallbacks: settings.ui_font.fallbacks.clone(),
688 font_size: rems(0.875).into(),
689 font_weight: settings.ui_font.weight,
690 font_style: FontStyle::Normal,
691 line_height: relative(1.3),
692 white_space: WhiteSpace::Normal,
693 ..Default::default()
694 };
695 EditorElement::new(
696 &self.api_key_editor,
697 EditorStyle {
698 background: cx.theme().colors().editor_background,
699 local_player: cx.theme().players().local(),
700 text: text_style,
701 ..Default::default()
702 },
703 )
704 }
705
706 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
707 !self.state.read(cx).is_authenticated()
708 }
709}
710
711impl Render for ConfigurationView {
712 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
713 let env_var_set = self.state.read(cx).api_key_from_env;
714
715 if self.load_credentials_task.is_some() {
716 div().child(Label::new("Loading credentials...")).into_any()
717 } else if self.should_render_editor(cx) {
718 v_flex()
719 .size_full()
720 .on_action(cx.listener(Self::save_api_key))
721 .child(Label::new("To use Zed's assistant with OpenRouter, you need to add an API key. Follow these steps:"))
722 .child(
723 List::new()
724 .child(InstructionListItem::new(
725 "Create an API key by visiting",
726 Some("OpenRouter's console"),
727 Some("https://openrouter.ai/keys"),
728 ))
729 .child(InstructionListItem::text_only(
730 "Ensure your OpenRouter account has credits",
731 ))
732 .child(InstructionListItem::text_only(
733 "Paste your API key below and hit enter to start using the assistant",
734 )),
735 )
736 .child(
737 h_flex()
738 .w_full()
739 .my_2()
740 .px_2()
741 .py_1()
742 .bg(cx.theme().colors().editor_background)
743 .border_1()
744 .border_color(cx.theme().colors().border)
745 .rounded_sm()
746 .child(self.render_api_key_editor(cx)),
747 )
748 .child(
749 Label::new(
750 format!("You can also assign the {OPENROUTER_API_KEY_VAR} environment variable and restart Zed."),
751 )
752 .size(LabelSize::Small).color(Color::Muted),
753 )
754 .into_any()
755 } else {
756 h_flex()
757 .mt_1()
758 .p_1()
759 .justify_between()
760 .rounded_md()
761 .border_1()
762 .border_color(cx.theme().colors().border)
763 .bg(cx.theme().colors().background)
764 .child(
765 h_flex()
766 .gap_1()
767 .child(Icon::new(IconName::Check).color(Color::Success))
768 .child(Label::new(if env_var_set {
769 format!("API key set in {OPENROUTER_API_KEY_VAR} environment variable.")
770 } else {
771 "API key configured.".to_string()
772 })),
773 )
774 .child(
775 Button::new("reset-key", "Reset Key")
776 .label_size(LabelSize::Small)
777 .icon(Some(IconName::Trash))
778 .icon_size(IconSize::Small)
779 .icon_position(IconPosition::Start)
780 .disabled(env_var_set)
781 .when(env_var_set, |this| {
782 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENROUTER_API_KEY_VAR} environment variable.")))
783 })
784 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
785 )
786 .into_any()
787 }
788 }
789}