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 >,
371 > {
372 let request = into_open_router(request, &self.model, self.max_output_tokens());
373 let completions = self.stream_completion(request, cx);
374 async move {
375 let mapper = OpenRouterEventMapper::new();
376 Ok(mapper.map_stream(completions.await?).boxed())
377 }
378 .boxed()
379 }
380}
381
382pub fn into_open_router(
383 request: LanguageModelRequest,
384 model: &Model,
385 max_output_tokens: Option<u32>,
386) -> open_router::Request {
387 let mut messages = Vec::new();
388 for req_message in request.messages {
389 for content in req_message.content {
390 match content {
391 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => messages
392 .push(match req_message.role {
393 Role::User => open_router::RequestMessage::User { content: text },
394 Role::Assistant => open_router::RequestMessage::Assistant {
395 content: Some(text),
396 tool_calls: Vec::new(),
397 },
398 Role::System => open_router::RequestMessage::System { content: text },
399 }),
400 MessageContent::RedactedThinking(_) => {}
401 MessageContent::Image(_) => {}
402 MessageContent::ToolUse(tool_use) => {
403 let tool_call = open_router::ToolCall {
404 id: tool_use.id.to_string(),
405 content: open_router::ToolCallContent::Function {
406 function: open_router::FunctionContent {
407 name: tool_use.name.to_string(),
408 arguments: serde_json::to_string(&tool_use.input)
409 .unwrap_or_default(),
410 },
411 },
412 };
413
414 if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
415 messages.last_mut()
416 {
417 tool_calls.push(tool_call);
418 } else {
419 messages.push(open_router::RequestMessage::Assistant {
420 content: None,
421 tool_calls: vec![tool_call],
422 });
423 }
424 }
425 MessageContent::ToolResult(tool_result) => {
426 let content = match &tool_result.content {
427 LanguageModelToolResultContent::Text(text) => {
428 text.to_string()
429 }
430 LanguageModelToolResultContent::Image(_) => {
431 "[Tool responded with an image, but Zed doesn't support these in Open AI models yet]".to_string()
432 }
433 };
434
435 messages.push(open_router::RequestMessage::Tool {
436 content: content,
437 tool_call_id: tool_result.tool_use_id.to_string(),
438 });
439 }
440 }
441 }
442 }
443
444 open_router::Request {
445 model: model.id().into(),
446 messages,
447 stream: true,
448 stop: request.stop,
449 temperature: request.temperature.unwrap_or(0.4),
450 max_tokens: max_output_tokens,
451 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
452 Some(false)
453 } else {
454 None
455 },
456 tools: request
457 .tools
458 .into_iter()
459 .map(|tool| open_router::ToolDefinition::Function {
460 function: open_router::FunctionDefinition {
461 name: tool.name,
462 description: Some(tool.description),
463 parameters: Some(tool.input_schema),
464 },
465 })
466 .collect(),
467 tool_choice: request.tool_choice.map(|choice| match choice {
468 LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
469 LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
470 LanguageModelToolChoice::None => open_router::ToolChoice::None,
471 }),
472 }
473}
474
475pub struct OpenRouterEventMapper {
476 tool_calls_by_index: HashMap<usize, RawToolCall>,
477}
478
479impl OpenRouterEventMapper {
480 pub fn new() -> Self {
481 Self {
482 tool_calls_by_index: HashMap::default(),
483 }
484 }
485
486 pub fn map_stream(
487 mut self,
488 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
489 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
490 {
491 events.flat_map(move |event| {
492 futures::stream::iter(match event {
493 Ok(event) => self.map_event(event),
494 Err(error) => vec![Err(LanguageModelCompletionError::Other(anyhow!(error)))],
495 })
496 })
497 }
498
499 pub fn map_event(
500 &mut self,
501 event: ResponseStreamEvent,
502 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
503 let Some(choice) = event.choices.first() else {
504 return vec![Err(LanguageModelCompletionError::Other(anyhow!(
505 "Response contained no choices"
506 )))];
507 };
508
509 let mut events = Vec::new();
510 if let Some(content) = choice.delta.content.clone() {
511 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
512 }
513
514 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
515 for tool_call in tool_calls {
516 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
517
518 if let Some(tool_id) = tool_call.id.clone() {
519 entry.id = tool_id;
520 }
521
522 if let Some(function) = tool_call.function.as_ref() {
523 if let Some(name) = function.name.clone() {
524 entry.name = name;
525 }
526
527 if let Some(arguments) = function.arguments.clone() {
528 entry.arguments.push_str(&arguments);
529 }
530 }
531 }
532 }
533
534 match choice.finish_reason.as_deref() {
535 Some("stop") => {
536 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
537 }
538 Some("tool_calls") => {
539 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
540 match serde_json::Value::from_str(&tool_call.arguments) {
541 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
542 LanguageModelToolUse {
543 id: tool_call.id.clone().into(),
544 name: tool_call.name.as_str().into(),
545 is_input_complete: true,
546 input,
547 raw_input: tool_call.arguments.clone(),
548 },
549 )),
550 Err(error) => Err(LanguageModelCompletionError::BadInputJson {
551 id: tool_call.id.into(),
552 tool_name: tool_call.name.as_str().into(),
553 raw_input: tool_call.arguments.into(),
554 json_parse_error: error.to_string(),
555 }),
556 }
557 }));
558
559 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
560 }
561 Some(stop_reason) => {
562 log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
563 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
564 }
565 None => {}
566 }
567
568 events
569 }
570}
571
572#[derive(Default)]
573struct RawToolCall {
574 id: String,
575 name: String,
576 arguments: String,
577}
578
579pub fn count_open_router_tokens(
580 request: LanguageModelRequest,
581 _model: open_router::Model,
582 cx: &App,
583) -> BoxFuture<'static, Result<usize>> {
584 cx.background_spawn(async move {
585 let messages = request
586 .messages
587 .into_iter()
588 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
589 role: match message.role {
590 Role::User => "user".into(),
591 Role::Assistant => "assistant".into(),
592 Role::System => "system".into(),
593 },
594 content: Some(message.string_contents()),
595 name: None,
596 function_call: None,
597 })
598 .collect::<Vec<_>>();
599
600 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages)
601 })
602 .boxed()
603}
604
605struct ConfigurationView {
606 api_key_editor: Entity<Editor>,
607 state: gpui::Entity<State>,
608 load_credentials_task: Option<Task<()>>,
609}
610
611impl ConfigurationView {
612 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
613 let api_key_editor = cx.new(|cx| {
614 let mut editor = Editor::single_line(window, cx);
615 editor
616 .set_placeholder_text("sk_or_000000000000000000000000000000000000000000000000", cx);
617 editor
618 });
619
620 cx.observe(&state, |_, _, cx| {
621 cx.notify();
622 })
623 .detach();
624
625 let load_credentials_task = Some(cx.spawn_in(window, {
626 let state = state.clone();
627 async move |this, cx| {
628 if let Some(task) = state
629 .update(cx, |state, cx| state.authenticate(cx))
630 .log_err()
631 {
632 let _ = task.await;
633 }
634
635 this.update(cx, |this, cx| {
636 this.load_credentials_task = None;
637 cx.notify();
638 })
639 .log_err();
640 }
641 }));
642
643 Self {
644 api_key_editor,
645 state,
646 load_credentials_task,
647 }
648 }
649
650 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
651 let api_key = self.api_key_editor.read(cx).text(cx);
652 if api_key.is_empty() {
653 return;
654 }
655
656 let state = self.state.clone();
657 cx.spawn_in(window, async move |_, cx| {
658 state
659 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
660 .await
661 })
662 .detach_and_log_err(cx);
663
664 cx.notify();
665 }
666
667 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
668 self.api_key_editor
669 .update(cx, |editor, cx| editor.set_text("", window, cx));
670
671 let state = self.state.clone();
672 cx.spawn_in(window, async move |_, cx| {
673 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
674 })
675 .detach_and_log_err(cx);
676
677 cx.notify();
678 }
679
680 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
681 let settings = ThemeSettings::get_global(cx);
682 let text_style = TextStyle {
683 color: cx.theme().colors().text,
684 font_family: settings.ui_font.family.clone(),
685 font_features: settings.ui_font.features.clone(),
686 font_fallbacks: settings.ui_font.fallbacks.clone(),
687 font_size: rems(0.875).into(),
688 font_weight: settings.ui_font.weight,
689 font_style: FontStyle::Normal,
690 line_height: relative(1.3),
691 white_space: WhiteSpace::Normal,
692 ..Default::default()
693 };
694 EditorElement::new(
695 &self.api_key_editor,
696 EditorStyle {
697 background: cx.theme().colors().editor_background,
698 local_player: cx.theme().players().local(),
699 text: text_style,
700 ..Default::default()
701 },
702 )
703 }
704
705 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
706 !self.state.read(cx).is_authenticated()
707 }
708}
709
710impl Render for ConfigurationView {
711 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
712 let env_var_set = self.state.read(cx).api_key_from_env;
713
714 if self.load_credentials_task.is_some() {
715 div().child(Label::new("Loading credentials...")).into_any()
716 } else if self.should_render_editor(cx) {
717 v_flex()
718 .size_full()
719 .on_action(cx.listener(Self::save_api_key))
720 .child(Label::new("To use Zed's assistant with OpenRouter, you need to add an API key. Follow these steps:"))
721 .child(
722 List::new()
723 .child(InstructionListItem::new(
724 "Create an API key by visiting",
725 Some("OpenRouter's console"),
726 Some("https://openrouter.ai/keys"),
727 ))
728 .child(InstructionListItem::text_only(
729 "Ensure your OpenRouter account has credits",
730 ))
731 .child(InstructionListItem::text_only(
732 "Paste your API key below and hit enter to start using the assistant",
733 )),
734 )
735 .child(
736 h_flex()
737 .w_full()
738 .my_2()
739 .px_2()
740 .py_1()
741 .bg(cx.theme().colors().editor_background)
742 .border_1()
743 .border_color(cx.theme().colors().border)
744 .rounded_sm()
745 .child(self.render_api_key_editor(cx)),
746 )
747 .child(
748 Label::new(
749 format!("You can also assign the {OPENROUTER_API_KEY_VAR} environment variable and restart Zed."),
750 )
751 .size(LabelSize::Small).color(Color::Muted),
752 )
753 .into_any()
754 } else {
755 h_flex()
756 .mt_1()
757 .p_1()
758 .justify_between()
759 .rounded_md()
760 .border_1()
761 .border_color(cx.theme().colors().border)
762 .bg(cx.theme().colors().background)
763 .child(
764 h_flex()
765 .gap_1()
766 .child(Icon::new(IconName::Check).color(Color::Success))
767 .child(Label::new(if env_var_set {
768 format!("API key set in {OPENROUTER_API_KEY_VAR} environment variable.")
769 } else {
770 "API key configured.".to_string()
771 })),
772 )
773 .child(
774 Button::new("reset-key", "Reset Key")
775 .label_size(LabelSize::Small)
776 .icon(Some(IconName::Trash))
777 .icon_size(IconSize::Small)
778 .icon_position(IconPosition::Start)
779 .disabled(env_var_set)
780 .when(env_var_set, |this| {
781 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENROUTER_API_KEY_VAR} environment variable.")))
782 })
783 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
784 )
785 .into_any()
786 }
787 }
788}