1use anyhow::{Result, anyhow};
2use collections::HashMap;
3use futures::{FutureExt, Stream, StreamExt, future, 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::str::FromStr as _;
20use std::sync::{Arc, LazyLock};
21use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
22use ui_input::InputField;
23use util::ResultExt;
24
25const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("openrouter");
26const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("OpenRouter");
27
28const API_KEY_ENV_VAR_NAME: &str = "OPENROUTER_API_KEY";
29static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
30
31#[derive(Default, Clone, Debug, PartialEq)]
32pub struct OpenRouterSettings {
33 pub api_url: String,
34 pub available_models: Vec<AvailableModel>,
35}
36
37pub struct OpenRouterLanguageModelProvider {
38 http_client: Arc<dyn HttpClient>,
39 state: Entity<State>,
40}
41
42pub struct State {
43 api_key_state: ApiKeyState,
44 http_client: Arc<dyn HttpClient>,
45 available_models: Vec<open_router::Model>,
46 fetch_models_task: Option<Task<Result<(), LanguageModelCompletionError>>>,
47}
48
49impl State {
50 fn is_authenticated(&self) -> bool {
51 self.api_key_state.has_key()
52 }
53
54 fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
55 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
56 self.api_key_state
57 .store(api_url, api_key, |this| &mut this.api_key_state, cx)
58 }
59
60 fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
61 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
62 let task = self
63 .api_key_state
64 .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
65
66 cx.spawn(async move |this, cx| {
67 let result = task.await;
68 this.update(cx, |this, cx| this.restart_fetch_models_task(cx))
69 .ok();
70 result
71 })
72 }
73
74 fn fetch_models(
75 &mut self,
76 cx: &mut Context<Self>,
77 ) -> Task<Result<(), LanguageModelCompletionError>> {
78 let http_client = self.http_client.clone();
79 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
80 let Some(api_key) = self.api_key_state.key(&api_url) else {
81 return Task::ready(Err(LanguageModelCompletionError::NoApiKey {
82 provider: PROVIDER_NAME,
83 }));
84 };
85 cx.spawn(async move |this, cx| {
86 let models = list_models(http_client.as_ref(), &api_url, &api_key)
87 .await
88 .map_err(|e| {
89 LanguageModelCompletionError::Other(anyhow::anyhow!(
90 "OpenRouter error: {:?}",
91 e
92 ))
93 })?;
94
95 this.update(cx, |this, cx| {
96 this.available_models = models;
97 cx.notify();
98 })
99 .map_err(|e| LanguageModelCompletionError::Other(e))?;
100
101 Ok(())
102 })
103 }
104
105 fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
106 if self.is_authenticated() {
107 let task = self.fetch_models(cx);
108 self.fetch_models_task.replace(task);
109 } else {
110 self.available_models = Vec::new();
111 }
112 }
113}
114
115impl OpenRouterLanguageModelProvider {
116 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
117 let state = cx.new(|cx| {
118 cx.observe_global::<SettingsStore>({
119 let mut last_settings = OpenRouterLanguageModelProvider::settings(cx).clone();
120 move |this: &mut State, cx| {
121 let current_settings = OpenRouterLanguageModelProvider::settings(cx);
122 let settings_changed = current_settings != &last_settings;
123 if settings_changed {
124 last_settings = current_settings.clone();
125 this.authenticate(cx).detach();
126 cx.notify();
127 }
128 }
129 })
130 .detach();
131 State {
132 api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
133 http_client: http_client.clone(),
134 available_models: Vec::new(),
135 fetch_models_task: None,
136 }
137 });
138
139 Self { http_client, state }
140 }
141
142 fn settings(cx: &App) -> &OpenRouterSettings {
143 &crate::AllLanguageModelSettings::get_global(cx).open_router
144 }
145
146 fn api_url(cx: &App) -> SharedString {
147 let api_url = &Self::settings(cx).api_url;
148 if api_url.is_empty() {
149 OPEN_ROUTER_API_URL.into()
150 } else {
151 SharedString::new(api_url.as_str())
152 }
153 }
154
155 fn create_language_model(&self, model: open_router::Model) -> Arc<dyn LanguageModel> {
156 Arc::new(OpenRouterLanguageModel {
157 id: LanguageModelId::from(model.id().to_string()),
158 model,
159 state: self.state.clone(),
160 http_client: self.http_client.clone(),
161 request_limiter: RateLimiter::new(4),
162 })
163 }
164}
165
166impl LanguageModelProviderState for OpenRouterLanguageModelProvider {
167 type ObservableEntity = State;
168
169 fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
170 Some(self.state.clone())
171 }
172}
173
174impl LanguageModelProvider for OpenRouterLanguageModelProvider {
175 fn id(&self) -> LanguageModelProviderId {
176 PROVIDER_ID
177 }
178
179 fn name(&self) -> LanguageModelProviderName {
180 PROVIDER_NAME
181 }
182
183 fn icon(&self) -> IconOrSvg {
184 IconOrSvg::Icon(IconName::AiOpenRouter)
185 }
186
187 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
188 Some(self.create_language_model(open_router::Model::default()))
189 }
190
191 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
192 Some(self.create_language_model(open_router::Model::default_fast()))
193 }
194
195 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
196 let mut models_from_api = self.state.read(cx).available_models.clone();
197 let mut settings_models = Vec::new();
198
199 for model in &Self::settings(cx).available_models {
200 settings_models.push(open_router::Model {
201 name: model.name.clone(),
202 display_name: model.display_name.clone(),
203 max_tokens: model.max_tokens,
204 supports_tools: model.supports_tools,
205 supports_images: model.supports_images,
206 mode: model.mode.unwrap_or_default(),
207 provider: model.provider.clone(),
208 });
209 }
210
211 for settings_model in &settings_models {
212 if let Some(pos) = models_from_api
213 .iter()
214 .position(|m| m.name == settings_model.name)
215 {
216 models_from_api[pos] = settings_model.clone();
217 } else {
218 models_from_api.push(settings_model.clone());
219 }
220 }
221
222 models_from_api
223 .into_iter()
224 .map(|model| self.create_language_model(model))
225 .collect()
226 }
227
228 fn is_authenticated(&self, cx: &App) -> bool {
229 self.state.read(cx).is_authenticated()
230 }
231
232 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
233 self.state.update(cx, |state, cx| state.authenticate(cx))
234 }
235
236 fn configuration_view(
237 &self,
238 _target_agent: language_model::ConfigurationViewTargetAgent,
239 window: &mut Window,
240 cx: &mut App,
241 ) -> AnyView {
242 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
243 .into()
244 }
245
246 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
247 self.state
248 .update(cx, |state, cx| state.set_api_key(None, cx))
249 }
250}
251
252pub struct OpenRouterLanguageModel {
253 id: LanguageModelId,
254 model: open_router::Model,
255 state: Entity<State>,
256 http_client: Arc<dyn HttpClient>,
257 request_limiter: RateLimiter,
258}
259
260impl OpenRouterLanguageModel {
261 fn stream_completion(
262 &self,
263 request: open_router::Request,
264 cx: &AsyncApp,
265 ) -> BoxFuture<
266 'static,
267 Result<
268 futures::stream::BoxStream<
269 'static,
270 Result<ResponseStreamEvent, open_router::OpenRouterError>,
271 >,
272 LanguageModelCompletionError,
273 >,
274 > {
275 let http_client = self.http_client.clone();
276 let Ok((api_key, api_url)) = self.state.read_with(cx, |state, cx| {
277 let api_url = OpenRouterLanguageModelProvider::api_url(cx);
278 (state.api_key_state.key(&api_url), api_url)
279 }) else {
280 return future::ready(Err(anyhow!("App state dropped").into())).boxed();
281 };
282
283 async move {
284 let Some(api_key) = api_key else {
285 return Err(LanguageModelCompletionError::NoApiKey {
286 provider: PROVIDER_NAME,
287 });
288 };
289 let request =
290 open_router::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
291 request.await.map_err(Into::into)
292 }
293 .boxed()
294 }
295}
296
297impl LanguageModel for OpenRouterLanguageModel {
298 fn id(&self) -> LanguageModelId {
299 self.id.clone()
300 }
301
302 fn name(&self) -> LanguageModelName {
303 LanguageModelName::from(self.model.display_name().to_string())
304 }
305
306 fn provider_id(&self) -> LanguageModelProviderId {
307 PROVIDER_ID
308 }
309
310 fn provider_name(&self) -> LanguageModelProviderName {
311 PROVIDER_NAME
312 }
313
314 fn supports_tools(&self) -> bool {
315 self.model.supports_tool_calls()
316 }
317
318 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
319 let model_id = self.model.id().trim().to_lowercase();
320 if model_id.contains("gemini") || model_id.contains("grok") {
321 LanguageModelToolSchemaFormat::JsonSchemaSubset
322 } else {
323 LanguageModelToolSchemaFormat::JsonSchema
324 }
325 }
326
327 fn telemetry_id(&self) -> String {
328 format!("openrouter/{}", self.model.id())
329 }
330
331 fn max_token_count(&self) -> u64 {
332 self.model.max_token_count()
333 }
334
335 fn max_output_tokens(&self) -> Option<u64> {
336 self.model.max_output_tokens()
337 }
338
339 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
340 match choice {
341 LanguageModelToolChoice::Auto => true,
342 LanguageModelToolChoice::Any => true,
343 LanguageModelToolChoice::None => true,
344 }
345 }
346
347 fn supports_images(&self) -> bool {
348 self.model.supports_images.unwrap_or(false)
349 }
350
351 fn count_tokens(
352 &self,
353 request: LanguageModelRequest,
354 cx: &App,
355 ) -> BoxFuture<'static, Result<u64>> {
356 count_open_router_tokens(request, self.model.clone(), cx)
357 }
358
359 fn stream_completion(
360 &self,
361 request: LanguageModelRequest,
362 cx: &AsyncApp,
363 ) -> BoxFuture<
364 'static,
365 Result<
366 futures::stream::BoxStream<
367 'static,
368 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
369 >,
370 LanguageModelCompletionError,
371 >,
372 > {
373 let openrouter_request = into_open_router(request, &self.model, self.max_output_tokens());
374 let request = self.stream_completion(openrouter_request, cx);
375 let future = self.request_limiter.stream(async move {
376 let response = request.await?;
377 Ok(OpenRouterEventMapper::new().map_stream(response))
378 });
379 async move { Ok(future.await?.boxed()) }.boxed()
380 }
381}
382
383pub fn into_open_router(
384 request: LanguageModelRequest,
385 model: &Model,
386 max_output_tokens: Option<u64>,
387) -> open_router::Request {
388 // Anthropic models via OpenRouter don't accept reasoning_details being echoed back
389 // in requests - it's an output-only field for them. However, Gemini models require
390 // the thought signatures to be echoed back for proper reasoning chain continuity.
391 // Note: OpenRouter's model API provides an `architecture.tokenizer` field (e.g. "Claude",
392 // "Gemini") which could replace this ID prefix check, but since this is the only place
393 // we need this distinction, we're just using this less invasive check instead.
394 // If we ever have a more formal distionction between the models in the future,
395 // we should revise this to use that instead.
396 let is_anthropic_model = model.id().starts_with("anthropic/");
397
398 let mut messages = Vec::new();
399 for message in request.messages {
400 let reasoning_details_for_message = if is_anthropic_model {
401 None
402 } else {
403 message.reasoning_details.clone()
404 };
405
406 for content in message.content {
407 match content {
408 MessageContent::Text(text) => add_message_content_part(
409 open_router::MessagePart::Text { text },
410 message.role,
411 &mut messages,
412 reasoning_details_for_message.clone(),
413 ),
414 MessageContent::Thinking { .. } => {}
415 MessageContent::RedactedThinking(_) => {}
416 MessageContent::Image(image) => {
417 add_message_content_part(
418 open_router::MessagePart::Image {
419 image_url: image.to_base64_url(),
420 },
421 message.role,
422 &mut messages,
423 reasoning_details_for_message.clone(),
424 );
425 }
426 MessageContent::ToolUse(tool_use) => {
427 let tool_call = open_router::ToolCall {
428 id: tool_use.id.to_string(),
429 content: open_router::ToolCallContent::Function {
430 function: open_router::FunctionContent {
431 name: tool_use.name.to_string(),
432 arguments: serde_json::to_string(&tool_use.input)
433 .unwrap_or_default(),
434 thought_signature: tool_use.thought_signature.clone(),
435 },
436 },
437 };
438
439 if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
440 messages.last_mut()
441 {
442 tool_calls.push(tool_call);
443 } else {
444 messages.push(open_router::RequestMessage::Assistant {
445 content: None,
446 tool_calls: vec![tool_call],
447 reasoning_details: reasoning_details_for_message.clone(),
448 });
449 }
450 }
451 MessageContent::ToolResult(tool_result) => {
452 let content = match &tool_result.content {
453 LanguageModelToolResultContent::Text(text) => {
454 vec![open_router::MessagePart::Text {
455 text: text.to_string(),
456 }]
457 }
458 LanguageModelToolResultContent::Image(image) => {
459 vec![open_router::MessagePart::Image {
460 image_url: image.to_base64_url(),
461 }]
462 }
463 };
464
465 messages.push(open_router::RequestMessage::Tool {
466 content: content.into(),
467 tool_call_id: tool_result.tool_use_id.to_string(),
468 });
469 }
470 }
471 }
472 }
473
474 open_router::Request {
475 model: model.id().into(),
476 messages,
477 stream: true,
478 stop: request.stop,
479 temperature: request.temperature.unwrap_or(0.4),
480 max_tokens: max_output_tokens,
481 parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
482 Some(false)
483 } else {
484 None
485 },
486 usage: open_router::RequestUsage { include: true },
487 reasoning: if request.thinking_allowed
488 && let OpenRouterModelMode::Thinking { budget_tokens } = model.mode
489 {
490 Some(open_router::Reasoning {
491 effort: None,
492 max_tokens: budget_tokens,
493 exclude: Some(false),
494 enabled: Some(true),
495 })
496 } else {
497 None
498 },
499 tools: request
500 .tools
501 .into_iter()
502 .map(|tool| open_router::ToolDefinition::Function {
503 function: open_router::FunctionDefinition {
504 name: tool.name,
505 description: Some(tool.description),
506 parameters: Some(tool.input_schema),
507 },
508 })
509 .collect(),
510 tool_choice: request.tool_choice.map(|choice| match choice {
511 LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
512 LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
513 LanguageModelToolChoice::None => open_router::ToolChoice::None,
514 }),
515 provider: model.provider.clone(),
516 }
517}
518
519fn add_message_content_part(
520 new_part: open_router::MessagePart,
521 role: Role,
522 messages: &mut Vec<open_router::RequestMessage>,
523 reasoning_details: Option<serde_json::Value>,
524) {
525 match (role, messages.last_mut()) {
526 (Role::User, Some(open_router::RequestMessage::User { content }))
527 | (Role::System, Some(open_router::RequestMessage::System { content })) => {
528 content.push_part(new_part);
529 }
530 (
531 Role::Assistant,
532 Some(open_router::RequestMessage::Assistant {
533 content: Some(content),
534 ..
535 }),
536 ) => {
537 content.push_part(new_part);
538 }
539 _ => {
540 messages.push(match role {
541 Role::User => open_router::RequestMessage::User {
542 content: open_router::MessageContent::from(vec![new_part]),
543 },
544 Role::Assistant => open_router::RequestMessage::Assistant {
545 content: Some(open_router::MessageContent::from(vec![new_part])),
546 tool_calls: Vec::new(),
547 reasoning_details,
548 },
549 Role::System => open_router::RequestMessage::System {
550 content: open_router::MessageContent::from(vec![new_part]),
551 },
552 });
553 }
554 }
555}
556
557pub struct OpenRouterEventMapper {
558 tool_calls_by_index: HashMap<usize, RawToolCall>,
559 reasoning_details: Option<serde_json::Value>,
560}
561
562impl OpenRouterEventMapper {
563 pub fn new() -> Self {
564 Self {
565 tool_calls_by_index: HashMap::default(),
566 reasoning_details: None,
567 }
568 }
569
570 pub fn map_stream(
571 mut self,
572 events: Pin<
573 Box<
574 dyn Send + Stream<Item = Result<ResponseStreamEvent, open_router::OpenRouterError>>,
575 >,
576 >,
577 ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
578 {
579 events.flat_map(move |event| {
580 futures::stream::iter(match event {
581 Ok(event) => self.map_event(event),
582 Err(error) => vec![Err(error.into())],
583 })
584 })
585 }
586
587 pub fn map_event(
588 &mut self,
589 event: ResponseStreamEvent,
590 ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
591 let Some(choice) = event.choices.first() else {
592 return vec![Err(LanguageModelCompletionError::from(anyhow!(
593 "Response contained no choices"
594 )))];
595 };
596
597 let mut events = Vec::new();
598
599 if let Some(details) = choice.delta.reasoning_details.clone() {
600 // Emit reasoning_details immediately
601 events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
602 details.clone(),
603 )));
604 self.reasoning_details = Some(details);
605 }
606
607 if let Some(reasoning) = choice.delta.reasoning.clone() {
608 events.push(Ok(LanguageModelCompletionEvent::Thinking {
609 text: reasoning,
610 signature: None,
611 }));
612 }
613
614 if let Some(content) = choice.delta.content.clone() {
615 // OpenRouter send empty content string with the reasoning content
616 // This is a workaround for the OpenRouter API bug
617 if !content.is_empty() {
618 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
619 }
620 }
621
622 if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
623 for tool_call in tool_calls {
624 let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
625
626 if let Some(tool_id) = tool_call.id.clone() {
627 entry.id = tool_id;
628 }
629
630 if let Some(function) = tool_call.function.as_ref() {
631 if let Some(name) = function.name.clone() {
632 entry.name = name;
633 }
634
635 if let Some(arguments) = function.arguments.clone() {
636 entry.arguments.push_str(&arguments);
637 }
638
639 if let Some(signature) = function.thought_signature.clone() {
640 entry.thought_signature = Some(signature);
641 }
642 }
643 }
644 }
645
646 if let Some(usage) = event.usage {
647 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
648 input_tokens: usage.prompt_tokens,
649 output_tokens: usage.completion_tokens,
650 cache_creation_input_tokens: 0,
651 cache_read_input_tokens: 0,
652 })));
653 }
654
655 match choice.finish_reason.as_deref() {
656 Some("stop") => {
657 // Don't emit reasoning_details here - already emitted immediately when captured
658 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
659 }
660 Some("tool_calls") => {
661 events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
662 match serde_json::Value::from_str(&tool_call.arguments) {
663 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
664 LanguageModelToolUse {
665 id: tool_call.id.clone().into(),
666 name: tool_call.name.as_str().into(),
667 is_input_complete: true,
668 input,
669 raw_input: tool_call.arguments.clone(),
670 thought_signature: tool_call.thought_signature.clone(),
671 },
672 )),
673 Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
674 id: tool_call.id.clone().into(),
675 tool_name: tool_call.name.as_str().into(),
676 raw_input: tool_call.arguments.clone().into(),
677 json_parse_error: error.to_string(),
678 }),
679 }
680 }));
681
682 // Don't emit reasoning_details here - already emitted immediately when captured
683 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
684 }
685 Some(stop_reason) => {
686 log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
687 // Don't emit reasoning_details here - already emitted immediately when captured
688 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
689 }
690 None => {}
691 }
692
693 events
694 }
695}
696
697#[derive(Default)]
698struct RawToolCall {
699 id: String,
700 name: String,
701 arguments: String,
702 thought_signature: Option<String>,
703}
704
705pub fn count_open_router_tokens(
706 request: LanguageModelRequest,
707 _model: open_router::Model,
708 cx: &App,
709) -> BoxFuture<'static, Result<u64>> {
710 cx.background_spawn(async move {
711 let messages = request
712 .messages
713 .into_iter()
714 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
715 role: match message.role {
716 Role::User => "user".into(),
717 Role::Assistant => "assistant".into(),
718 Role::System => "system".into(),
719 },
720 content: Some(message.string_contents()),
721 name: None,
722 function_call: None,
723 })
724 .collect::<Vec<_>>();
725
726 tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
727 })
728 .boxed()
729}
730
731struct ConfigurationView {
732 api_key_editor: Entity<InputField>,
733 state: Entity<State>,
734 load_credentials_task: Option<Task<()>>,
735}
736
737impl ConfigurationView {
738 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
739 let api_key_editor = cx.new(|cx| {
740 InputField::new(
741 window,
742 cx,
743 "sk_or_000000000000000000000000000000000000000000000000",
744 )
745 });
746
747 cx.observe(&state, |_, _, cx| {
748 cx.notify();
749 })
750 .detach();
751
752 let load_credentials_task = Some(cx.spawn_in(window, {
753 let state = state.clone();
754 async move |this, cx| {
755 if let Some(task) = state
756 .update(cx, |state, cx| state.authenticate(cx))
757 .log_err()
758 {
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 assign 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}