1use anyhow::Result;
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 mut events = Vec::new();
595
596 if let Some(usage) = event.usage {
597 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
598 input_tokens: usage.prompt_tokens,
599 output_tokens: usage.completion_tokens,
600 cache_creation_input_tokens: 0,
601 cache_read_input_tokens: 0,
602 })));
603 }
604
605 let Some(choice) = event.choices.first() else {
606 return events;
607 };
608
609 if let Some(details) = choice.delta.reasoning_details.clone() {
610 // Emit reasoning_details immediately
611 events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
612 details.clone(),
613 )));
614 self.reasoning_details = Some(details);
615 }
616
617 if let Some(reasoning) = choice.delta.reasoning.clone() {
618 events.push(Ok(LanguageModelCompletionEvent::Thinking {
619 text: reasoning,
620 signature: None,
621 }));
622 }
623
624 if let Some(content) = choice.delta.content.clone() {
625 // OpenRouter send empty content string with the reasoning content
626 // This is a workaround for the OpenRouter API bug
627 if !content.is_empty() {
628 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
629 }
630 }
631
632 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
633 for tool_call in tool_calls {
634 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
635
636 if let Some(tool_id) = tool_call.id.clone() {
637 entry.id = tool_id;
638 }
639
640 if let Some(function) = tool_call.function.as_ref() {
641 if let Some(name) = function.name.clone() {
642 entry.name = name;
643 }
644
645 if let Some(arguments) = function.arguments.clone() {
646 entry.arguments.push_str(&arguments);
647 }
648
649 if let Some(signature) = function.thought_signature.clone() {
650 entry.thought_signature = Some(signature);
651 }
652 }
653 }
654 }
655
656 match choice.finish_reason.as_deref() {
657 Some("stop") => {
658 // Don't emit reasoning_details here - already emitted immediately when captured
659 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
660 }
661 Some("tool_calls") => {
662 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
663 match parse_tool_arguments(&tool_call.arguments) {
664 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
665 LanguageModelToolUse {
666 id: tool_call.id.clone().into(),
667 name: tool_call.name.as_str().into(),
668 is_input_complete: true,
669 input,
670 raw_input: tool_call.arguments.clone(),
671 thought_signature: tool_call.thought_signature.clone(),
672 },
673 )),
674 Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
675 id: tool_call.id.clone().into(),
676 tool_name: tool_call.name.as_str().into(),
677 raw_input: tool_call.arguments.clone().into(),
678 json_parse_error: error.to_string(),
679 }),
680 }
681 }));
682
683 // Don't emit reasoning_details here - already emitted immediately when captured
684 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
685 }
686 Some(stop_reason) => {
687 log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
688 // Don't emit reasoning_details here - already emitted immediately when captured
689 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
690 }
691 None => {}
692 }
693
694 events
695 }
696}
697
698#[derive(Default)]
699struct RawToolCall {
700 id: String,
701 name: String,
702 arguments: String,
703 thought_signature: Option<String>,
704}
705
706pub fn count_open_router_tokens(
707 request: LanguageModelRequest,
708 _model: open_router::Model,
709 cx: &App,
710) -> BoxFuture<'static, Result<u64>> {
711 cx.background_spawn(async move {
712 let messages = request
713 .messages
714 .into_iter()
715 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
716 role: match message.role {
717 Role::User => "user".into(),
718 Role::Assistant => "assistant".into(),
719 Role::System => "system".into(),
720 },
721 content: Some(message.string_contents()),
722 name: None,
723 function_call: None,
724 })
725 .collect::<Vec<_>>();
726
727 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
728 })
729 .boxed()
730}
731
732struct ConfigurationView {
733 api_key_editor: Entity<InputField>,
734 state: Entity<State>,
735 load_credentials_task: Option<Task<()>>,
736}
737
738impl ConfigurationView {
739 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
740 let api_key_editor = cx.new(|cx| {
741 InputField::new(
742 window,
743 cx,
744 "sk_or_000000000000000000000000000000000000000000000000",
745 )
746 });
747
748 cx.observe(&state, |_, _, cx| {
749 cx.notify();
750 })
751 .detach();
752
753 let load_credentials_task = Some(cx.spawn_in(window, {
754 let state = state.clone();
755 async move |this, cx| {
756 if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
757 let _ = task.await;
758 }
759
760 this.update(cx, |this, cx| {
761 this.load_credentials_task = None;
762 cx.notify();
763 })
764 .log_err();
765 }
766 }));
767
768 Self {
769 api_key_editor,
770 state,
771 load_credentials_task,
772 }
773 }
774
775 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
776 let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
777 if api_key.is_empty() {
778 return;
779 }
780
781 // url changes can cause the editor to be displayed again
782 self.api_key_editor
783 .update(cx, |editor, cx| editor.set_text("", window, cx));
784
785 let state = self.state.clone();
786 cx.spawn_in(window, async move |_, cx| {
787 state
788 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
789 .await
790 })
791 .detach_and_log_err(cx);
792 }
793
794 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
795 self.api_key_editor
796 .update(cx, |editor, cx| editor.set_text("", window, cx));
797
798 let state = self.state.clone();
799 cx.spawn_in(window, async move |_, cx| {
800 state
801 .update(cx, |state, cx| state.set_api_key(None, cx))
802 .await
803 })
804 .detach_and_log_err(cx);
805 }
806
807 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
808 !self.state.read(cx).is_authenticated()
809 }
810}
811
812impl Render for ConfigurationView {
813 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
814 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
815 let configured_card_label = if env_var_set {
816 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
817 } else {
818 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
819 if api_url == OPEN_ROUTER_API_URL {
820 "API key configured".to_string()
821 } else {
822 format!("API key configured for {}", api_url)
823 }
824 };
825
826 if self.load_credentials_task.is_some() {
827 div()
828 .child(Label::new("Loading credentials..."))
829 .into_any_element()
830 } else if self.should_render_editor(cx) {
831 v_flex()
832 .size_full()
833 .on_action(cx.listener(Self::save_api_key))
834 .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
835 .child(
836 List::new()
837 .child(
838 ListBulletItem::new("")
839 .child(Label::new("Create an API key by visiting"))
840 .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
841 )
842 .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
843 )
844 .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
845 ),
846 )
847 .child(self.api_key_editor.clone())
848 .child(
849 Label::new(
850 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
851 )
852 .size(LabelSize::Small).color(Color::Muted),
853 )
854 .into_any_element()
855 } else {
856 ConfiguredApiCard::new(configured_card_label)
857 .disabled(env_var_set)
858 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
859 .when(env_var_set, |this| {
860 this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
861 })
862 .into_any_element()
863 }
864 }
865}
866
867#[cfg(test)]
868mod tests {
869 use super::*;
870
871 use open_router::{ChoiceDelta, FunctionChunk, ResponseMessageDelta, ToolCallChunk};
872
873 #[gpui::test]
874 async fn test_reasoning_details_preservation_with_tool_calls() {
875 // This test verifies that reasoning_details are properly captured and preserved
876 // when a model uses tool calling with reasoning/thinking tokens.
877 //
878 // The key regression this prevents:
879 // - OpenRouter sends multiple reasoning_details updates during streaming
880 // - First with actual content (encrypted reasoning data)
881 // - Then with empty array on completion
882 // - We must NOT overwrite the real data with the empty array
883
884 let mut mapper = OpenRouterEventMapper::new();
885
886 // Simulate the streaming events as they come from OpenRouter/Gemini
887 let events = vec![
888 // Event 1: Initial reasoning details with text
889 ResponseStreamEvent {
890 id: Some("response_123".into()),
891 created: 1234567890,
892 model: "google/gemini-3-pro-preview".into(),
893 choices: vec![ChoiceDelta {
894 index: 0,
895 delta: ResponseMessageDelta {
896 role: None,
897 content: None,
898 reasoning: None,
899 tool_calls: None,
900 reasoning_details: Some(serde_json::json!([
901 {
902 "type": "reasoning.text",
903 "text": "Let me analyze this request...",
904 "format": "google-gemini-v1",
905 "index": 0
906 }
907 ])),
908 },
909 finish_reason: None,
910 }],
911 usage: None,
912 },
913 // Event 2: More reasoning details
914 ResponseStreamEvent {
915 id: Some("response_123".into()),
916 created: 1234567890,
917 model: "google/gemini-3-pro-preview".into(),
918 choices: vec![ChoiceDelta {
919 index: 0,
920 delta: ResponseMessageDelta {
921 role: None,
922 content: None,
923 reasoning: None,
924 tool_calls: None,
925 reasoning_details: Some(serde_json::json!([
926 {
927 "type": "reasoning.encrypted",
928 "data": "EtgDCtUDAdHtim9OF5jm4aeZSBAtl/randomized123",
929 "format": "google-gemini-v1",
930 "index": 0,
931 "id": "tool_call_abc123"
932 }
933 ])),
934 },
935 finish_reason: None,
936 }],
937 usage: None,
938 },
939 // Event 3: Tool call starts
940 ResponseStreamEvent {
941 id: Some("response_123".into()),
942 created: 1234567890,
943 model: "google/gemini-3-pro-preview".into(),
944 choices: vec![ChoiceDelta {
945 index: 0,
946 delta: ResponseMessageDelta {
947 role: None,
948 content: None,
949 reasoning: None,
950 tool_calls: Some(vec![ToolCallChunk {
951 index: 0,
952 id: Some("tool_call_abc123".into()),
953 function: Some(FunctionChunk {
954 name: Some("list_directory".into()),
955 arguments: Some("{\"path\":\"test\"}".into()),
956 thought_signature: Some("sha256:test_signature_xyz789".into()),
957 }),
958 }]),
959 reasoning_details: None,
960 },
961 finish_reason: None,
962 }],
963 usage: None,
964 },
965 // Event 4: Empty reasoning_details on tool_calls finish
966 // This is the critical event - we must not overwrite with this empty array!
967 ResponseStreamEvent {
968 id: Some("response_123".into()),
969 created: 1234567890,
970 model: "google/gemini-3-pro-preview".into(),
971 choices: vec![ChoiceDelta {
972 index: 0,
973 delta: ResponseMessageDelta {
974 role: None,
975 content: None,
976 reasoning: None,
977 tool_calls: None,
978 reasoning_details: Some(serde_json::json!([])),
979 },
980 finish_reason: Some("tool_calls".into()),
981 }],
982 usage: None,
983 },
984 ];
985
986 // Process all events
987 let mut collected_events = Vec::new();
988 for event in events {
989 let mapped = mapper.map_event(event);
990 collected_events.extend(mapped);
991 }
992
993 // Verify we got the expected events
994 let mut has_tool_use = false;
995 let mut reasoning_details_events = Vec::new();
996 let mut thought_signature_value = None;
997
998 for event_result in collected_events {
999 match event_result {
1000 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1001 has_tool_use = true;
1002 assert_eq!(tool_use.id.to_string(), "tool_call_abc123");
1003 assert_eq!(tool_use.name.as_ref(), "list_directory");
1004 thought_signature_value = tool_use.thought_signature.clone();
1005 }
1006 Ok(LanguageModelCompletionEvent::ReasoningDetails(details)) => {
1007 reasoning_details_events.push(details);
1008 }
1009 _ => {}
1010 }
1011 }
1012
1013 // Assertions
1014 assert!(has_tool_use, "Should have emitted ToolUse event");
1015 assert!(
1016 !reasoning_details_events.is_empty(),
1017 "Should have emitted ReasoningDetails events"
1018 );
1019
1020 // We should have received multiple reasoning_details events (text, encrypted, empty)
1021 // The agent layer is responsible for keeping only the first non-empty one
1022 assert!(
1023 reasoning_details_events.len() >= 2,
1024 "Should have multiple reasoning_details events from streaming"
1025 );
1026
1027 // Verify at least one contains the encrypted data
1028 let has_encrypted = reasoning_details_events.iter().any(|details| {
1029 if let serde_json::Value::Array(arr) = details {
1030 arr.iter().any(|item| {
1031 item["type"] == "reasoning.encrypted"
1032 && item["data"]
1033 .as_str()
1034 .map_or(false, |s| s.contains("EtgDCtUDAdHtim9OF5jm4aeZSBAtl"))
1035 })
1036 } else {
1037 false
1038 }
1039 });
1040 assert!(
1041 has_encrypted,
1042 "Should have at least one reasoning_details with encrypted data"
1043 );
1044
1045 // Verify thought_signature was captured
1046 assert!(
1047 thought_signature_value.is_some(),
1048 "Tool use should have thought_signature"
1049 );
1050 assert_eq!(
1051 thought_signature_value.unwrap(),
1052 "sha256:test_signature_xyz789"
1053 );
1054 }
1055
1056 #[gpui::test]
1057 async fn test_usage_only_chunk_with_empty_choices_does_not_error() {
1058 let mut mapper = OpenRouterEventMapper::new();
1059
1060 let events = mapper.map_event(ResponseStreamEvent {
1061 id: Some("response_123".into()),
1062 created: 1234567890,
1063 model: "google/gemini-3-flash-preview".into(),
1064 choices: Vec::new(),
1065 usage: Some(open_router::Usage {
1066 prompt_tokens: 12,
1067 completion_tokens: 7,
1068 total_tokens: 19,
1069 }),
1070 });
1071
1072 assert_eq!(events.len(), 1);
1073 match events.into_iter().next().unwrap() {
1074 Ok(LanguageModelCompletionEvent::UsageUpdate(usage)) => {
1075 assert_eq!(usage.input_tokens, 12);
1076 assert_eq!(usage.output_tokens, 7);
1077 }
1078 other => panic!("Expected usage update event, got: {other:?}"),
1079 }
1080 }
1081
1082 #[gpui::test]
1083 async fn test_agent_prevents_empty_reasoning_details_overwrite() {
1084 // This test verifies that the agent layer prevents empty reasoning_details
1085 // from overwriting non-empty ones, even though the mapper emits all events.
1086
1087 // Simulate what the agent does when it receives multiple ReasoningDetails events
1088 let mut agent_reasoning_details: Option<serde_json::Value> = None;
1089
1090 let events = vec![
1091 // First event: non-empty reasoning_details
1092 serde_json::json!([
1093 {
1094 "type": "reasoning.encrypted",
1095 "data": "real_data_here",
1096 "format": "google-gemini-v1"
1097 }
1098 ]),
1099 // Second event: empty array (should not overwrite)
1100 serde_json::json!([]),
1101 ];
1102
1103 for details in events {
1104 // This mimics the agent's logic: only store if we don't already have it
1105 if agent_reasoning_details.is_none() {
1106 agent_reasoning_details = Some(details);
1107 }
1108 }
1109
1110 // Verify the agent kept the first non-empty reasoning_details
1111 assert!(agent_reasoning_details.is_some());
1112 let final_details = agent_reasoning_details.unwrap();
1113 if let serde_json::Value::Array(arr) = &final_details {
1114 assert!(
1115 !arr.is_empty(),
1116 "Agent should have kept the non-empty reasoning_details"
1117 );
1118 assert_eq!(arr[0]["data"], "real_data_here");
1119 } else {
1120 panic!("Expected array");
1121 }
1122 }
1123}