1use anyhow::{Result, anyhow};
2use collections::HashMap;
3use futures::{FutureExt, Stream, StreamExt, future::BoxFuture};
4use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task};
5use http_client::HttpClient;
6use language_model::{
7 ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
8 LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
9 LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
10 LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
11 LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
12 StopReason, TokenUsage, env_var,
13};
14use open_router::{
15 Model, ModelMode as OpenRouterModelMode, OPEN_ROUTER_API_URL, ResponseStreamEvent, list_models,
16};
17use settings::{OpenRouterAvailableModel as AvailableModel, Settings, SettingsStore};
18use std::pin::Pin;
19use std::sync::{Arc, LazyLock};
20use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
21use ui_input::InputField;
22use util::ResultExt;
23
24use crate::provider::util::parse_tool_arguments;
25
26const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("openrouter");
27const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("OpenRouter");
28
29const API_KEY_ENV_VAR_NAME: &str = "OPENROUTER_API_KEY";
30static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
31
32#[derive(Default, Clone, Debug, PartialEq)]
33pub struct OpenRouterSettings {
34 pub api_url: String,
35 pub available_models: Vec<AvailableModel>,
36}
37
38pub struct OpenRouterLanguageModelProvider {
39 http_client: Arc<dyn HttpClient>,
40 state: Entity<State>,
41}
42
43pub struct State {
44 api_key_state: ApiKeyState,
45 http_client: Arc<dyn HttpClient>,
46 available_models: Vec<open_router::Model>,
47 fetch_models_task: Option<Task<Result<(), LanguageModelCompletionError>>>,
48}
49
50impl State {
51 fn is_authenticated(&self) -> bool {
52 self.api_key_state.has_key()
53 }
54
55 fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
56 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
57 self.api_key_state
58 .store(api_url, api_key, |this| &mut this.api_key_state, cx)
59 }
60
61 fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
62 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
63 let task = self
64 .api_key_state
65 .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
66
67 cx.spawn(async move |this, cx| {
68 let result = task.await;
69 this.update(cx, |this, cx| this.restart_fetch_models_task(cx))
70 .ok();
71 result
72 })
73 }
74
75 fn fetch_models(
76 &mut self,
77 cx: &mut Context<Self>,
78 ) -> Task<Result<(), LanguageModelCompletionError>> {
79 let http_client = self.http_client.clone();
80 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
81 let Some(api_key) = self.api_key_state.key(&api_url) else {
82 return Task::ready(Err(LanguageModelCompletionError::NoApiKey {
83 provider: PROVIDER_NAME,
84 }));
85 };
86 cx.spawn(async move |this, cx| {
87 let models = list_models(http_client.as_ref(), &api_url, &api_key)
88 .await
89 .map_err(|e| {
90 LanguageModelCompletionError::Other(anyhow::anyhow!(
91 "OpenRouter error: {:?}",
92 e
93 ))
94 })?;
95
96 this.update(cx, |this, cx| {
97 this.available_models = models;
98 cx.notify();
99 })
100 .map_err(|e| LanguageModelCompletionError::Other(e))?;
101
102 Ok(())
103 })
104 }
105
106 fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
107 if self.is_authenticated() {
108 let task = self.fetch_models(cx);
109 self.fetch_models_task.replace(task);
110 } else {
111 self.available_models = Vec::new();
112 }
113 }
114}
115
116impl OpenRouterLanguageModelProvider {
117 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
118 let state = cx.new(|cx| {
119 cx.observe_global::<SettingsStore>({
120 let mut last_settings = OpenRouterLanguageModelProvider::settings(cx).clone();
121 move |this: &mut State, cx| {
122 let current_settings = OpenRouterLanguageModelProvider::settings(cx);
123 let settings_changed = current_settings != &last_settings;
124 if settings_changed {
125 last_settings = current_settings.clone();
126 this.authenticate(cx).detach();
127 cx.notify();
128 }
129 }
130 })
131 .detach();
132 State {
133 api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
134 http_client: http_client.clone(),
135 available_models: Vec::new(),
136 fetch_models_task: None,
137 }
138 });
139
140 Self { http_client, state }
141 }
142
143 fn settings(cx: &App) -> &OpenRouterSettings {
144 &crate::AllLanguageModelSettings::get_global(cx).open_router
145 }
146
147 fn api_url(cx: &App) -> SharedString {
148 let api_url = &Self::settings(cx).api_url;
149 if api_url.is_empty() {
150 OPEN_ROUTER_API_URL.into()
151 } else {
152 SharedString::new(api_url.as_str())
153 }
154 }
155
156 fn create_language_model(&self, model: open_router::Model) -> Arc<dyn LanguageModel> {
157 Arc::new(OpenRouterLanguageModel {
158 id: LanguageModelId::from(model.id().to_string()),
159 model,
160 state: self.state.clone(),
161 http_client: self.http_client.clone(),
162 request_limiter: RateLimiter::new(4),
163 })
164 }
165}
166
167impl LanguageModelProviderState for OpenRouterLanguageModelProvider {
168 type ObservableEntity = State;
169
170 fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
171 Some(self.state.clone())
172 }
173}
174
175impl LanguageModelProvider for OpenRouterLanguageModelProvider {
176 fn id(&self) -> LanguageModelProviderId {
177 PROVIDER_ID
178 }
179
180 fn name(&self) -> LanguageModelProviderName {
181 PROVIDER_NAME
182 }
183
184 fn icon(&self) -> IconOrSvg {
185 IconOrSvg::Icon(IconName::AiOpenRouter)
186 }
187
188 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
189 Some(self.create_language_model(open_router::Model::default()))
190 }
191
192 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
193 None
194 }
195
196 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
197 let mut models_from_api = self.state.read(cx).available_models.clone();
198 let mut settings_models = Vec::new();
199
200 for model in &Self::settings(cx).available_models {
201 settings_models.push(open_router::Model {
202 name: model.name.clone(),
203 display_name: model.display_name.clone(),
204 max_tokens: model.max_tokens,
205 supports_tools: model.supports_tools,
206 supports_images: model.supports_images,
207 mode: model.mode.unwrap_or_default(),
208 provider: model.provider.clone(),
209 });
210 }
211
212 for settings_model in &settings_models {
213 if let Some(pos) = models_from_api
214 .iter()
215 .position(|m| m.name == settings_model.name)
216 {
217 models_from_api[pos] = settings_model.clone();
218 } else {
219 models_from_api.push(settings_model.clone());
220 }
221 }
222
223 models_from_api
224 .into_iter()
225 .map(|model| self.create_language_model(model))
226 .collect()
227 }
228
229 fn is_authenticated(&self, cx: &App) -> bool {
230 self.state.read(cx).is_authenticated()
231 }
232
233 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
234 self.state.update(cx, |state, cx| state.authenticate(cx))
235 }
236
237 fn configuration_view(
238 &self,
239 _target_agent: language_model::ConfigurationViewTargetAgent,
240 window: &mut Window,
241 cx: &mut App,
242 ) -> AnyView {
243 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
244 .into()
245 }
246
247 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
248 self.state
249 .update(cx, |state, cx| state.set_api_key(None, cx))
250 }
251}
252
253pub struct OpenRouterLanguageModel {
254 id: LanguageModelId,
255 model: open_router::Model,
256 state: Entity<State>,
257 http_client: Arc<dyn HttpClient>,
258 request_limiter: RateLimiter,
259}
260
261impl OpenRouterLanguageModel {
262 fn stream_completion(
263 &self,
264 request: open_router::Request,
265 cx: &AsyncApp,
266 ) -> BoxFuture<
267 'static,
268 Result<
269 futures::stream::BoxStream<
270 'static,
271 Result<ResponseStreamEvent, open_router::OpenRouterError>,
272 >,
273 LanguageModelCompletionError,
274 >,
275 > {
276 let http_client = self.http_client.clone();
277 let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
278 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
279 (state.api_key_state.key(&api_url), api_url)
280 });
281
282 async move {
283 let Some(api_key) = api_key else {
284 return Err(LanguageModelCompletionError::NoApiKey {
285 provider: PROVIDER_NAME,
286 });
287 };
288 let request =
289 open_router::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
290 request.await.map_err(Into::into)
291 }
292 .boxed()
293 }
294}
295
296impl LanguageModel for OpenRouterLanguageModel {
297 fn id(&self) -> LanguageModelId {
298 self.id.clone()
299 }
300
301 fn name(&self) -> LanguageModelName {
302 LanguageModelName::from(self.model.display_name().to_string())
303 }
304
305 fn provider_id(&self) -> LanguageModelProviderId {
306 PROVIDER_ID
307 }
308
309 fn provider_name(&self) -> LanguageModelProviderName {
310 PROVIDER_NAME
311 }
312
313 fn supports_tools(&self) -> bool {
314 self.model.supports_tool_calls()
315 }
316
317 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
318 let model_id = self.model.id().trim().to_lowercase();
319 if model_id.contains("gemini") || model_id.contains("grok") {
320 LanguageModelToolSchemaFormat::JsonSchemaSubset
321 } else {
322 LanguageModelToolSchemaFormat::JsonSchema
323 }
324 }
325
326 fn telemetry_id(&self) -> String {
327 format!("openrouter/{}", self.model.id())
328 }
329
330 fn max_token_count(&self) -> u64 {
331 self.model.max_token_count()
332 }
333
334 fn max_output_tokens(&self) -> Option<u64> {
335 self.model.max_output_tokens()
336 }
337
338 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
339 match choice {
340 LanguageModelToolChoice::Auto => true,
341 LanguageModelToolChoice::Any => true,
342 LanguageModelToolChoice::None => true,
343 }
344 }
345
346 fn supports_images(&self) -> bool {
347 self.model.supports_images.unwrap_or(false)
348 }
349
350 fn count_tokens(
351 &self,
352 request: LanguageModelRequest,
353 cx: &App,
354 ) -> BoxFuture<'static, Result<u64>> {
355 count_open_router_tokens(request, self.model.clone(), cx)
356 }
357
358 fn stream_completion(
359 &self,
360 request: LanguageModelRequest,
361 cx: &AsyncApp,
362 ) -> BoxFuture<
363 'static,
364 Result<
365 futures::stream::BoxStream<
366 'static,
367 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
368 >,
369 LanguageModelCompletionError,
370 >,
371 > {
372 let openrouter_request = into_open_router(request, &self.model, self.max_output_tokens());
373 let request = self.stream_completion(openrouter_request, cx);
374 let future = self.request_limiter.stream(async move {
375 let response = request.await?;
376 Ok(OpenRouterEventMapper::new().map_stream(response))
377 });
378 async move { Ok(future.await?.boxed()) }.boxed()
379 }
380}
381
382pub fn into_open_router(
383 request: LanguageModelRequest,
384 model: &Model,
385 max_output_tokens: Option<u64>,
386) -> open_router::Request {
387 // Anthropic models via OpenRouter don't accept reasoning_details being echoed back
388 // in requests - it's an output-only field for them. However, Gemini models require
389 // the thought signatures to be echoed back for proper reasoning chain continuity.
390 // Note: OpenRouter's model API provides an `architecture.tokenizer` field (e.g. "Claude",
391 // "Gemini") which could replace this ID prefix check, but since this is the only place
392 // we need this distinction, we're just using this less invasive check instead.
393 // If we ever have a more formal distionction between the models in the future,
394 // we should revise this to use that instead.
395 let is_anthropic_model = model.id().starts_with("anthropic/");
396
397 let mut messages = Vec::new();
398 for message in request.messages {
399 let reasoning_details_for_message = if is_anthropic_model {
400 None
401 } else {
402 message.reasoning_details.clone()
403 };
404
405 for content in message.content {
406 match content {
407 MessageContent::Text(text) => add_message_content_part(
408 open_router::MessagePart::Text { text },
409 message.role,
410 &mut messages,
411 reasoning_details_for_message.clone(),
412 ),
413 MessageContent::Thinking { .. } => {}
414 MessageContent::RedactedThinking(_) => {}
415 MessageContent::Image(image) => {
416 add_message_content_part(
417 open_router::MessagePart::Image {
418 image_url: image.to_base64_url(),
419 },
420 message.role,
421 &mut messages,
422 reasoning_details_for_message.clone(),
423 );
424 }
425 MessageContent::ToolUse(tool_use) => {
426 let tool_call = open_router::ToolCall {
427 id: tool_use.id.to_string(),
428 content: open_router::ToolCallContent::Function {
429 function: open_router::FunctionContent {
430 name: tool_use.name.to_string(),
431 arguments: serde_json::to_string(&tool_use.input)
432 .unwrap_or_default(),
433 thought_signature: tool_use.thought_signature.clone(),
434 },
435 },
436 };
437
438 if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
439 messages.last_mut()
440 {
441 tool_calls.push(tool_call);
442 } else {
443 messages.push(open_router::RequestMessage::Assistant {
444 content: None,
445 tool_calls: vec![tool_call],
446 reasoning_details: reasoning_details_for_message.clone(),
447 });
448 }
449 }
450 MessageContent::ToolResult(tool_result) => {
451 let content = match &tool_result.content {
452 LanguageModelToolResultContent::Text(text) => {
453 vec![open_router::MessagePart::Text {
454 text: text.to_string(),
455 }]
456 }
457 LanguageModelToolResultContent::Image(image) => {
458 vec![open_router::MessagePart::Image {
459 image_url: image.to_base64_url(),
460 }]
461 }
462 };
463
464 messages.push(open_router::RequestMessage::Tool {
465 content: content.into(),
466 tool_call_id: tool_result.tool_use_id.to_string(),
467 });
468 }
469 }
470 }
471 }
472
473 open_router::Request {
474 model: model.id().into(),
475 messages,
476 stream: true,
477 stop: request.stop,
478 temperature: request.temperature.unwrap_or(0.4),
479 max_tokens: max_output_tokens,
480 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
481 Some(false)
482 } else {
483 None
484 },
485 usage: open_router::RequestUsage { include: true },
486 reasoning: if request.thinking_allowed
487 && let OpenRouterModelMode::Thinking { budget_tokens } = model.mode
488 {
489 Some(open_router::Reasoning {
490 effort: None,
491 max_tokens: budget_tokens,
492 exclude: Some(false),
493 enabled: Some(true),
494 })
495 } else {
496 None
497 },
498 tools: request
499 .tools
500 .into_iter()
501 .map(|tool| open_router::ToolDefinition::Function {
502 function: open_router::FunctionDefinition {
503 name: tool.name,
504 description: Some(tool.description),
505 parameters: Some(tool.input_schema),
506 },
507 })
508 .collect(),
509 tool_choice: request.tool_choice.map(|choice| match choice {
510 LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
511 LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
512 LanguageModelToolChoice::None => open_router::ToolChoice::None,
513 }),
514 provider: model.provider.clone(),
515 }
516}
517
518fn add_message_content_part(
519 new_part: open_router::MessagePart,
520 role: Role,
521 messages: &mut Vec<open_router::RequestMessage>,
522 reasoning_details: Option<serde_json::Value>,
523) {
524 match (role, messages.last_mut()) {
525 (Role::User, Some(open_router::RequestMessage::User { content }))
526 | (Role::System, Some(open_router::RequestMessage::System { content })) => {
527 content.push_part(new_part);
528 }
529 (
530 Role::Assistant,
531 Some(open_router::RequestMessage::Assistant {
532 content: Some(content),
533 ..
534 }),
535 ) => {
536 content.push_part(new_part);
537 }
538 _ => {
539 messages.push(match role {
540 Role::User => open_router::RequestMessage::User {
541 content: open_router::MessageContent::from(vec![new_part]),
542 },
543 Role::Assistant => open_router::RequestMessage::Assistant {
544 content: Some(open_router::MessageContent::from(vec![new_part])),
545 tool_calls: Vec::new(),
546 reasoning_details,
547 },
548 Role::System => open_router::RequestMessage::System {
549 content: open_router::MessageContent::from(vec![new_part]),
550 },
551 });
552 }
553 }
554}
555
556pub struct OpenRouterEventMapper {
557 tool_calls_by_index: HashMap<usize, RawToolCall>,
558 reasoning_details: Option<serde_json::Value>,
559}
560
561impl OpenRouterEventMapper {
562 pub fn new() -> Self {
563 Self {
564 tool_calls_by_index: HashMap::default(),
565 reasoning_details: None,
566 }
567 }
568
569 pub fn map_stream(
570 mut self,
571 events: Pin<
572 Box<
573 dyn Send + Stream<Item = Result<ResponseStreamEvent, open_router::OpenRouterError>>,
574 >,
575 >,
576 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
577 {
578 events.flat_map(move |event| {
579 futures::stream::iter(match event {
580 Ok(event) => self.map_event(event),
581 Err(error) => vec![Err(error.into())],
582 })
583 })
584 }
585
586 pub fn map_event(
587 &mut self,
588 event: ResponseStreamEvent,
589 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
590 let Some(choice) = event.choices.first() else {
591 return vec![Err(LanguageModelCompletionError::from(anyhow!(
592 "Response contained no choices"
593 )))];
594 };
595
596 let mut events = Vec::new();
597
598 if let Some(details) = choice.delta.reasoning_details.clone() {
599 // Emit reasoning_details immediately
600 events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
601 details.clone(),
602 )));
603 self.reasoning_details = Some(details);
604 }
605
606 if let Some(reasoning) = choice.delta.reasoning.clone() {
607 events.push(Ok(LanguageModelCompletionEvent::Thinking {
608 text: reasoning,
609 signature: None,
610 }));
611 }
612
613 if let Some(content) = choice.delta.content.clone() {
614 // OpenRouter send empty content string with the reasoning content
615 // This is a workaround for the OpenRouter API bug
616 if !content.is_empty() {
617 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
618 }
619 }
620
621 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
622 for tool_call in tool_calls {
623 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
624
625 if let Some(tool_id) = tool_call.id.clone() {
626 entry.id = tool_id;
627 }
628
629 if let Some(function) = tool_call.function.as_ref() {
630 if let Some(name) = function.name.clone() {
631 entry.name = name;
632 }
633
634 if let Some(arguments) = function.arguments.clone() {
635 entry.arguments.push_str(&arguments);
636 }
637
638 if let Some(signature) = function.thought_signature.clone() {
639 entry.thought_signature = Some(signature);
640 }
641 }
642 }
643 }
644
645 if let Some(usage) = event.usage {
646 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
647 input_tokens: usage.prompt_tokens,
648 output_tokens: usage.completion_tokens,
649 cache_creation_input_tokens: 0,
650 cache_read_input_tokens: 0,
651 })));
652 }
653
654 match choice.finish_reason.as_deref() {
655 Some("stop") => {
656 // Don't emit reasoning_details here - already emitted immediately when captured
657 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
658 }
659 Some("tool_calls") => {
660 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
661 match parse_tool_arguments(&tool_call.arguments) {
662 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
663 LanguageModelToolUse {
664 id: tool_call.id.clone().into(),
665 name: tool_call.name.as_str().into(),
666 is_input_complete: true,
667 input,
668 raw_input: tool_call.arguments.clone(),
669 thought_signature: tool_call.thought_signature.clone(),
670 },
671 )),
672 Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
673 id: tool_call.id.clone().into(),
674 tool_name: tool_call.name.as_str().into(),
675 raw_input: tool_call.arguments.clone().into(),
676 json_parse_error: error.to_string(),
677 }),
678 }
679 }));
680
681 // Don't emit reasoning_details here - already emitted immediately when captured
682 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
683 }
684 Some(stop_reason) => {
685 log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
686 // Don't emit reasoning_details here - already emitted immediately when captured
687 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
688 }
689 None => {}
690 }
691
692 events
693 }
694}
695
696#[derive(Default)]
697struct RawToolCall {
698 id: String,
699 name: String,
700 arguments: String,
701 thought_signature: Option<String>,
702}
703
704pub fn count_open_router_tokens(
705 request: LanguageModelRequest,
706 _model: open_router::Model,
707 cx: &App,
708) -> BoxFuture<'static, Result<u64>> {
709 cx.background_spawn(async move {
710 let messages = request
711 .messages
712 .into_iter()
713 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
714 role: match message.role {
715 Role::User => "user".into(),
716 Role::Assistant => "assistant".into(),
717 Role::System => "system".into(),
718 },
719 content: Some(message.string_contents()),
720 name: None,
721 function_call: None,
722 })
723 .collect::<Vec<_>>();
724
725 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
726 })
727 .boxed()
728}
729
730struct ConfigurationView {
731 api_key_editor: Entity<InputField>,
732 state: Entity<State>,
733 load_credentials_task: Option<Task<()>>,
734}
735
736impl ConfigurationView {
737 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
738 let api_key_editor = cx.new(|cx| {
739 InputField::new(
740 window,
741 cx,
742 "sk_or_000000000000000000000000000000000000000000000000",
743 )
744 });
745
746 cx.observe(&state, |_, _, cx| {
747 cx.notify();
748 })
749 .detach();
750
751 let load_credentials_task = Some(cx.spawn_in(window, {
752 let state = state.clone();
753 async move |this, cx| {
754 if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
755 let _ = task.await;
756 }
757
758 this.update(cx, |this, cx| {
759 this.load_credentials_task = None;
760 cx.notify();
761 })
762 .log_err();
763 }
764 }));
765
766 Self {
767 api_key_editor,
768 state,
769 load_credentials_task,
770 }
771 }
772
773 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
774 let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
775 if api_key.is_empty() {
776 return;
777 }
778
779 // url changes can cause the editor to be displayed again
780 self.api_key_editor
781 .update(cx, |editor, cx| editor.set_text("", window, cx));
782
783 let state = self.state.clone();
784 cx.spawn_in(window, async move |_, cx| {
785 state
786 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
787 .await
788 })
789 .detach_and_log_err(cx);
790 }
791
792 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
793 self.api_key_editor
794 .update(cx, |editor, cx| editor.set_text("", window, cx));
795
796 let state = self.state.clone();
797 cx.spawn_in(window, async move |_, cx| {
798 state
799 .update(cx, |state, cx| state.set_api_key(None, cx))
800 .await
801 })
802 .detach_and_log_err(cx);
803 }
804
805 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
806 !self.state.read(cx).is_authenticated()
807 }
808}
809
810impl Render for ConfigurationView {
811 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
812 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
813 let configured_card_label = if env_var_set {
814 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
815 } else {
816 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
817 if api_url == OPEN_ROUTER_API_URL {
818 "API key configured".to_string()
819 } else {
820 format!("API key configured for {}", api_url)
821 }
822 };
823
824 if self.load_credentials_task.is_some() {
825 div()
826 .child(Label::new("Loading credentials..."))
827 .into_any_element()
828 } else if self.should_render_editor(cx) {
829 v_flex()
830 .size_full()
831 .on_action(cx.listener(Self::save_api_key))
832 .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
833 .child(
834 List::new()
835 .child(
836 ListBulletItem::new("")
837 .child(Label::new("Create an API key by visiting"))
838 .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
839 )
840 .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
841 )
842 .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
843 ),
844 )
845 .child(self.api_key_editor.clone())
846 .child(
847 Label::new(
848 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
849 )
850 .size(LabelSize::Small).color(Color::Muted),
851 )
852 .into_any_element()
853 } else {
854 ConfiguredApiCard::new(configured_card_label)
855 .disabled(env_var_set)
856 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
857 .when(env_var_set, |this| {
858 this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
859 })
860 .into_any_element()
861 }
862 }
863}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868
869 use open_router::{ChoiceDelta, FunctionChunk, ResponseMessageDelta, ToolCallChunk};
870
871 #[gpui::test]
872 async fn test_reasoning_details_preservation_with_tool_calls() {
873 // This test verifies that reasoning_details are properly captured and preserved
874 // when a model uses tool calling with reasoning/thinking tokens.
875 //
876 // The key regression this prevents:
877 // - OpenRouter sends multiple reasoning_details updates during streaming
878 // - First with actual content (encrypted reasoning data)
879 // - Then with empty array on completion
880 // - We must NOT overwrite the real data with the empty array
881
882 let mut mapper = OpenRouterEventMapper::new();
883
884 // Simulate the streaming events as they come from OpenRouter/Gemini
885 let events = vec![
886 // Event 1: Initial reasoning details with text
887 ResponseStreamEvent {
888 id: Some("response_123".into()),
889 created: 1234567890,
890 model: "google/gemini-3-pro-preview".into(),
891 choices: vec![ChoiceDelta {
892 index: 0,
893 delta: ResponseMessageDelta {
894 role: None,
895 content: None,
896 reasoning: None,
897 tool_calls: None,
898 reasoning_details: Some(serde_json::json!([
899 {
900 "type": "reasoning.text",
901 "text": "Let me analyze this request...",
902 "format": "google-gemini-v1",
903 "index": 0
904 }
905 ])),
906 },
907 finish_reason: None,
908 }],
909 usage: None,
910 },
911 // Event 2: More reasoning details
912 ResponseStreamEvent {
913 id: Some("response_123".into()),
914 created: 1234567890,
915 model: "google/gemini-3-pro-preview".into(),
916 choices: vec![ChoiceDelta {
917 index: 0,
918 delta: ResponseMessageDelta {
919 role: None,
920 content: None,
921 reasoning: None,
922 tool_calls: None,
923 reasoning_details: Some(serde_json::json!([
924 {
925 "type": "reasoning.encrypted",
926 "data": "EtgDCtUDAdHtim9OF5jm4aeZSBAtl/randomized123",
927 "format": "google-gemini-v1",
928 "index": 0,
929 "id": "tool_call_abc123"
930 }
931 ])),
932 },
933 finish_reason: None,
934 }],
935 usage: None,
936 },
937 // Event 3: Tool call starts
938 ResponseStreamEvent {
939 id: Some("response_123".into()),
940 created: 1234567890,
941 model: "google/gemini-3-pro-preview".into(),
942 choices: vec![ChoiceDelta {
943 index: 0,
944 delta: ResponseMessageDelta {
945 role: None,
946 content: None,
947 reasoning: None,
948 tool_calls: Some(vec![ToolCallChunk {
949 index: 0,
950 id: Some("tool_call_abc123".into()),
951 function: Some(FunctionChunk {
952 name: Some("list_directory".into()),
953 arguments: Some("{\"path\":\"test\"}".into()),
954 thought_signature: Some("sha256:test_signature_xyz789".into()),
955 }),
956 }]),
957 reasoning_details: None,
958 },
959 finish_reason: None,
960 }],
961 usage: None,
962 },
963 // Event 4: Empty reasoning_details on tool_calls finish
964 // This is the critical event - we must not overwrite with this empty array!
965 ResponseStreamEvent {
966 id: Some("response_123".into()),
967 created: 1234567890,
968 model: "google/gemini-3-pro-preview".into(),
969 choices: vec![ChoiceDelta {
970 index: 0,
971 delta: ResponseMessageDelta {
972 role: None,
973 content: None,
974 reasoning: None,
975 tool_calls: None,
976 reasoning_details: Some(serde_json::json!([])),
977 },
978 finish_reason: Some("tool_calls".into()),
979 }],
980 usage: None,
981 },
982 ];
983
984 // Process all events
985 let mut collected_events = Vec::new();
986 for event in events {
987 let mapped = mapper.map_event(event);
988 collected_events.extend(mapped);
989 }
990
991 // Verify we got the expected events
992 let mut has_tool_use = false;
993 let mut reasoning_details_events = Vec::new();
994 let mut thought_signature_value = None;
995
996 for event_result in collected_events {
997 match event_result {
998 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
999 has_tool_use = true;
1000 assert_eq!(tool_use.id.to_string(), "tool_call_abc123");
1001 assert_eq!(tool_use.name.as_ref(), "list_directory");
1002 thought_signature_value = tool_use.thought_signature.clone();
1003 }
1004 Ok(LanguageModelCompletionEvent::ReasoningDetails(details)) => {
1005 reasoning_details_events.push(details);
1006 }
1007 _ => {}
1008 }
1009 }
1010
1011 // Assertions
1012 assert!(has_tool_use, "Should have emitted ToolUse event");
1013 assert!(
1014 !reasoning_details_events.is_empty(),
1015 "Should have emitted ReasoningDetails events"
1016 );
1017
1018 // We should have received multiple reasoning_details events (text, encrypted, empty)
1019 // The agent layer is responsible for keeping only the first non-empty one
1020 assert!(
1021 reasoning_details_events.len() >= 2,
1022 "Should have multiple reasoning_details events from streaming"
1023 );
1024
1025 // Verify at least one contains the encrypted data
1026 let has_encrypted = reasoning_details_events.iter().any(|details| {
1027 if let serde_json::Value::Array(arr) = details {
1028 arr.iter().any(|item| {
1029 item["type"] == "reasoning.encrypted"
1030 && item["data"]
1031 .as_str()
1032 .map_or(false, |s| s.contains("EtgDCtUDAdHtim9OF5jm4aeZSBAtl"))
1033 })
1034 } else {
1035 false
1036 }
1037 });
1038 assert!(
1039 has_encrypted,
1040 "Should have at least one reasoning_details with encrypted data"
1041 );
1042
1043 // Verify thought_signature was captured
1044 assert!(
1045 thought_signature_value.is_some(),
1046 "Tool use should have thought_signature"
1047 );
1048 assert_eq!(
1049 thought_signature_value.unwrap(),
1050 "sha256:test_signature_xyz789"
1051 );
1052 }
1053
1054 #[gpui::test]
1055 async fn test_agent_prevents_empty_reasoning_details_overwrite() {
1056 // This test verifies that the agent layer prevents empty reasoning_details
1057 // from overwriting non-empty ones, even though the mapper emits all events.
1058
1059 // Simulate what the agent does when it receives multiple ReasoningDetails events
1060 let mut agent_reasoning_details: Option<serde_json::Value> = None;
1061
1062 let events = vec![
1063 // First event: non-empty reasoning_details
1064 serde_json::json!([
1065 {
1066 "type": "reasoning.encrypted",
1067 "data": "real_data_here",
1068 "format": "google-gemini-v1"
1069 }
1070 ]),
1071 // Second event: empty array (should not overwrite)
1072 serde_json::json!([]),
1073 ];
1074
1075 for details in events {
1076 // This mimics the agent's logic: only store if we don't already have it
1077 if agent_reasoning_details.is_none() {
1078 agent_reasoning_details = Some(details);
1079 }
1080 }
1081
1082 // Verify the agent kept the first non-empty reasoning_details
1083 assert!(agent_reasoning_details.is_some());
1084 let final_details = agent_reasoning_details.unwrap();
1085 if let serde_json::Value::Array(arr) = &final_details {
1086 assert!(
1087 !arr.is_empty(),
1088 "Agent should have kept the non-empty reasoning_details"
1089 );
1090 assert_eq!(arr[0]["data"], "real_data_here");
1091 } else {
1092 panic!("Expected array");
1093 }
1094 }
1095}