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 supports_thinking(&self) -> bool {
318 matches!(self.model.mode, OpenRouterModelMode::Thinking { .. })
319 }
320
321 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
322 let model_id = self.model.id().trim().to_lowercase();
323 if model_id.contains("gemini") || model_id.contains("grok") {
324 LanguageModelToolSchemaFormat::JsonSchemaSubset
325 } else {
326 LanguageModelToolSchemaFormat::JsonSchema
327 }
328 }
329
330 fn telemetry_id(&self) -> String {
331 format!("openrouter/{}", self.model.id())
332 }
333
334 fn max_token_count(&self) -> u64 {
335 self.model.max_token_count()
336 }
337
338 fn max_output_tokens(&self) -> Option<u64> {
339 self.model.max_output_tokens()
340 }
341
342 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
343 match choice {
344 LanguageModelToolChoice::Auto => true,
345 LanguageModelToolChoice::Any => true,
346 LanguageModelToolChoice::None => true,
347 }
348 }
349
350 fn supports_images(&self) -> bool {
351 self.model.supports_images.unwrap_or(false)
352 }
353
354 fn count_tokens(
355 &self,
356 request: LanguageModelRequest,
357 cx: &App,
358 ) -> BoxFuture<'static, Result<u64>> {
359 count_open_router_tokens(request, self.model.clone(), cx)
360 }
361
362 fn stream_completion(
363 &self,
364 request: LanguageModelRequest,
365 cx: &AsyncApp,
366 ) -> BoxFuture<
367 'static,
368 Result<
369 futures::stream::BoxStream<
370 'static,
371 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
372 >,
373 LanguageModelCompletionError,
374 >,
375 > {
376 let openrouter_request = into_open_router(request, &self.model, self.max_output_tokens());
377 let request = self.stream_completion(openrouter_request, cx);
378 let future = self.request_limiter.stream(async move {
379 let response = request.await?;
380 Ok(OpenRouterEventMapper::new().map_stream(response))
381 });
382 async move { Ok(future.await?.boxed()) }.boxed()
383 }
384}
385
386pub fn into_open_router(
387 request: LanguageModelRequest,
388 model: &Model,
389 max_output_tokens: Option<u64>,
390) -> open_router::Request {
391 // Anthropic models via OpenRouter don't accept reasoning_details being echoed back
392 // in requests - it's an output-only field for them. However, Gemini models require
393 // the thought signatures to be echoed back for proper reasoning chain continuity.
394 // Note: OpenRouter's model API provides an `architecture.tokenizer` field (e.g. "Claude",
395 // "Gemini") which could replace this ID prefix check, but since this is the only place
396 // we need this distinction, we're just using this less invasive check instead.
397 // If we ever have a more formal distionction between the models in the future,
398 // we should revise this to use that instead.
399 let is_anthropic_model = model.id().starts_with("anthropic/");
400
401 let mut messages = Vec::new();
402 for message in request.messages {
403 let reasoning_details_for_message = if is_anthropic_model {
404 None
405 } else {
406 message.reasoning_details.clone()
407 };
408
409 for content in message.content {
410 match content {
411 MessageContent::Text(text) => add_message_content_part(
412 open_router::MessagePart::Text { text },
413 message.role,
414 &mut messages,
415 reasoning_details_for_message.clone(),
416 ),
417 MessageContent::Thinking { .. } => {}
418 MessageContent::RedactedThinking(_) => {}
419 MessageContent::Image(image) => {
420 add_message_content_part(
421 open_router::MessagePart::Image {
422 image_url: image.to_base64_url(),
423 },
424 message.role,
425 &mut messages,
426 reasoning_details_for_message.clone(),
427 );
428 }
429 MessageContent::ToolUse(tool_use) => {
430 let tool_call = open_router::ToolCall {
431 id: tool_use.id.to_string(),
432 content: open_router::ToolCallContent::Function {
433 function: open_router::FunctionContent {
434 name: tool_use.name.to_string(),
435 arguments: serde_json::to_string(&tool_use.input)
436 .unwrap_or_default(),
437 thought_signature: tool_use.thought_signature.clone(),
438 },
439 },
440 };
441
442 if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
443 messages.last_mut()
444 {
445 tool_calls.push(tool_call);
446 } else {
447 messages.push(open_router::RequestMessage::Assistant {
448 content: None,
449 tool_calls: vec![tool_call],
450 reasoning_details: reasoning_details_for_message.clone(),
451 });
452 }
453 }
454 MessageContent::ToolResult(tool_result) => {
455 let content = match &tool_result.content {
456 LanguageModelToolResultContent::Text(text) => {
457 vec![open_router::MessagePart::Text {
458 text: text.to_string(),
459 }]
460 }
461 LanguageModelToolResultContent::Image(image) => {
462 vec![open_router::MessagePart::Image {
463 image_url: image.to_base64_url(),
464 }]
465 }
466 };
467
468 messages.push(open_router::RequestMessage::Tool {
469 content: content.into(),
470 tool_call_id: tool_result.tool_use_id.to_string(),
471 });
472 }
473 }
474 }
475 }
476
477 open_router::Request {
478 model: model.id().into(),
479 messages,
480 stream: true,
481 stop: request.stop,
482 temperature: request.temperature.unwrap_or(0.4),
483 max_tokens: max_output_tokens,
484 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
485 Some(false)
486 } else {
487 None
488 },
489 usage: open_router::RequestUsage { include: true },
490 reasoning: if request.thinking_allowed
491 && let OpenRouterModelMode::Thinking { budget_tokens } = model.mode
492 {
493 Some(open_router::Reasoning {
494 effort: None,
495 max_tokens: budget_tokens,
496 exclude: Some(false),
497 enabled: Some(true),
498 })
499 } else {
500 None
501 },
502 tools: request
503 .tools
504 .into_iter()
505 .map(|tool| open_router::ToolDefinition::Function {
506 function: open_router::FunctionDefinition {
507 name: tool.name,
508 description: Some(tool.description),
509 parameters: Some(tool.input_schema),
510 },
511 })
512 .collect(),
513 tool_choice: request.tool_choice.map(|choice| match choice {
514 LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
515 LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
516 LanguageModelToolChoice::None => open_router::ToolChoice::None,
517 }),
518 provider: model.provider.clone(),
519 }
520}
521
522fn add_message_content_part(
523 new_part: open_router::MessagePart,
524 role: Role,
525 messages: &mut Vec<open_router::RequestMessage>,
526 reasoning_details: Option<serde_json::Value>,
527) {
528 match (role, messages.last_mut()) {
529 (Role::User, Some(open_router::RequestMessage::User { content }))
530 | (Role::System, Some(open_router::RequestMessage::System { content })) => {
531 content.push_part(new_part);
532 }
533 (
534 Role::Assistant,
535 Some(open_router::RequestMessage::Assistant {
536 content: Some(content),
537 ..
538 }),
539 ) => {
540 content.push_part(new_part);
541 }
542 _ => {
543 messages.push(match role {
544 Role::User => open_router::RequestMessage::User {
545 content: open_router::MessageContent::from(vec![new_part]),
546 },
547 Role::Assistant => open_router::RequestMessage::Assistant {
548 content: Some(open_router::MessageContent::from(vec![new_part])),
549 tool_calls: Vec::new(),
550 reasoning_details,
551 },
552 Role::System => open_router::RequestMessage::System {
553 content: open_router::MessageContent::from(vec![new_part]),
554 },
555 });
556 }
557 }
558}
559
560pub struct OpenRouterEventMapper {
561 tool_calls_by_index: HashMap<usize, RawToolCall>,
562 reasoning_details: Option<serde_json::Value>,
563}
564
565impl OpenRouterEventMapper {
566 pub fn new() -> Self {
567 Self {
568 tool_calls_by_index: HashMap::default(),
569 reasoning_details: None,
570 }
571 }
572
573 pub fn map_stream(
574 mut self,
575 events: Pin<
576 Box<
577 dyn Send + Stream<Item = Result<ResponseStreamEvent, open_router::OpenRouterError>>,
578 >,
579 >,
580 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
581 {
582 events.flat_map(move |event| {
583 futures::stream::iter(match event {
584 Ok(event) => self.map_event(event),
585 Err(error) => vec![Err(error.into())],
586 })
587 })
588 }
589
590 pub fn map_event(
591 &mut self,
592 event: ResponseStreamEvent,
593 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
594 let Some(choice) = event.choices.first() else {
595 return vec![Err(LanguageModelCompletionError::from(anyhow!(
596 "Response contained no choices"
597 )))];
598 };
599
600 let mut events = Vec::new();
601
602 if let Some(details) = choice.delta.reasoning_details.clone() {
603 // Emit reasoning_details immediately
604 events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
605 details.clone(),
606 )));
607 self.reasoning_details = Some(details);
608 }
609
610 if let Some(reasoning) = choice.delta.reasoning.clone() {
611 events.push(Ok(LanguageModelCompletionEvent::Thinking {
612 text: reasoning,
613 signature: None,
614 }));
615 }
616
617 if let Some(content) = choice.delta.content.clone() {
618 // OpenRouter send empty content string with the reasoning content
619 // This is a workaround for the OpenRouter API bug
620 if !content.is_empty() {
621 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
622 }
623 }
624
625 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
626 for tool_call in tool_calls {
627 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
628
629 if let Some(tool_id) = tool_call.id.clone() {
630 entry.id = tool_id;
631 }
632
633 if let Some(function) = tool_call.function.as_ref() {
634 if let Some(name) = function.name.clone() {
635 entry.name = name;
636 }
637
638 if let Some(arguments) = function.arguments.clone() {
639 entry.arguments.push_str(&arguments);
640 }
641
642 if let Some(signature) = function.thought_signature.clone() {
643 entry.thought_signature = Some(signature);
644 }
645 }
646 }
647 }
648
649 if let Some(usage) = event.usage {
650 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
651 input_tokens: usage.prompt_tokens,
652 output_tokens: usage.completion_tokens,
653 cache_creation_input_tokens: 0,
654 cache_read_input_tokens: 0,
655 })));
656 }
657
658 match choice.finish_reason.as_deref() {
659 Some("stop") => {
660 // Don't emit reasoning_details here - already emitted immediately when captured
661 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
662 }
663 Some("tool_calls") => {
664 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
665 match parse_tool_arguments(&tool_call.arguments) {
666 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
667 LanguageModelToolUse {
668 id: tool_call.id.clone().into(),
669 name: tool_call.name.as_str().into(),
670 is_input_complete: true,
671 input,
672 raw_input: tool_call.arguments.clone(),
673 thought_signature: tool_call.thought_signature.clone(),
674 },
675 )),
676 Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
677 id: tool_call.id.clone().into(),
678 tool_name: tool_call.name.as_str().into(),
679 raw_input: tool_call.arguments.clone().into(),
680 json_parse_error: error.to_string(),
681 }),
682 }
683 }));
684
685 // Don't emit reasoning_details here - already emitted immediately when captured
686 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
687 }
688 Some(stop_reason) => {
689 log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
690 // Don't emit reasoning_details here - already emitted immediately when captured
691 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
692 }
693 None => {}
694 }
695
696 events
697 }
698}
699
700#[derive(Default)]
701struct RawToolCall {
702 id: String,
703 name: String,
704 arguments: String,
705 thought_signature: Option<String>,
706}
707
708pub fn count_open_router_tokens(
709 request: LanguageModelRequest,
710 _model: open_router::Model,
711 cx: &App,
712) -> BoxFuture<'static, Result<u64>> {
713 cx.background_spawn(async move {
714 let messages = request
715 .messages
716 .into_iter()
717 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
718 role: match message.role {
719 Role::User => "user".into(),
720 Role::Assistant => "assistant".into(),
721 Role::System => "system".into(),
722 },
723 content: Some(message.string_contents()),
724 name: None,
725 function_call: None,
726 })
727 .collect::<Vec<_>>();
728
729 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
730 })
731 .boxed()
732}
733
734struct ConfigurationView {
735 api_key_editor: Entity<InputField>,
736 state: Entity<State>,
737 load_credentials_task: Option<Task<()>>,
738}
739
740impl ConfigurationView {
741 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
742 let api_key_editor = cx.new(|cx| {
743 InputField::new(
744 window,
745 cx,
746 "sk_or_000000000000000000000000000000000000000000000000",
747 )
748 });
749
750 cx.observe(&state, |_, _, cx| {
751 cx.notify();
752 })
753 .detach();
754
755 let load_credentials_task = Some(cx.spawn_in(window, {
756 let state = state.clone();
757 async move |this, cx| {
758 if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
759 let _ = task.await;
760 }
761
762 this.update(cx, |this, cx| {
763 this.load_credentials_task = None;
764 cx.notify();
765 })
766 .log_err();
767 }
768 }));
769
770 Self {
771 api_key_editor,
772 state,
773 load_credentials_task,
774 }
775 }
776
777 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
778 let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
779 if api_key.is_empty() {
780 return;
781 }
782
783 // url changes can cause the editor to be displayed again
784 self.api_key_editor
785 .update(cx, |editor, cx| editor.set_text("", window, cx));
786
787 let state = self.state.clone();
788 cx.spawn_in(window, async move |_, cx| {
789 state
790 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
791 .await
792 })
793 .detach_and_log_err(cx);
794 }
795
796 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
797 self.api_key_editor
798 .update(cx, |editor, cx| editor.set_text("", window, cx));
799
800 let state = self.state.clone();
801 cx.spawn_in(window, async move |_, cx| {
802 state
803 .update(cx, |state, cx| state.set_api_key(None, cx))
804 .await
805 })
806 .detach_and_log_err(cx);
807 }
808
809 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
810 !self.state.read(cx).is_authenticated()
811 }
812}
813
814impl Render for ConfigurationView {
815 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
816 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
817 let configured_card_label = if env_var_set {
818 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
819 } else {
820 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
821 if api_url == OPEN_ROUTER_API_URL {
822 "API key configured".to_string()
823 } else {
824 format!("API key configured for {}", api_url)
825 }
826 };
827
828 if self.load_credentials_task.is_some() {
829 div()
830 .child(Label::new("Loading credentials..."))
831 .into_any_element()
832 } else if self.should_render_editor(cx) {
833 v_flex()
834 .size_full()
835 .on_action(cx.listener(Self::save_api_key))
836 .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
837 .child(
838 List::new()
839 .child(
840 ListBulletItem::new("")
841 .child(Label::new("Create an API key by visiting"))
842 .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
843 )
844 .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
845 )
846 .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
847 ),
848 )
849 .child(self.api_key_editor.clone())
850 .child(
851 Label::new(
852 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
853 )
854 .size(LabelSize::Small).color(Color::Muted),
855 )
856 .into_any_element()
857 } else {
858 ConfiguredApiCard::new(configured_card_label)
859 .disabled(env_var_set)
860 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
861 .when(env_var_set, |this| {
862 this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
863 })
864 .into_any_element()
865 }
866 }
867}
868
869#[cfg(test)]
870mod tests {
871 use super::*;
872
873 use open_router::{ChoiceDelta, FunctionChunk, ResponseMessageDelta, ToolCallChunk};
874
875 #[gpui::test]
876 async fn test_reasoning_details_preservation_with_tool_calls() {
877 // This test verifies that reasoning_details are properly captured and preserved
878 // when a model uses tool calling with reasoning/thinking tokens.
879 //
880 // The key regression this prevents:
881 // - OpenRouter sends multiple reasoning_details updates during streaming
882 // - First with actual content (encrypted reasoning data)
883 // - Then with empty array on completion
884 // - We must NOT overwrite the real data with the empty array
885
886 let mut mapper = OpenRouterEventMapper::new();
887
888 // Simulate the streaming events as they come from OpenRouter/Gemini
889 let events = vec![
890 // Event 1: Initial reasoning details with text
891 ResponseStreamEvent {
892 id: Some("response_123".into()),
893 created: 1234567890,
894 model: "google/gemini-3-pro-preview".into(),
895 choices: vec![ChoiceDelta {
896 index: 0,
897 delta: ResponseMessageDelta {
898 role: None,
899 content: None,
900 reasoning: None,
901 tool_calls: None,
902 reasoning_details: Some(serde_json::json!([
903 {
904 "type": "reasoning.text",
905 "text": "Let me analyze this request...",
906 "format": "google-gemini-v1",
907 "index": 0
908 }
909 ])),
910 },
911 finish_reason: None,
912 }],
913 usage: None,
914 },
915 // Event 2: More reasoning details
916 ResponseStreamEvent {
917 id: Some("response_123".into()),
918 created: 1234567890,
919 model: "google/gemini-3-pro-preview".into(),
920 choices: vec![ChoiceDelta {
921 index: 0,
922 delta: ResponseMessageDelta {
923 role: None,
924 content: None,
925 reasoning: None,
926 tool_calls: None,
927 reasoning_details: Some(serde_json::json!([
928 {
929 "type": "reasoning.encrypted",
930 "data": "EtgDCtUDAdHtim9OF5jm4aeZSBAtl/randomized123",
931 "format": "google-gemini-v1",
932 "index": 0,
933 "id": "tool_call_abc123"
934 }
935 ])),
936 },
937 finish_reason: None,
938 }],
939 usage: None,
940 },
941 // Event 3: Tool call starts
942 ResponseStreamEvent {
943 id: Some("response_123".into()),
944 created: 1234567890,
945 model: "google/gemini-3-pro-preview".into(),
946 choices: vec![ChoiceDelta {
947 index: 0,
948 delta: ResponseMessageDelta {
949 role: None,
950 content: None,
951 reasoning: None,
952 tool_calls: Some(vec![ToolCallChunk {
953 index: 0,
954 id: Some("tool_call_abc123".into()),
955 function: Some(FunctionChunk {
956 name: Some("list_directory".into()),
957 arguments: Some("{\"path\":\"test\"}".into()),
958 thought_signature: Some("sha256:test_signature_xyz789".into()),
959 }),
960 }]),
961 reasoning_details: None,
962 },
963 finish_reason: None,
964 }],
965 usage: None,
966 },
967 // Event 4: Empty reasoning_details on tool_calls finish
968 // This is the critical event - we must not overwrite with this empty array!
969 ResponseStreamEvent {
970 id: Some("response_123".into()),
971 created: 1234567890,
972 model: "google/gemini-3-pro-preview".into(),
973 choices: vec![ChoiceDelta {
974 index: 0,
975 delta: ResponseMessageDelta {
976 role: None,
977 content: None,
978 reasoning: None,
979 tool_calls: None,
980 reasoning_details: Some(serde_json::json!([])),
981 },
982 finish_reason: Some("tool_calls".into()),
983 }],
984 usage: None,
985 },
986 ];
987
988 // Process all events
989 let mut collected_events = Vec::new();
990 for event in events {
991 let mapped = mapper.map_event(event);
992 collected_events.extend(mapped);
993 }
994
995 // Verify we got the expected events
996 let mut has_tool_use = false;
997 let mut reasoning_details_events = Vec::new();
998 let mut thought_signature_value = None;
999
1000 for event_result in collected_events {
1001 match event_result {
1002 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1003 has_tool_use = true;
1004 assert_eq!(tool_use.id.to_string(), "tool_call_abc123");
1005 assert_eq!(tool_use.name.as_ref(), "list_directory");
1006 thought_signature_value = tool_use.thought_signature.clone();
1007 }
1008 Ok(LanguageModelCompletionEvent::ReasoningDetails(details)) => {
1009 reasoning_details_events.push(details);
1010 }
1011 _ => {}
1012 }
1013 }
1014
1015 // Assertions
1016 assert!(has_tool_use, "Should have emitted ToolUse event");
1017 assert!(
1018 !reasoning_details_events.is_empty(),
1019 "Should have emitted ReasoningDetails events"
1020 );
1021
1022 // We should have received multiple reasoning_details events (text, encrypted, empty)
1023 // The agent layer is responsible for keeping only the first non-empty one
1024 assert!(
1025 reasoning_details_events.len() >= 2,
1026 "Should have multiple reasoning_details events from streaming"
1027 );
1028
1029 // Verify at least one contains the encrypted data
1030 let has_encrypted = reasoning_details_events.iter().any(|details| {
1031 if let serde_json::Value::Array(arr) = details {
1032 arr.iter().any(|item| {
1033 item["type"] == "reasoning.encrypted"
1034 && item["data"]
1035 .as_str()
1036 .map_or(false, |s| s.contains("EtgDCtUDAdHtim9OF5jm4aeZSBAtl"))
1037 })
1038 } else {
1039 false
1040 }
1041 });
1042 assert!(
1043 has_encrypted,
1044 "Should have at least one reasoning_details with encrypted data"
1045 );
1046
1047 // Verify thought_signature was captured
1048 assert!(
1049 thought_signature_value.is_some(),
1050 "Tool use should have thought_signature"
1051 );
1052 assert_eq!(
1053 thought_signature_value.unwrap(),
1054 "sha256:test_signature_xyz789"
1055 );
1056 }
1057
1058 #[gpui::test]
1059 async fn test_agent_prevents_empty_reasoning_details_overwrite() {
1060 // This test verifies that the agent layer prevents empty reasoning_details
1061 // from overwriting non-empty ones, even though the mapper emits all events.
1062
1063 // Simulate what the agent does when it receives multiple ReasoningDetails events
1064 let mut agent_reasoning_details: Option<serde_json::Value> = None;
1065
1066 let events = vec![
1067 // First event: non-empty reasoning_details
1068 serde_json::json!([
1069 {
1070 "type": "reasoning.encrypted",
1071 "data": "real_data_here",
1072 "format": "google-gemini-v1"
1073 }
1074 ]),
1075 // Second event: empty array (should not overwrite)
1076 serde_json::json!([]),
1077 ];
1078
1079 for details in events {
1080 // This mimics the agent's logic: only store if we don't already have it
1081 if agent_reasoning_details.is_none() {
1082 agent_reasoning_details = Some(details);
1083 }
1084 }
1085
1086 // Verify the agent kept the first non-empty reasoning_details
1087 assert!(agent_reasoning_details.is_some());
1088 let final_details = agent_reasoning_details.unwrap();
1089 if let serde_json::Value::Array(arr) = &final_details {
1090 assert!(
1091 !arr.is_empty(),
1092 "Agent should have kept the non-empty reasoning_details"
1093 );
1094 assert_eq!(arr[0]["data"], "real_data_here");
1095 } else {
1096 panic!("Expected array");
1097 }
1098 }
1099}