1#![allow(missing_docs)]
3
4use super::OPENROUTER_EXTENSION_NAMESPACE;
5use super::chat::{
6 OpenRouterChatMessageContent, OpenRouterChatRequest, OpenRouterChatResponse,
7 OpenRouterChatToolCall, OpenRouterFunctionDescription, OpenRouterImageConfig, OpenRouterPlugin,
8 OpenRouterProviderPreferences, OpenRouterReasoningConfig, OpenRouterResponseFormat,
9 OpenRouterTool, OpenRouterToolChoice,
10};
11use super::client::OpenRouterClient;
12use super::config::OpenRouterApiMode;
13use super::convert_chat::{
14 adk_contents_to_chat_messages, augment_chat_plugins_for_contents,
15 chat_message_reasoning_to_parts,
16};
17use super::convert_responses::{
18 adk_contents_to_response_input, responses_reasoning_items_to_parts,
19};
20use super::metadata::{
21 chat_response_citation_metadata, chat_response_provider_metadata, chat_usage_to_metadata,
22 responses_citation_metadata, responses_provider_metadata, responses_usage_to_metadata,
23};
24use super::responses::{
25 OpenRouterResponse, OpenRouterResponseOutputItem, OpenRouterResponseTextConfig,
26 OpenRouterResponseTool, OpenRouterResponsesRequest,
27};
28use crate::retry::{execute_with_retry, is_retryable_model_error};
29use adk_core::{
30 AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, GenerateContentConfig, Llm,
31 LlmRequest, LlmResponse, LlmResponseStream, Part, Result,
32};
33use async_stream::try_stream;
34use async_trait::async_trait;
35use futures::StreamExt;
36use serde::{Deserialize, Serialize};
37use serde_json::{Map, Value, json};
38use std::collections::BTreeMap;
39
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
62pub struct OpenRouterRequestOptions {
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub api_mode: Option<OpenRouterApiMode>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub models: Option<Vec<String>>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub route: Option<String>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub plugins: Option<Vec<OpenRouterPlugin>>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub response_tools: Option<Vec<OpenRouterResponseTool>>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub provider: Option<OpenRouterProviderPreferences>,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub reasoning: Option<OpenRouterReasoningConfig>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub reasoning_content: Option<String>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub reasoning_details: Option<Value>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub previous_response_id: Option<String>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub prompt_cache_key: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub modalities: Option<Vec<String>>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub include: Option<Vec<String>>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub image_config: Option<OpenRouterImageConfig>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub metadata: Option<Value>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub instructions: Option<String>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub session_id: Option<String>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub trace: Option<Value>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub user: Option<String>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub tool_choice: Option<OpenRouterToolChoice>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub parallel_tool_calls: Option<bool>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub response_text: Option<OpenRouterResponseTextConfig>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub response_format: Option<OpenRouterResponseFormat>,
109 #[serde(default, flatten)]
110 pub extra: BTreeMap<String, Value>,
111}
112
113impl OpenRouterRequestOptions {
114 #[must_use]
116 pub fn with_api_mode(mut self, api_mode: OpenRouterApiMode) -> Self {
117 self.api_mode = Some(api_mode);
118 self
119 }
120
121 #[must_use]
123 pub fn with_models(mut self, models: Vec<String>) -> Self {
124 self.models = Some(models);
125 self
126 }
127
128 #[must_use]
130 pub fn with_route(mut self, route: impl Into<String>) -> Self {
131 self.route = Some(route.into());
132 self
133 }
134
135 #[must_use]
137 pub fn with_plugin(mut self, plugin: OpenRouterPlugin) -> Self {
138 self.plugins.get_or_insert_with(Vec::new).push(plugin);
139 self
140 }
141
142 #[must_use]
144 pub fn with_response_tool(mut self, tool: OpenRouterResponseTool) -> Self {
145 self.response_tools.get_or_insert_with(Vec::new).push(tool);
146 self
147 }
148
149 #[must_use]
151 pub fn with_provider_preferences(mut self, provider: OpenRouterProviderPreferences) -> Self {
152 self.provider = Some(provider);
153 self
154 }
155
156 #[must_use]
158 pub fn with_reasoning(mut self, reasoning: OpenRouterReasoningConfig) -> Self {
159 self.reasoning = Some(reasoning);
160 self
161 }
162
163 #[must_use]
165 pub fn with_previous_response_id(mut self, previous_response_id: impl Into<String>) -> Self {
166 self.previous_response_id = Some(previous_response_id.into());
167 self
168 }
169
170 #[must_use]
172 pub fn with_prompt_cache_key(mut self, prompt_cache_key: impl Into<String>) -> Self {
173 self.prompt_cache_key = Some(prompt_cache_key.into());
174 self
175 }
176
177 #[must_use]
179 pub fn with_modalities(mut self, modalities: Vec<String>) -> Self {
180 self.modalities = Some(modalities);
181 self
182 }
183
184 #[must_use]
186 pub fn with_include(mut self, include: Vec<String>) -> Self {
187 self.include = Some(include);
188 self
189 }
190
191 pub fn to_extension_value(&self) -> Result<Value> {
193 serde_json::to_value(self).map_err(|err| {
194 AdkError::new(
195 ErrorComponent::Model,
196 ErrorCategory::Internal,
197 "model.openrouter.request_options_serialize_failed",
198 "Failed to serialize OpenRouter request options",
199 )
200 .with_provider("openrouter")
201 .with_source(err)
202 })
203 }
204
205 pub fn from_extension_value(value: &Value) -> Result<Self> {
207 serde_json::from_value(value.clone()).map_err(|err| {
208 AdkError::new(
209 ErrorComponent::Model,
210 ErrorCategory::InvalidInput,
211 "model.openrouter.invalid_request_options",
212 "OpenRouter extension options are not valid JSON for OpenRouterRequestOptions",
213 )
214 .with_provider("openrouter")
215 .with_source(err)
216 })
217 }
218
219 pub fn from_generate_config(config: Option<&GenerateContentConfig>) -> Result<Option<Self>> {
221 config
222 .and_then(|config| config.extensions.get(OPENROUTER_EXTENSION_NAMESPACE))
223 .map(Self::from_extension_value)
224 .transpose()
225 }
226
227 pub fn insert_into_config(&self, config: &mut GenerateContentConfig) -> Result<()> {
229 config
230 .extensions
231 .insert(OPENROUTER_EXTENSION_NAMESPACE.to_string(), self.to_extension_value()?);
232 Ok(())
233 }
234}
235
236#[async_trait]
237impl Llm for OpenRouterClient {
238 fn name(&self) -> &str {
239 self.model()
240 }
241
242 fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
244 vec![adk_core::DataDestination::of_url("openrouter", self.config().effective_base_url())]
245 }
246
247 #[tracing::instrument(
248 name = "model.generate_content",
249 skip_all,
250 fields(
251 model.name = %self.name(),
252 stream = %stream,
253 request.contents_count = %request.contents.len(),
254 request.tools_count = %request.tools.len()
255 )
256 )]
257 async fn generate_content(
258 &self,
259 mut request: LlmRequest,
260 stream: bool,
261 ) -> Result<LlmResponseStream> {
262 let request_options =
263 OpenRouterRequestOptions::from_generate_config(request.config.as_ref())?
264 .unwrap_or_default();
265 let model_name = effective_model_name(self, &request);
266 adk_core::history::retain_replayable(
268 &mut request.contents,
269 &adk_core::history::ProviderOrigin::new("openrouter", &model_name),
270 );
271 let api_mode = request_options.api_mode.unwrap_or(self.config().default_api_mode);
272 let usage_span =
273 crate::telemetry::inference_span("openrouter", &model_name, stream, &request);
274
275 let response_stream = match api_mode {
276 OpenRouterApiMode::ChatCompletions => {
277 build_chat_llm_stream(self, request, &request_options, stream).await?
278 }
279 OpenRouterApiMode::Responses => {
280 build_responses_llm_stream(self, request, &request_options, stream).await?
281 }
282 };
283
284 Ok(crate::usage_tracking::with_priced_usage_tracking(
285 response_stream,
286 usage_span,
287 "openrouter",
288 model_name,
289 ))
290 }
291}
292
293async fn build_chat_llm_stream(
294 client: &OpenRouterClient,
295 request: LlmRequest,
296 request_options: &OpenRouterRequestOptions,
297 stream: bool,
298) -> Result<LlmResponseStream> {
299 let native_request = build_chat_request(client, &request, request_options, stream)?;
300
301 if stream {
302 let native_request_for_retry = native_request.clone();
303 let native_stream =
304 execute_with_retry(client.retry_config(), is_retryable_model_error, || {
305 let native_request = native_request_for_retry.clone();
306 async move { client.send_chat_stream(native_request).await }
307 })
308 .await?;
309
310 let response_stream = try_stream! {
311 let mut native_stream = native_stream;
312 let mut state = ChatStreamState::default();
313 let mut final_parts = Vec::new();
314 let mut final_finish_reason = None;
315 let mut final_usage_metadata = None;
316 let mut logprobs = Vec::new();
318 let mut finished = false;
321 let mut refused = false;
323
324 while let Some(item) = native_stream.next().await {
325 match item? {
326 super::stream::OpenRouterChatStreamItem::Chunk(chunk) => {
327 if let Some(usage_metadata) = chunk.usage.as_ref().map(chat_usage_to_metadata) {
328 final_usage_metadata = Some(usage_metadata);
329 }
330
331 if let Some(choice) = chunk.choices.first() {
332 logprobs.extend(
333 choice
334 .logprobs
335 .as_ref()
336 .and_then(|logprobs| logprobs.get("content"))
337 .and_then(Value::as_array)
338 .into_iter()
339 .flatten()
340 .cloned(),
341 );
342 if let Some(delta) = choice.delta.as_ref() {
343 let (reasoning_parts, reasoning_metadata) =
344 chat_message_reasoning_to_parts(delta);
345 if let Some(response) = llm_stream_response(
346 reasoning_parts,
347 None,
348 None,
349 reasoning_metadata,
350 true,
351 false,
352 ) {
353 yield response;
354 }
355
356 let mut text_parts = chat_content_to_parts(delta.content.as_ref());
357 if let Some(refusal) = delta.refusal.as_ref().filter(|r| !r.is_empty()) {
358 refused = true;
359 text_parts.push(Part::Text { text: refusal.clone() });
360 }
361 if let Some(response) = llm_stream_response(
362 text_parts,
363 None,
364 None,
365 None,
366 true,
367 false,
368 ) {
369 yield response;
370 }
371
372 if let Some(tool_calls) = delta.tool_calls.as_ref() {
373 state.capture_chat_tool_calls(tool_calls);
374 }
375 }
376
377 if let Some(finish_reason) = choice.finish_reason.as_deref() {
378 if finish_reason == "error" {
379 Err(crate::stream_error::reported(
380 "openrouter",
381 "model.openrouter.stream_error",
382 &Value::Null,
383 ))?;
384 }
385 final_parts.extend(state.drain_chat_tool_calls()?);
386 final_finish_reason =
387 Some(chat_finish_reason(choice, finish_reason, refused));
388 finished = true;
389 }
390 }
391 }
392 super::stream::OpenRouterChatStreamItem::Done => {
393 if state.has_pending_tool_calls() {
394 Err(chat_stream_incomplete("its tool calls finished"))?;
395 }
396 finished = true;
397 if let Some(response) = llm_stream_response(
398 std::mem::take(&mut final_parts),
399 final_usage_metadata.take(),
400 final_finish_reason.take(),
401 logprobs_metadata(std::mem::take(&mut logprobs)),
402 false,
403 true,
404 ) {
405 yield response;
406 }
407 }
408 super::stream::OpenRouterChatStreamItem::Error(_) => unreachable!(),
409 }
410 }
411
412 if !finished {
413 Err(chat_stream_incomplete(if state.has_pending_tool_calls() {
414 "its tool calls finished"
415 } else {
416 "the response finished"
417 }))?;
418 }
419
420 if let Some(response) = llm_stream_response(
421 final_parts,
422 final_usage_metadata,
423 final_finish_reason,
424 logprobs_metadata(logprobs),
425 false,
426 true,
427 ) {
428 yield response;
429 }
430 };
431
432 Ok(Box::pin(response_stream))
433 } else {
434 let native_request_for_retry = native_request.clone();
435 let response = execute_with_retry(client.retry_config(), is_retryable_model_error, || {
436 let native_request = native_request_for_retry.clone();
437 async move { client.send_chat(native_request).await }
438 })
439 .await?;
440 let mapped = chat_response_to_llm_response(&response);
441 let response_stream = try_stream! {
442 yield mapped;
443 };
444
445 Ok(Box::pin(response_stream))
446 }
447}
448
449fn chat_stream_incomplete(unfinished: &str) -> AdkError {
450 crate::stream_error::incomplete(
451 "OpenRouter chat",
452 "model.openrouter.chat_stream_incomplete",
453 unfinished,
454 )
455 .with_provider("openrouter")
456}
457
458async fn build_responses_llm_stream(
459 client: &OpenRouterClient,
460 request: LlmRequest,
461 request_options: &OpenRouterRequestOptions,
462 stream: bool,
463) -> Result<LlmResponseStream> {
464 let native_request = build_responses_request(client, &request, request_options, stream)?;
465
466 if stream {
467 let native_request_for_retry = native_request.clone();
468 let native_stream =
469 execute_with_retry(client.retry_config(), is_retryable_model_error, || {
470 let native_request = native_request_for_retry.clone();
471 async move { client.create_response_stream(native_request).await }
472 })
473 .await?;
474
475 let response_stream = try_stream! {
480 let mut native_stream = native_stream;
481
482 while let Some(item) = native_stream.next().await {
483 match item? {
484 super::stream::OpenRouterResponsesStreamItem::Event(event) => {
485 match event.kind.as_str() {
486 "response.output_text.delta" => {
487 if let Some(delta) = event.delta.as_deref()
488 && let Some(response) = llm_stream_response(
489 vec![Part::Text { text: delta.to_string() }],
490 None,
491 None,
492 None,
493 true,
494 false,
495 ) {
496 yield response;
497 }
498 }
499 "response.reasoning.delta"
500 | "response.reasoning_text.delta"
501 | "response.reasoning_summary_text.delta" => {
502 if let Some(delta) = event.delta.as_deref().or(event.text.as_deref())
503 && let Some(response) = llm_stream_response(
504 vec![Part::Thinking {
505 thinking: delta.to_string(),
506 signature: None,
507 }],
508 None,
509 None,
510 None,
511 true,
512 false,
513 ) {
514 yield response;
515 }
516 }
517 "response.failed" => {
518 Err(super::error::response_failed_to_adk_error(
519 event.response.as_ref().and_then(|response| response.error.as_ref()),
520 ))?;
521 }
522 "response.completed" | "response.incomplete" => {
523 let response = event.response.as_ref().ok_or_else(|| {
524 AdkError::new(
525 ErrorComponent::Model,
526 ErrorCategory::Internal,
527 "model.openrouter.responses_stream_invalid_event",
528 "OpenRouter responses stream ended with a terminal event that carries no response",
529 )
530 .with_provider("openrouter")
531 })?;
532 if let Some(mut mapped) = responses_terminal_to_llm_response(response)? {
533 mapped
534 .provider_metadata
535 .get_or_insert_with(|| json!({}))["content_complete"] = json!(true);
536 yield mapped;
537 }
538 return;
539 }
540 _ => {}
541 }
542 }
543 super::stream::OpenRouterResponsesStreamItem::Done => {}
545 super::stream::OpenRouterResponsesStreamItem::Error(_) => unreachable!(),
546 }
547 }
548
549 Err(crate::stream_error::incomplete(
550 "OpenRouter responses",
551 "model.openrouter.responses_stream_incomplete",
552 "the response finished",
553 )
554 .with_provider("openrouter"))?;
555 };
556
557 Ok(Box::pin(response_stream))
558 } else {
559 let native_request_for_retry = native_request.clone();
560 let response = execute_with_retry(client.retry_config(), is_retryable_model_error, || {
561 let native_request = native_request_for_retry.clone();
562 async move { client.create_response(native_request).await }
563 })
564 .await?;
565 let mapped = responses_terminal_to_llm_response(&response)?;
566 let response_stream = try_stream! {
567 if let Some(mapped) = mapped {
568 yield mapped;
569 }
570 };
571
572 Ok(Box::pin(response_stream))
573 }
574}
575
576fn responses_terminal_to_llm_response(
580 response: &OpenRouterResponse,
581) -> Result<Option<LlmResponse>> {
582 let failure = |category: ErrorCategory, code: &'static str, message: &'static str| {
583 AdkError::new(ErrorComponent::Model, category, code, message).with_provider("openrouter")
584 };
585 match response.status.as_deref() {
586 Some("failed") => {
587 return Err(super::error::response_failed_to_adk_error(response.error.as_ref()));
588 }
589 Some("cancelled") => {
590 return Err(failure(
591 ErrorCategory::Cancelled,
592 "model.openrouter.response_cancelled",
593 "OpenRouter response was cancelled",
594 ));
595 }
596 Some("incomplete")
597 if !matches!(
598 response
599 .incomplete_details
600 .as_ref()
601 .and_then(|details| details.get("reason"))
602 .and_then(Value::as_str),
603 Some("max_output_tokens" | "content_filter")
604 ) =>
605 {
606 return Err(failure(
607 ErrorCategory::Internal,
608 "model.openrouter.response_incomplete",
609 "OpenRouter response is incomplete",
610 ));
611 }
612 _ => {}
613 }
614 responses_response_to_llm_response(response)
615}
616
617fn build_chat_request(
618 client: &OpenRouterClient,
619 request: &LlmRequest,
620 request_options: &OpenRouterRequestOptions,
621 stream: bool,
622) -> Result<OpenRouterChatRequest> {
623 crate::generation_config::reject_unsupported(
624 "openrouter",
625 request.config.as_ref(),
626 crate::generation_config::Supports {
627 stop_sequences: true,
628 seed: true,
629 penalties: true,
630 top_logprobs: true,
631 },
632 )?;
633 let mut chat_request = OpenRouterChatRequest {
634 model: effective_model_name(client, request),
635 messages: adk_contents_to_chat_messages(&request.contents)?,
636 tools: chat_tools_from_llm_request(&request.tools),
637 tool_choice: request_options.tool_choice.clone(),
638 parallel_tool_calls: request_options.parallel_tool_calls,
639 plugins: chat_plugins_for_request(&request.contents, request_options),
640 provider: request_options.provider.clone(),
641 models: request_options.models.clone(),
642 route: request_options.route.clone(),
643 reasoning: request_options.reasoning.clone(),
644 reasoning_content: request_options.reasoning_content.clone(),
645 reasoning_details: request_options.reasoning_details.clone(),
646 response_format: request_options.response_format.clone(),
647 modalities: request_options.modalities.clone(),
648 image_config: request_options.image_config.clone(),
649 metadata: request_options.metadata.clone(),
650 session_id: request_options.session_id.clone(),
651 trace: request_options.trace.clone(),
652 stream: stream.then_some(true),
653 stream_options: stream.then_some(json!({ "include_usage": true })),
654 user: request_options.user.clone(),
655 extra: request_options.extra.clone(),
656 ..Default::default()
657 };
658
659 if let Some(config) = request.config.as_ref() {
660 apply_generate_config_to_chat_request(&mut chat_request, config, &request.model);
661 }
662
663 Ok(chat_request)
664}
665
666fn build_responses_request(
667 client: &OpenRouterClient,
668 request: &LlmRequest,
669 request_options: &OpenRouterRequestOptions,
670 stream: bool,
671) -> Result<OpenRouterResponsesRequest> {
672 let mut responses_request = OpenRouterResponsesRequest {
673 input: Some(adk_contents_to_response_input(&request.contents)?),
674 instructions: request_options.instructions.clone(),
675 metadata: request_options.metadata.clone(),
676 tools: responses_tools_from_llm_request(&request.tools, request_options),
677 tool_choice: request_options.tool_choice.clone(),
678 parallel_tool_calls: request_options.parallel_tool_calls,
679 model: Some(effective_model_name(client, request)),
680 models: request_options.models.clone(),
681 text: request_options.response_text.clone(),
682 reasoning: request_options.reasoning.clone(),
683 reasoning_content: request_options.reasoning_content.clone(),
684 reasoning_details: request_options.reasoning_details.clone(),
685 image_config: request_options.image_config.clone(),
686 modalities: request_options.modalities.clone(),
687 prompt_cache_key: request_options.prompt_cache_key.clone(),
688 previous_response_id: request_options.previous_response_id.clone(),
689 include: request_options.include.clone(),
690 stream: stream.then_some(true),
691 provider: request_options.provider.clone(),
692 route: request_options.route.clone(),
693 session_id: request_options.session_id.clone(),
694 trace: request_options.trace.clone(),
695 user: request_options.user.clone(),
696 plugins: request_options.plugins.clone(),
697 extra: request_options.extra.clone(),
698 ..Default::default()
699 };
700
701 if let Some(config) = request.config.as_ref() {
702 crate::generation_config::reject_unsupported(
704 "OpenRouter Responses",
705 Some(config),
706 crate::generation_config::Supports {
707 stop_sequences: true,
708 seed: false,
709 penalties: true,
710 top_logprobs: true,
711 },
712 )
713 .map_err(|error| error.with_provider("openrouter"))?;
714 apply_generate_config_to_responses_request(&mut responses_request, config, &request.model);
715 }
716
717 Ok(responses_request)
718}
719
720fn effective_model_name(client: &OpenRouterClient, request: &LlmRequest) -> String {
721 if request.model.trim().is_empty() { client.model().to_string() } else { request.model.clone() }
722}
723
724fn chat_tools_from_llm_request(tools: &adk_core::ToolDeclarations) -> Option<Vec<OpenRouterTool>> {
725 (!tools.is_empty()).then_some(
726 tools
727 .iter()
728 .map(|(name, declaration)| OpenRouterTool {
729 kind: "function".to_string(),
730 function: Some(OpenRouterFunctionDescription {
731 name: name.clone(),
732 description: declaration
733 .get("description")
734 .and_then(Value::as_str)
735 .map(ToString::to_string),
736 parameters: declaration.get("parameters").cloned(),
737 ..Default::default()
738 }),
739 ..Default::default()
740 })
741 .collect(),
742 )
743}
744
745fn responses_tools_from_llm_request(
746 tools: &adk_core::ToolDeclarations,
747 request_options: &OpenRouterRequestOptions,
748) -> Option<Vec<OpenRouterResponseTool>> {
749 let mut response_tools = tools
750 .iter()
751 .map(|(name, declaration)| OpenRouterResponseTool {
752 kind: "function".to_string(),
753 name: Some(name.clone()),
754 description: declaration
755 .get("description")
756 .and_then(Value::as_str)
757 .map(ToString::to_string),
758 parameters: declaration.get("parameters").cloned(),
759 strict: declaration.get("strict").and_then(Value::as_bool),
760 ..Default::default()
761 })
762 .collect::<Vec<_>>();
763
764 if let Some(extra_tools) = request_options.response_tools.as_ref() {
765 response_tools.extend(extra_tools.clone());
766 }
767
768 (!response_tools.is_empty()).then_some(response_tools)
769}
770
771fn chat_plugins_for_request(
772 contents: &[Content],
773 request_options: &OpenRouterRequestOptions,
774) -> Option<Vec<OpenRouterPlugin>> {
775 let plugins = augment_chat_plugins_for_contents(
776 contents,
777 request_options.plugins.clone().unwrap_or_default(),
778 );
779 (!plugins.is_empty()).then_some(plugins)
780}
781
782fn request_reasoning(
786 options: Option<OpenRouterReasoningConfig>,
787 config: &GenerateContentConfig,
788) -> Option<OpenRouterReasoningConfig> {
789 let Some(level) = config.effort else {
790 return options;
791 };
792 let mut reasoning = options.unwrap_or_default();
793 if reasoning.effort.is_some()
794 || reasoning.max_tokens.is_some()
795 || reasoning.enabled == Some(false)
796 {
797 tracing::debug!(
798 effort = %level,
799 "openrouter reasoning options choose the reasoning; the request's effort is ignored"
800 );
801 return Some(reasoning);
802 }
803 reasoning.effort = Some(level.as_str().to_string());
804 Some(reasoning)
805}
806
807fn apply_generate_config_to_chat_request(
808 request: &mut OpenRouterChatRequest,
809 config: &GenerateContentConfig,
810 model_name: &str,
811) {
812 request.reasoning = request_reasoning(request.reasoning.take(), config);
813 request.temperature = config.temperature;
814 request.top_p = config.top_p;
815 request.max_completion_tokens = config.max_output_tokens;
816 request.frequency_penalty = config.frequency_penalty;
817 request.presence_penalty = config.presence_penalty;
818 request.seed = config.seed;
819 request.top_logprobs = config.top_logprobs;
820
821 if !config.stop_sequences.is_empty() {
822 request.stop =
823 Some(Value::Array(config.stop_sequences.iter().cloned().map(Value::String).collect()));
824 }
825
826 if request.response_format.is_none() {
827 request.response_format =
828 config.response_schema.as_ref().map(|schema| OpenRouterResponseFormat {
829 kind: "json_schema".to_string(),
830 json_schema: Some(json!({
831 "name": sanitized_schema_name(model_name),
832 "schema": schema,
833 "strict": true
834 })),
835 ..Default::default()
836 });
837 }
838}
839
840fn apply_generate_config_to_responses_request(
841 request: &mut OpenRouterResponsesRequest,
842 config: &GenerateContentConfig,
843 model_name: &str,
844) {
845 request.reasoning = request_reasoning(request.reasoning.take(), config);
846 request.temperature = config.temperature;
847 request.top_p = config.top_p;
848 request.top_k = config.top_k;
849 request.max_output_tokens = config.max_output_tokens;
850 request.frequency_penalty = config.frequency_penalty;
851 request.presence_penalty = config.presence_penalty;
852 request.top_logprobs = config.top_logprobs;
853
854 if !config.stop_sequences.is_empty() {
855 request.extra.insert(
856 "stop".to_string(),
857 Value::Array(config.stop_sequences.iter().cloned().map(Value::String).collect()),
858 );
859 }
860
861 if let Some(schema) = config.response_schema.as_ref() {
862 let mut text_config = request.text.clone().unwrap_or_default();
863 if text_config.format.is_none() {
864 text_config.format = Some(json!({
865 "type": "json_schema",
866 "name": sanitized_schema_name(model_name),
867 "schema": schema,
868 "strict": true
869 }));
870 }
871 request.text = Some(text_config);
872 }
873}
874
875fn sanitized_schema_name(model_name: &str) -> String {
876 model_name.replace(['-', '.', '/'], "_")
877}
878
879fn chat_response_to_llm_response(response: &OpenRouterChatResponse) -> LlmResponse {
880 let mut parts = Vec::new();
881 let mut provider_metadata = Map::new();
882
883 if let Some(choice) = response.choices.first() {
884 if let Some(message) = choice.message.as_ref() {
885 let (reasoning_parts, reasoning_metadata) = chat_message_reasoning_to_parts(message);
886 parts.extend(reasoning_parts);
887 parts.extend(chat_content_to_parts(message.content.as_ref()));
888 if let Some(refusal) = message.refusal.as_ref().filter(|r| !r.is_empty()) {
889 parts.push(Part::Text { text: refusal.clone() });
890 }
891 parts.extend(chat_tool_calls_to_parts(message.tool_calls.as_ref()));
892 merge_metadata_object(&mut provider_metadata, reasoning_metadata);
893 }
894
895 if let Some(logprobs) = choice.logprobs.clone() {
896 provider_metadata.insert("logprobs".to_string(), logprobs);
897 }
898 if !choice.extra.is_empty() {
899 provider_metadata.insert("choice_extra".to_string(), json!(choice.extra));
900 }
901 }
902
903 merge_metadata_object(&mut provider_metadata, chat_response_provider_metadata(response));
904
905 if let Some(system_fingerprint) = response.system_fingerprint.as_ref() {
906 provider_metadata
907 .insert("system_fingerprint".to_string(), Value::String(system_fingerprint.clone()));
908 }
909 if !response.extra.is_empty() {
910 provider_metadata.insert("response_extra".to_string(), json!(response.extra));
911 }
912
913 LlmResponse {
914 content: (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts }),
915 usage_metadata: response.usage.as_ref().map(chat_usage_to_metadata),
916 finish_reason: response.choices.first().and_then(|choice| {
917 let refused = choice
918 .message
919 .as_ref()
920 .and_then(|message| message.refusal.as_ref())
921 .is_some_and(|refusal| !refusal.is_empty());
922 choice
923 .finish_reason
924 .as_deref()
925 .map(|finish_reason| chat_finish_reason(choice, finish_reason, refused))
926 }),
927 citation_metadata: chat_response_citation_metadata(response),
928 partial: false,
929 turn_complete: true,
930 interrupted: false,
931 error_code: None,
932 error_message: None,
933 provider_metadata: (!provider_metadata.is_empty())
934 .then_some(Value::Object(provider_metadata)),
935 interaction_id: None,
936 model: None,
937 provider: None,
938 }
939}
940
941fn responses_response_to_llm_response(
942 response: &OpenRouterResponse,
943) -> Result<Option<LlmResponse>> {
944 let mut parts = Vec::new();
945 let mut provider_metadata = Map::new();
946
947 let (reasoning_parts, reasoning_metadata) =
948 responses_reasoning_items_to_parts(&response.output);
949 parts.extend(reasoning_parts);
950 merge_metadata_object(&mut provider_metadata, reasoning_metadata);
951
952 for item in &response.output {
953 match item.kind.as_str() {
954 "message" => parts.extend(response_message_item_to_parts(item)),
955 "function_call" => parts.push(response_function_call_part(item)?),
956 _ => {}
957 }
958 }
959
960 merge_metadata_object(&mut provider_metadata, responses_provider_metadata(response));
961 let logprobs: Vec<Value> = response
963 .output
964 .iter()
965 .filter(|item| item.kind == "message")
966 .filter_map(|item| item.content.as_ref().and_then(Value::as_array))
967 .flatten()
968 .filter_map(|part| part.get("logprobs").and_then(Value::as_array))
969 .flatten()
970 .cloned()
971 .collect();
972 merge_metadata_object(&mut provider_metadata, logprobs_metadata(logprobs));
973
974 if let Some(previous_response_id) = response.previous_response_id.as_ref() {
975 provider_metadata.insert(
976 "previous_response_id".to_string(),
977 Value::String(previous_response_id.clone()),
978 );
979 }
980 if let Some(incomplete_details) = response.incomplete_details.clone() {
981 provider_metadata.insert("incomplete_details".to_string(), incomplete_details);
982 }
983 if let Some(error) = response.error.clone() {
984 provider_metadata.insert("error".to_string(), error);
985 }
986 if !response.extra.is_empty() {
987 provider_metadata.insert("response_extra".to_string(), json!(response.extra));
988 }
989
990 let usage_metadata = response.usage.as_ref().map(responses_usage_to_metadata);
991 let finish_reason = responses_finish_reason(response);
992 let citation_metadata = responses_citation_metadata(response);
993 let content = (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts });
994
995 if content.is_none()
996 && usage_metadata.is_none()
997 && finish_reason.is_none()
998 && citation_metadata.is_none()
999 && provider_metadata.is_empty()
1000 {
1001 return Ok(None);
1002 }
1003
1004 Ok(Some(LlmResponse {
1005 content,
1006 usage_metadata,
1007 finish_reason,
1008 citation_metadata,
1009 partial: false,
1010 turn_complete: true,
1011 interrupted: false,
1012 error_code: None,
1013 error_message: None,
1014 provider_metadata: (!provider_metadata.is_empty())
1015 .then_some(Value::Object(provider_metadata)),
1016 interaction_id: None,
1017 model: None,
1018 provider: None,
1019 }))
1020}
1021
1022fn chat_content_to_parts(content: Option<&OpenRouterChatMessageContent>) -> Vec<Part> {
1023 match content {
1024 Some(OpenRouterChatMessageContent::Text(text)) if !text.is_empty() => {
1025 vec![Part::Text { text: text.clone() }]
1026 }
1027 Some(OpenRouterChatMessageContent::Parts(parts)) => parts
1028 .iter()
1029 .filter_map(|part| {
1030 (part.kind == "text")
1031 .then_some(part.text.as_ref())
1032 .flatten()
1033 .filter(|text| !text.is_empty())
1034 .map(|text| Part::Text { text: text.clone() })
1035 })
1036 .collect(),
1037 _ => Vec::new(),
1038 }
1039}
1040
1041fn chat_tool_calls_to_parts(tool_calls: Option<&Vec<OpenRouterChatToolCall>>) -> Vec<Part> {
1042 tool_calls.into_iter().flatten().filter_map(chat_tool_call_to_part).collect()
1043}
1044
1045fn chat_tool_call_to_part(tool_call: &OpenRouterChatToolCall) -> Option<Part> {
1046 let function = tool_call.function.as_ref()?;
1047 let name = function.name.clone()?;
1048 let args = crate::tool_args::streamed_tool_arguments(
1051 "openrouter",
1052 &name,
1053 function.arguments.as_deref().unwrap_or_default(),
1054 );
1055
1056 Some(Part::FunctionCall { name, args, id: tool_call.id.clone(), thought_signature: None })
1057}
1058
1059fn response_message_item_to_parts(item: &OpenRouterResponseOutputItem) -> Vec<Part> {
1060 item.content
1061 .as_ref()
1062 .and_then(Value::as_array)
1063 .into_iter()
1064 .flatten()
1065 .filter_map(|part| {
1066 let field = match part.get("type").and_then(Value::as_str) {
1067 Some("output_text") => "text",
1068 Some("refusal") => "refusal",
1069 _ => return None,
1070 };
1071 part.get(field)
1072 .and_then(Value::as_str)
1073 .filter(|text| !text.is_empty())
1074 .map(|text| Part::Text { text: text.to_string() })
1075 })
1076 .collect()
1077}
1078
1079fn response_function_call_part(item: &OpenRouterResponseOutputItem) -> Result<Part> {
1083 let invalid = |message: &'static str| {
1084 AdkError::new(
1085 ErrorComponent::Model,
1086 ErrorCategory::Internal,
1087 "model.openrouter.invalid_tool_call",
1088 message,
1089 )
1090 .with_provider("openrouter")
1091 };
1092 let name = item
1093 .name
1094 .clone()
1095 .ok_or_else(|| invalid("OpenRouter returned a tool call without a name"))?;
1096 if item.status.as_deref().is_some_and(|status| status != "completed") {
1097 return Err(invalid("OpenRouter returned an unfinished tool call"));
1098 }
1099 let args = crate::tool_args::streamed_tool_arguments(
1100 "openrouter",
1101 &name,
1102 item.arguments.as_deref().unwrap_or_default(),
1103 );
1104
1105 Ok(Part::FunctionCall {
1106 name,
1107 args,
1108 id: item.call_id.clone().or_else(|| item.id.clone()),
1109 thought_signature: None,
1110 })
1111}
1112
1113fn chat_finish_reason(
1120 choice: &super::chat::OpenRouterChatChoice,
1121 finish_reason: &str,
1122 refused: bool,
1123) -> FinishReason {
1124 let native = choice.extra.get("native_finish_reason").and_then(Value::as_str);
1125 match (finish_reason, native) {
1126 _ if refused => FinishReason::Refusal,
1127 (_, Some("refusal")) => FinishReason::Refusal,
1128 (_, Some("MALFORMED_FUNCTION_CALL" | "UNEXPECTED_TOOL_CALL" | "malformed_tool_use")) => {
1129 FinishReason::MalformedToolCall
1130 }
1131 ("stop" | "tool_calls" | "function_call", _) => FinishReason::Stop,
1132 ("length" | "max_tokens", _) => FinishReason::MaxTokens,
1133 ("content_filter" | "safety", _) => FinishReason::Safety,
1134 ("recitation", _) => FinishReason::Recitation,
1135 _ => FinishReason::Other,
1136 }
1137}
1138
1139fn responses_finish_reason(response: &OpenRouterResponse) -> Option<FinishReason> {
1140 let refused = response
1141 .output
1142 .iter()
1143 .filter(|item| item.kind == "message")
1144 .filter_map(|item| item.content.as_ref().and_then(Value::as_array))
1145 .flatten()
1146 .any(|part| {
1147 part.get("type").and_then(Value::as_str) == Some("refusal")
1148 && part.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.is_empty())
1149 });
1150 match response.status.as_deref() {
1151 Some("completed") if refused => Some(FinishReason::Refusal),
1152 Some("completed") => Some(FinishReason::Stop),
1153 Some("incomplete") => match response
1154 .incomplete_details
1155 .as_ref()
1156 .and_then(|details| details.get("reason"))
1157 .and_then(Value::as_str)
1158 {
1159 Some("max_output_tokens") => Some(FinishReason::MaxTokens),
1160 Some("content_filter") => Some(FinishReason::Safety),
1161 Some(_) | None => Some(FinishReason::Other),
1162 },
1163 Some("failed" | "cancelled") => Some(FinishReason::Other),
1164 _ => None,
1165 }
1166}
1167
1168fn logprobs_metadata(logprobs: Vec<Value>) -> Option<Value> {
1171 (!logprobs.is_empty()).then(|| json!({"logprobs": {"content": logprobs}}))
1172}
1173
1174fn merge_metadata_object(target: &mut Map<String, Value>, value: Option<Value>) {
1175 if let Some(Value::Object(object)) = value {
1176 target.extend(object);
1177 }
1178}
1179
1180fn llm_stream_response(
1181 parts: Vec<Part>,
1182 usage_metadata: Option<adk_core::UsageMetadata>,
1183 finish_reason: Option<FinishReason>,
1184 provider_metadata: Option<Value>,
1185 partial: bool,
1186 turn_complete: bool,
1187) -> Option<LlmResponse> {
1188 if parts.is_empty()
1189 && usage_metadata.is_none()
1190 && finish_reason.is_none()
1191 && provider_metadata.is_none()
1192 {
1193 return None;
1194 }
1195
1196 Some(LlmResponse {
1197 content: (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts }),
1198 usage_metadata,
1199 finish_reason,
1200 citation_metadata: None,
1201 partial,
1202 turn_complete,
1203 interrupted: false,
1204 error_code: None,
1205 error_message: None,
1206 provider_metadata,
1207 interaction_id: None,
1208 model: None,
1209 provider: None,
1210 })
1211}
1212
1213#[derive(Debug, Default)]
1214struct ChatStreamState {
1215 pending_tool_calls: BTreeMap<usize, PendingChatToolCall>,
1216}
1217
1218#[derive(Debug, Default)]
1219struct PendingChatToolCall {
1220 id: Option<String>,
1221 name: Option<String>,
1222 arguments: String,
1223}
1224
1225impl ChatStreamState {
1226 fn capture_chat_tool_calls(&mut self, tool_calls: &[OpenRouterChatToolCall]) {
1227 for (pos, tool_call) in tool_calls.iter().enumerate() {
1228 let key = tool_call.index.unwrap_or(pos);
1232 let pending = self.pending_tool_calls.entry(key).or_default();
1233 if let Some(id) = tool_call.id.as_ref() {
1234 pending.id = Some(id.clone());
1235 }
1236 if let Some(function) = tool_call.function.as_ref() {
1237 if let Some(name) = function.name.as_ref() {
1238 pending.name = Some(name.clone());
1239 }
1240 if let Some(arguments) = function.arguments.as_ref() {
1241 pending.arguments.push_str(arguments);
1242 }
1243 }
1244 }
1245 }
1246
1247 fn has_pending_tool_calls(&self) -> bool {
1248 !self.pending_tool_calls.is_empty()
1249 }
1250
1251 fn drain_chat_tool_calls(&mut self) -> Result<Vec<Part>> {
1255 std::mem::take(&mut self.pending_tool_calls)
1256 .into_values()
1257 .map(|pending| {
1258 let name = pending.name.ok_or_else(|| {
1259 AdkError::new(
1260 ErrorComponent::Model,
1261 ErrorCategory::Internal,
1262 "model.openrouter.invalid_tool_call",
1263 "OpenRouter returned a tool call without a name",
1264 )
1265 .with_provider("openrouter")
1266 })?;
1267 let args = crate::tool_args::streamed_tool_arguments(
1268 "openrouter",
1269 &name,
1270 &pending.arguments,
1271 );
1272 Ok(Part::FunctionCall { name, args, id: pending.id, thought_signature: None })
1273 })
1274 .collect()
1275 }
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280 use super::OpenRouterRequestOptions;
1281 use crate::openrouter::chat::{
1282 OpenRouterPlugin, OpenRouterProviderPreferences, OpenRouterReasoningConfig,
1283 };
1284 use crate::openrouter::responses::OpenRouterResponseTool;
1285 use crate::openrouter::{OpenRouterApiMode, OpenRouterClient, OpenRouterConfig};
1286 use adk_core::{GenerateContentConfig, Llm, LlmRequest, Part};
1287 use futures::StreamExt;
1288 use serde_json::json;
1289 use wiremock::matchers::{body_json, method, path};
1290 use wiremock::{Mock, MockServer, ResponseTemplate};
1291
1292 #[test]
1293 fn request_options_round_trip_through_extension_bag() {
1294 let options = OpenRouterRequestOptions::default()
1295 .with_api_mode(OpenRouterApiMode::Responses)
1296 .with_models(vec!["openai/gpt-5.2".to_string(), "openai/gpt-5-mini".to_string()])
1297 .with_route("fallback")
1298 .with_plugin(OpenRouterPlugin {
1299 id: "web".to_string(),
1300 enabled: Some(true),
1301 ..Default::default()
1302 })
1303 .with_response_tool(OpenRouterResponseTool {
1304 kind: "web_search".to_string(),
1305 ..Default::default()
1306 })
1307 .with_provider_preferences(OpenRouterProviderPreferences {
1308 zdr: Some(true),
1309 ..Default::default()
1310 })
1311 .with_reasoning(OpenRouterReasoningConfig {
1312 effort: Some("high".to_string()),
1313 ..Default::default()
1314 })
1315 .with_previous_response_id("resp_previous")
1316 .with_prompt_cache_key("cache-key")
1317 .with_modalities(vec!["text".to_string(), "image".to_string()])
1318 .with_include(vec!["reasoning.encrypted_content".to_string()]);
1319
1320 let mut config = GenerateContentConfig::default();
1321 options.insert_into_config(&mut config).expect("options should insert into config");
1322
1323 let request = LlmRequest::new("openai/gpt-5.2", vec![]).with_config(config);
1324 let round_trip_request: LlmRequest = serde_json::from_value(
1325 serde_json::to_value(&request).expect("request should serialize"),
1326 )
1327 .expect("request should deserialize");
1328 let round_trip =
1329 OpenRouterRequestOptions::from_generate_config(round_trip_request.config.as_ref())
1330 .expect("options should parse")
1331 .expect("openrouter options should exist");
1332
1333 assert_eq!(round_trip, options);
1334 }
1335
1336 #[tokio::test]
1337 async fn generate_content_chat_mode_maps_reasoning_and_function_calls() {
1338 let server = MockServer::start().await;
1339 let expected_body = json!({
1340 "model": "openai/gpt-5.2",
1341 "messages": [
1342 {
1343 "role": "user",
1344 "content": "hello"
1345 }
1346 ],
1347 "plugins": [
1348 {
1349 "id": "web",
1350 "enabled": true
1351 }
1352 ],
1353 "provider": {
1354 "zdr": true
1355 }
1356 });
1357
1358 Mock::given(method("POST"))
1359 .and(path("/chat/completions"))
1360 .and(body_json(&expected_body))
1361 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1362 "id": "chatcmpl-1",
1363 "model": "openai/gpt-5.2",
1364 "choices": [
1365 {
1366 "index": 0,
1367 "message": {
1368 "role": "assistant",
1369 "reasoning": "Need to call the weather tool.",
1370 "content": "",
1371 "tool_calls": [
1372 {
1373 "id": "call_weather",
1374 "type": "function",
1375 "function": {
1376 "name": "lookup_weather",
1377 "arguments": "{\"city\":\"Nairobi\"}"
1378 }
1379 }
1380 ]
1381 },
1382 "finish_reason": "tool_calls"
1383 }
1384 ]
1385 })))
1386 .mount(&server)
1387 .await;
1388
1389 let client = OpenRouterClient::new(
1390 OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
1391 )
1392 .expect("client should build");
1393
1394 let mut config = GenerateContentConfig::default();
1395 OpenRouterRequestOptions::default()
1396 .with_plugin(OpenRouterPlugin {
1397 id: "web".to_string(),
1398 enabled: Some(true),
1399 ..Default::default()
1400 })
1401 .with_provider_preferences(OpenRouterProviderPreferences {
1402 zdr: Some(true),
1403 ..Default::default()
1404 })
1405 .insert_into_config(&mut config)
1406 .expect("options should insert");
1407
1408 let mut stream = client
1409 .generate_content(
1410 LlmRequest::new(
1411 "openai/gpt-5.2",
1412 vec![adk_core::Content::new("user").with_text("hello")],
1413 )
1414 .with_config(config),
1415 false,
1416 )
1417 .await
1418 .expect("generation should start");
1419
1420 let response = stream.next().await.expect("response").expect("response should succeed");
1421 let content = response.content.expect("content should exist");
1422
1423 assert_eq!(response.finish_reason, Some(adk_core::FinishReason::Stop));
1424 assert!(
1425 matches!(&content.parts[0], Part::Thinking { thinking, .. } if thinking == "Need to call the weather tool.")
1426 );
1427 assert!(
1428 matches!(&content.parts[1], Part::FunctionCall { name, id, .. } if name == "lookup_weather" && id.as_deref() == Some("call_weather"))
1429 );
1430 }
1431
1432 #[tokio::test]
1433 async fn generate_content_chat_stream_emits_one_final_chunk_when_usage_arrives_after_finish() {
1434 let server = MockServer::start().await;
1435
1436 Mock::given(method("POST"))
1437 .and(path("/chat/completions"))
1438 .respond_with(ResponseTemplate::new(200).set_body_string(
1439 "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hello\"}}]}\n\n\
1440 data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n\
1441 data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{}}],\"usage\":{\"prompt_tokens\":4,\"completion_tokens\":2,\"total_tokens\":6}}\n\n\
1442 data: [DONE]\n\n",
1443 ))
1444 .mount(&server)
1445 .await;
1446
1447 let client = OpenRouterClient::new(
1448 OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
1449 )
1450 .expect("client should build");
1451
1452 let mut stream = client
1453 .generate_content(
1454 LlmRequest::new(
1455 "openai/gpt-5.2",
1456 vec![adk_core::Content::new("user").with_text("hello")],
1457 ),
1458 true,
1459 )
1460 .await
1461 .expect("generation should start");
1462
1463 let mut responses = Vec::new();
1464 while let Some(item) = stream.next().await {
1465 responses.push(item.expect("chunk should succeed"));
1466 }
1467
1468 assert_eq!(responses.len(), 2);
1469 assert!(responses[0].partial);
1470 assert!(!responses[0].turn_complete);
1471 assert_eq!(
1472 responses[0]
1473 .content
1474 .as_ref()
1475 .and_then(|content| content.parts.first())
1476 .and_then(Part::text),
1477 Some("hello")
1478 );
1479
1480 assert!(!responses[1].partial);
1481 assert!(responses[1].turn_complete);
1482 assert_eq!(responses[1].finish_reason, Some(adk_core::FinishReason::Stop));
1483 assert_eq!(
1484 responses[1].usage_metadata.as_ref().map(|usage| usage.total_token_count),
1485 Some(6)
1486 );
1487 }
1488
1489 #[tokio::test]
1490 async fn generate_content_responses_mode_uses_extension_options_after_request_round_trip() {
1491 let server = MockServer::start().await;
1492 let expected_body = json!({
1493 "model": "openai/gpt-5.2",
1494 "input": [
1495 {
1496 "type": "message",
1497 "role": "user",
1498 "content": "hello"
1499 }
1500 ],
1501 "tools": [
1502 {
1503 "type": "web_search"
1504 }
1505 ],
1506 "reasoning": {
1507 "effort": "medium"
1508 },
1509 "previous_response_id": "resp_previous",
1510 "prompt_cache_key": "cache-key",
1511 "include": ["reasoning.encrypted_content"],
1512 "route": "fallback",
1513 "models": ["openai/gpt-5.2", "openai/gpt-5-mini"]
1514 });
1515
1516 Mock::given(method("POST"))
1517 .and(path("/responses"))
1518 .and(body_json(&expected_body))
1519 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1520 "id": "resp-1",
1521 "model": "openai/gpt-5.2",
1522 "status": "completed",
1523 "output": [
1524 {
1525 "type": "message",
1526 "id": "msg-1",
1527 "role": "assistant",
1528 "status": "completed",
1529 "content": [
1530 {
1531 "type": "output_text",
1532 "text": "hello back",
1533 "annotations": []
1534 }
1535 ]
1536 }
1537 ],
1538 "usage": {
1539 "input_tokens": 10,
1540 "input_tokens_details": { "cached_tokens": 1 },
1541 "output_tokens": 6,
1542 "output_tokens_details": { "reasoning_tokens": 2 },
1543 "total_tokens": 16,
1544 "cost": 0.001
1545 }
1546 })))
1547 .mount(&server)
1548 .await;
1549
1550 let client = OpenRouterClient::new(
1551 OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
1552 )
1553 .expect("client should build");
1554
1555 let mut config = GenerateContentConfig::default();
1556 OpenRouterRequestOptions::default()
1557 .with_api_mode(OpenRouterApiMode::Responses)
1558 .with_response_tool(OpenRouterResponseTool {
1559 kind: "web_search".to_string(),
1560 ..Default::default()
1561 })
1562 .with_reasoning(OpenRouterReasoningConfig {
1563 effort: Some("medium".to_string()),
1564 ..Default::default()
1565 })
1566 .with_previous_response_id("resp_previous")
1567 .with_prompt_cache_key("cache-key")
1568 .with_include(vec!["reasoning.encrypted_content".to_string()])
1569 .with_route("fallback")
1570 .with_models(vec!["openai/gpt-5.2".to_string(), "openai/gpt-5-mini".to_string()])
1571 .insert_into_config(&mut config)
1572 .expect("options should insert");
1573
1574 let request = LlmRequest::new(
1575 "openai/gpt-5.2",
1576 vec![adk_core::Content::new("user").with_text("hello")],
1577 )
1578 .with_config(config);
1579 let round_trip_request: LlmRequest = serde_json::from_value(
1580 serde_json::to_value(&request).expect("request should serialize"),
1581 )
1582 .expect("request should deserialize");
1583
1584 let mut stream = client
1585 .generate_content(round_trip_request, false)
1586 .await
1587 .expect("generation should start");
1588
1589 let response = stream.next().await.expect("response").expect("response should succeed");
1590 assert_eq!(
1591 response
1592 .content
1593 .as_ref()
1594 .and_then(|content| content.parts.first())
1595 .and_then(Part::text),
1596 Some("hello back")
1597 );
1598 assert_eq!(response.usage_metadata.as_ref().and_then(|usage| usage.cost), Some(0.001));
1599 }
1600
1601 #[tokio::test]
1602 async fn generate_content_responses_stream_emits_function_call_with_terminal_response() {
1603 let server = MockServer::start().await;
1604
1605 Mock::given(method("POST"))
1606 .and(path("/responses"))
1607 .respond_with(ResponseTemplate::new(200).set_body_string(
1608 "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_weather\",\"name\":\"lookup_weather\",\"arguments\":\"\",\"status\":\"in_progress\"},\"sequence_number\":1}\n\n\
1609 data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"{\\\"city\\\":\\\"Na\",\"sequence_number\":2}\n\n\
1610 data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"irobi\\\"}\",\"sequence_number\":3}\n\n\
1611 data: {\"type\":\"response.function_call_arguments.done\",\"item_id\":\"fc_1\",\"arguments\":\"{\\\"city\\\":\\\"Nairobi\\\"}\",\"sequence_number\":4}\n\n\
1612 data: {\"type\":\"response.completed\",\"sequence_number\":5,\"response\":{\"id\":\"resp_1\",\"status\":\"completed\",\"output\":[{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_weather\",\"name\":\"lookup_weather\",\"arguments\":\"{\\\"city\\\":\\\"Nairobi\\\"}\",\"status\":\"completed\"}]}}\n\n\
1613 data: [DONE]\n\n",
1614 ))
1615 .mount(&server)
1616 .await;
1617
1618 let client = OpenRouterClient::new(
1619 OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
1620 )
1621 .expect("client should build");
1622
1623 let mut config = GenerateContentConfig::default();
1624 OpenRouterRequestOptions::default()
1625 .with_api_mode(OpenRouterApiMode::Responses)
1626 .insert_into_config(&mut config)
1627 .expect("options should insert");
1628
1629 let mut stream = client
1630 .generate_content(
1631 LlmRequest::new(
1632 "openai/gpt-5.2",
1633 vec![adk_core::Content::new("user").with_text("weather")],
1634 )
1635 .with_config(config),
1636 true,
1637 )
1638 .await
1639 .expect("generation should start");
1640
1641 let response = stream.next().await.expect("response").expect("response should succeed");
1642 let part = response
1643 .content
1644 .as_ref()
1645 .and_then(|content| content.parts.first())
1646 .expect("function call part should exist");
1647
1648 match part {
1649 Part::FunctionCall { name, args, id, .. } => {
1650 assert_eq!(name, "lookup_weather");
1651 assert_eq!(id.as_deref(), Some("call_weather"));
1652 assert_eq!(args["city"], json!("Nairobi"));
1653 }
1654 other => panic!("expected function call part, got {other:?}"),
1655 }
1656
1657 assert_eq!(response.content.as_ref().map(|content| content.parts.len()), Some(1));
1658 assert!(response.turn_complete);
1659 assert!(!response.partial);
1660 assert!(stream.next().await.is_none());
1661 }
1662
1663 #[test]
1669 fn streaming_keeps_parallel_tool_calls_separate_by_index() {
1670 use super::ChatStreamState;
1671 use crate::openrouter::chat::{OpenRouterChatToolCall, OpenRouterChatToolFunction};
1672
1673 fn frag(
1674 index: usize,
1675 id: Option<&str>,
1676 name: Option<&str>,
1677 args: &str,
1678 ) -> OpenRouterChatToolCall {
1679 OpenRouterChatToolCall {
1680 index: Some(index),
1681 id: id.map(str::to_string),
1682 kind: String::new(),
1683 function: Some(OpenRouterChatToolFunction {
1684 name: name.map(str::to_string),
1685 arguments: Some(args.to_string()),
1686 output: None,
1687 extra: Default::default(),
1688 }),
1689 extra: Default::default(),
1690 }
1691 }
1692
1693 let mut state = ChatStreamState::default();
1697 state.capture_chat_tool_calls(&[frag(0, Some("call_a"), Some("bash"), "{\"command\": ")]);
1698 state.capture_chat_tool_calls(&[frag(1, Some("call_b"), Some("bash"), "{\"command\": ")]);
1699 state.capture_chat_tool_calls(&[frag(0, None, None, "\"whoami\"}")]);
1700 state.capture_chat_tool_calls(&[frag(1, None, None, "\"pwd\"}")]);
1701
1702 let mut calls: Vec<(Option<String>, String, serde_json::Value)> = state
1703 .drain_chat_tool_calls()
1704 .expect("both calls carry a name and JSON-object arguments")
1705 .into_iter()
1706 .map(|p| match p {
1707 Part::FunctionCall { id, name, args, .. } => (id, name, args),
1708 other => panic!("expected a function call, got {other:?}"),
1709 })
1710 .collect();
1711 calls.sort_by(|a, b| a.0.cmp(&b.0));
1712
1713 assert_eq!(calls.len(), 2, "both parallel calls survive (was 0 before the index fix)");
1714 assert_eq!(calls[0].0.as_deref(), Some("call_a"));
1715 assert_eq!(calls[0].1, "bash");
1716 assert_eq!(calls[0].2, serde_json::json!({ "command": "whoami" }));
1717 assert_eq!(calls[1].0.as_deref(), Some("call_b"));
1718 assert_eq!(calls[1].2, serde_json::json!({ "command": "pwd" }));
1719 }
1720
1721 fn chat_choice(
1722 message: serde_json::Value,
1723 finish: &str,
1724 native: &str,
1725 ) -> adk_core::LlmResponse {
1726 let response: crate::openrouter::chat::OpenRouterChatResponse =
1727 serde_json::from_value(json!({
1728 "choices": [{
1729 "index": 0,
1730 "message": message,
1731 "finish_reason": finish,
1732 "native_finish_reason": native
1733 }]
1734 }))
1735 .unwrap();
1736 super::chat_response_to_llm_response(&response)
1737 }
1738
1739 #[test]
1740 fn a_chat_tool_call_with_malformed_arguments_is_kept_and_marked_invalid() {
1741 let call = |name: &str, arguments: &str| {
1742 json!({
1743 "id": name,
1744 "type": "function",
1745 "function": { "name": name, "arguments": arguments }
1746 })
1747 };
1748 let reply = chat_choice(
1749 json!({ "role": "assistant", "tool_calls": [call("lookup", "{}"), call("check", "{")] }),
1750 "tool_calls",
1751 "tool_calls",
1752 );
1753 let parts = reply.content.unwrap().parts;
1754 let calls: Vec<(&str, bool)> = parts
1755 .iter()
1756 .filter_map(|part| match part {
1757 adk_core::Part::FunctionCall { name, args, .. } => {
1758 Some((name.as_str(), adk_core::invalid_tool_arguments_reason(args).is_some()))
1759 }
1760 _ => None,
1761 })
1762 .collect();
1763 assert_eq!(calls, vec![("lookup", false), ("check", true)]);
1764 }
1765
1766 #[test]
1767 fn a_chat_refusal_is_the_text_and_finishes_with_refusal() {
1768 let response = chat_choice(
1769 json!({"role": "assistant", "content": null, "refusal": "I can't help with that."}),
1770 "stop",
1771 "stop",
1772 );
1773 assert_eq!(
1774 (response.finish_reason, response.content.unwrap().parts),
1775 (
1776 Some(adk_core::FinishReason::Refusal),
1777 vec![Part::Text { text: "I can't help with that.".into() }]
1778 )
1779 );
1780 }
1781
1782 #[test]
1783 fn the_native_finish_reason_reports_refusals_and_malformed_tool_calls() {
1784 for (finish, native, expected) in [
1785 ("stop", "refusal", adk_core::FinishReason::Refusal),
1786 ("stop", "MALFORMED_FUNCTION_CALL", adk_core::FinishReason::MalformedToolCall),
1787 ("stop", "UNEXPECTED_TOOL_CALL", adk_core::FinishReason::MalformedToolCall),
1788 ("stop", "malformed_tool_use", adk_core::FinishReason::MalformedToolCall),
1789 ("stop", "end_turn", adk_core::FinishReason::Stop),
1790 ("length", "max_tokens", adk_core::FinishReason::MaxTokens),
1791 ("content_filter", "SAFETY", adk_core::FinishReason::Safety),
1792 ] {
1793 let response =
1794 chat_choice(json!({"role": "assistant", "content": "x"}), finish, native);
1795 assert_eq!(response.finish_reason, Some(expected), "{finish}/{native}");
1796 }
1797 }
1798
1799 #[test]
1800 fn a_responses_refusal_part_is_the_text_and_finishes_with_refusal() {
1801 let response: crate::openrouter::responses::OpenRouterResponse =
1802 serde_json::from_value(json!({
1803 "status": "completed",
1804 "output": [{
1805 "type": "message",
1806 "id": "msg",
1807 "role": "assistant",
1808 "content": [{"type": "refusal", "refusal": "I can't help with that."}]
1809 }]
1810 }))
1811 .unwrap();
1812 let response = super::responses_response_to_llm_response(&response).unwrap().unwrap();
1813 assert_eq!(
1814 (response.finish_reason, response.content.unwrap().parts),
1815 (
1816 Some(adk_core::FinishReason::Refusal),
1817 vec![Part::Text { text: "I can't help with that.".into() }]
1818 )
1819 );
1820 }
1821}