1use adk_core::model::{FinishReason, GenerateContentConfig, LlmRequest};
52use adk_core::types::{Content, Part};
53use adk_core::{AdkError, ErrorCategory, Llm, ModelCallScope, Result};
54use futures::StreamExt;
55use serde::{Deserialize, Serialize};
56use std::sync::atomic::{AtomicU64, Ordering};
57use std::sync::{Arc, Mutex};
58use tracing::debug;
59
60#[derive(Debug, Default)]
83pub struct SamplingScopes {
84 active: Mutex<Vec<(u64, ModelCallScope)>>,
85 fallback: Mutex<Option<ModelCallScope>>,
86 next_id: AtomicU64,
87}
88
89impl SamplingScopes {
90 pub fn set_fallback(&self, scope: Option<ModelCallScope>) {
92 *self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = scope;
93 }
94
95 pub fn fallback(&self) -> Option<ModelCallScope> {
97 self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()
98 }
99
100 pub fn enter(self: &Arc<Self>, scope: ModelCallScope) -> SamplingScopeGuard {
102 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
103 self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push((id, scope));
104 SamplingScopeGuard { scopes: Arc::clone(self), id }
105 }
106
107 pub fn resolve(&self) -> Option<ModelCallScope> {
109 let active = self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
110 if let Some((_, latest)) = active.last() {
111 if active.iter().any(|(_, scope)| !scope.same_as(latest)) {
112 debug!(
113 in_flight = active.len(),
114 "tool calls from several runs are in flight; sampling counts against the latest"
115 );
116 }
117 return Some(latest.clone());
118 }
119 drop(active);
120 self.fallback()
121 }
122}
123
124#[derive(Debug)]
126pub struct SamplingScopeGuard {
127 scopes: Arc<SamplingScopes>,
128 id: u64,
129}
130
131impl Drop for SamplingScopeGuard {
132 fn drop(&mut self) {
133 self.scopes
134 .active
135 .lock()
136 .unwrap_or_else(|poisoned| poisoned.into_inner())
137 .retain(|(id, _)| *id != self.id);
138 }
139}
140
141#[async_trait::async_trait]
167pub trait SamplingHandler: Send + Sync {
168 async fn handle_create_message(&self, request: SamplingRequest) -> Result<SamplingResponse>;
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185pub struct SamplingRequest {
186 pub messages: Vec<SamplingMessage>,
188
189 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub system_prompt: Option<String>,
192
193 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub model_preferences: Option<ModelPreferences>,
196
197 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub max_tokens: Option<u32>,
200
201 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub temperature: Option<f64>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212pub struct SamplingResponse {
213 pub content: SamplingContent,
215
216 pub model: String,
218
219 pub stop_reason: String,
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct SamplingMessage {
227 pub role: String,
229
230 pub content: SamplingContent,
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
238#[serde(tag = "type")]
239pub enum SamplingContent {
240 #[serde(rename = "text")]
242 Text {
243 text: String,
245 },
246
247 #[serde(rename = "image", rename_all = "camelCase")]
249 Image {
250 data: String,
252 mime_type: String,
254 },
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize)]
262#[serde(rename_all = "camelCase")]
263pub struct ModelPreferences {
264 #[serde(default, skip_serializing_if = "Vec::is_empty")]
266 pub hints: Vec<ModelHint>,
267
268 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub cost_priority: Option<f64>,
271
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub speed_priority: Option<f64>,
275
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub intelligence_priority: Option<f64>,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct ModelHint {
285 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub name: Option<String>,
288}
289
290impl SamplingContent {
295 pub fn text(text: impl Into<String>) -> Self {
305 Self::Text { text: text.into() }
306 }
307
308 pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
318 Self::Image { data: data.into(), mime_type: mime_type.into() }
319 }
320}
321
322impl SamplingMessage {
323 pub fn new(role: impl Into<String>, content: SamplingContent) -> Self {
333 Self { role: role.into(), content }
334 }
335}
336
337impl SamplingResponse {
338 pub fn new(
352 content: SamplingContent,
353 model: impl Into<String>,
354 stop_reason: impl Into<String>,
355 ) -> Self {
356 Self { content, model: model.into(), stop_reason: stop_reason.into() }
357 }
358}
359
360pub struct LlmSamplingHandler {
381 llm: Arc<dyn Llm>,
382}
383
384impl LlmSamplingHandler {
385 pub fn new(llm: Arc<dyn Llm>) -> Self {
387 Self { llm }
388 }
389}
390
391#[async_trait::async_trait]
392impl SamplingHandler for LlmSamplingHandler {
393 async fn handle_create_message(&self, request: SamplingRequest) -> Result<SamplingResponse> {
394 let llm_request = sampling_request_to_llm_request(&request, self.llm.name());
395 debug!(
396 model = self.llm.name(),
397 message_count = request.messages.len(),
398 "routing sampling/createMessage to LLM"
399 );
400
401 let mut stream = adk_core::generate_metered(self.llm.as_ref(), llm_request, false)
403 .await
404 .map_err(|e| match e.category {
405 ErrorCategory::ResourceExhausted => e,
406 _ if e.code == adk_core::SPEND_LIMIT_EXCEEDED_CODE => e,
407 _ => AdkError::tool(format!("LLM sampling failed: {e}")),
408 })?;
409
410 let mut last_response = None;
412 while let Some(item) = stream.next().await {
413 match item {
414 Ok(resp) => last_response = Some(resp),
415 Err(e) => return Err(AdkError::tool(format!("LLM sampling stream error: {e}"))),
416 }
417 }
418
419 let llm_response = last_response
420 .ok_or_else(|| AdkError::tool("LLM returned empty response for sampling request"))?;
421
422 if let Some(ref error_message) = llm_response.error_message {
424 return Err(AdkError::tool(format!("LLM sampling error: {error_message}")));
425 }
426
427 Ok(llm_response_to_sampling_response(llm_response, self.llm.name()))
428 }
429}
430
431pub fn sampling_request_to_llm_request(request: &SamplingRequest, model_name: &str) -> LlmRequest {
439 let mut contents = Vec::with_capacity(request.messages.len() + 1);
440
441 if let Some(ref system_prompt) = request.system_prompt {
443 contents.push(Content::new("system").with_text(system_prompt.clone()));
444 }
445
446 for msg in &request.messages {
448 let role = match msg.role.as_str() {
449 "assistant" => "model",
450 other => other,
451 };
452 let content = match &msg.content {
453 SamplingContent::Text { text } => Content::new(role).with_text(text.clone()),
454 SamplingContent::Image { data, mime_type } => Content {
455 role: role.to_string(),
456 parts: vec![Part::InlineData {
457 mime_type: mime_type.clone(),
458 data: base64_decode_lossy(data),
459 uri: None,
460 annotations: None,
461 }],
462 },
463 };
464 contents.push(content);
465 }
466
467 let config = GenerateContentConfig {
468 temperature: request.temperature.map(|t| t as f32),
469 max_output_tokens: request.max_tokens.map(|t| t as i32),
470 ..Default::default()
471 };
472
473 LlmRequest {
474 model: model_name.to_string(),
475 contents,
476 config: Some(config),
477 tools: Default::default(),
478 previous_response_id: None,
479 }
480}
481
482pub fn llm_response_to_sampling_response(
487 response: adk_core::model::LlmResponse,
488 model_name: &str,
489) -> SamplingResponse {
490 let content = response
491 .content
492 .map(|c| content_to_sampling_content(&c))
493 .unwrap_or_else(|| SamplingContent::text(""));
494
495 let stop_reason = match response.finish_reason {
496 Some(FinishReason::Stop) => "endTurn".to_string(),
497 Some(FinishReason::MaxTokens) => "maxTokens".to_string(),
498 Some(FinishReason::Safety) => "safety".to_string(),
499 Some(FinishReason::Recitation) => "recitation".to_string(),
500 Some(FinishReason::Refusal) => "refusal".to_string(),
501 Some(FinishReason::MalformedToolCall) => "malformedToolCall".to_string(),
502 Some(FinishReason::Other) => "other".to_string(),
503 Some(_) => "other".to_string(),
504 None => "endTurn".to_string(),
505 };
506
507 SamplingResponse { content, model: model_name.to_string(), stop_reason }
508}
509
510fn content_to_sampling_content(content: &Content) -> SamplingContent {
512 for part in &content.parts {
513 match part {
514 Part::Text { text } => return SamplingContent::text(text.clone()),
515 Part::InlineData { mime_type, data, .. } => {
516 return SamplingContent::image(base64_encode(data), mime_type.clone());
517 }
518 _ => continue,
519 }
520 }
521 SamplingContent::text("")
523}
524
525fn base64_decode_lossy(input: &str) -> Vec<u8> {
527 use base64::Engine;
528 base64::engine::general_purpose::STANDARD.decode(input).unwrap_or_default()
529}
530
531fn base64_encode(data: &[u8]) -> String {
533 use base64::Engine;
534 base64::engine::general_purpose::STANDARD.encode(data)
535}
536
537#[cfg(test)]
542mod tests {
543 use super::*;
544
545 #[test]
546 fn sampling_handler_is_send_sync() {
547 fn require_send_sync<T: Send + Sync>() {}
548 require_send_sync::<Box<dyn SamplingHandler>>();
550 }
551
552 #[test]
553 fn sampling_request_json_round_trip() {
554 let request = SamplingRequest {
555 messages: vec![SamplingMessage::new("user", SamplingContent::text("What is 2+2?"))],
556 system_prompt: Some("You are a math tutor.".to_string()),
557 model_preferences: None,
558 max_tokens: Some(100),
559 temperature: Some(0.0),
560 };
561
562 let json = serde_json::to_string(&request).unwrap();
563 let parsed: SamplingRequest = serde_json::from_str(&json).unwrap();
564
565 assert_eq!(parsed.messages.len(), 1);
566 assert_eq!(parsed.system_prompt.as_deref(), Some("You are a math tutor."));
567 assert_eq!(parsed.max_tokens, Some(100));
568 assert_eq!(parsed.temperature, Some(0.0));
569 }
570
571 #[test]
572 fn sampling_response_json_round_trip() {
573 let response =
574 SamplingResponse::new(SamplingContent::text("4"), "gemini-2.0-flash", "endTurn");
575
576 let json = serde_json::to_string(&response).unwrap();
577 let parsed: SamplingResponse = serde_json::from_str(&json).unwrap();
578
579 assert_eq!(parsed.model, "gemini-2.0-flash");
580 assert_eq!(parsed.stop_reason, "endTurn");
581 match &parsed.content {
582 SamplingContent::Text { text } => assert_eq!(text, "4"),
583 _ => panic!("expected text content"),
584 }
585 }
586
587 #[test]
588 fn sampling_request_camel_case_serialization() {
589 let request = SamplingRequest {
590 messages: vec![],
591 system_prompt: Some("test".to_string()),
592 model_preferences: Some(ModelPreferences {
593 hints: vec![ModelHint { name: Some("gpt-4".to_string()) }],
594 cost_priority: Some(0.5),
595 speed_priority: None,
596 intelligence_priority: Some(0.8),
597 }),
598 max_tokens: Some(200),
599 temperature: Some(0.7),
600 };
601
602 let json = serde_json::to_string_pretty(&request).unwrap();
603
604 assert!(json.contains("systemPrompt"));
606 assert!(json.contains("modelPreferences"));
607 assert!(json.contains("maxTokens"));
608 assert!(json.contains("costPriority"));
609 assert!(json.contains("intelligencePriority"));
610
611 assert!(!json.contains("system_prompt"));
613 assert!(!json.contains("model_preferences"));
614 assert!(!json.contains("max_tokens"));
615 assert!(!json.contains("cost_priority"));
616 assert!(!json.contains("intelligence_priority"));
617 }
618
619 #[test]
620 fn sampling_response_camel_case_serialization() {
621 let response = SamplingResponse::new(SamplingContent::text("hello"), "model-1", "endTurn");
622
623 let json = serde_json::to_string(&response).unwrap();
624
625 assert!(json.contains("stopReason"));
626 assert!(!json.contains("stop_reason"));
627 }
628
629 #[test]
630 fn sampling_content_text_variant() {
631 let content = SamplingContent::text("hello");
632 let json = serde_json::to_string(&content).unwrap();
633
634 assert!(json.contains(r#""type":"text"#));
635 assert!(json.contains(r#""text":"hello"#));
636
637 let parsed: SamplingContent = serde_json::from_str(&json).unwrap();
638 match parsed {
639 SamplingContent::Text { text } => assert_eq!(text, "hello"),
640 _ => panic!("expected text variant"),
641 }
642 }
643
644 #[test]
645 fn sampling_content_image_variant() {
646 let content = SamplingContent::image("base64data", "image/png");
647 let json = serde_json::to_string(&content).unwrap();
648
649 assert!(json.contains(r#""type":"image"#));
650 assert!(json.contains(r#""data":"base64data"#));
651 assert!(json.contains(r#""mimeType":"image/png"#));
652
653 let parsed: SamplingContent = serde_json::from_str(&json).unwrap();
654 match parsed {
655 SamplingContent::Image { data, mime_type } => {
656 assert_eq!(data, "base64data");
657 assert_eq!(mime_type, "image/png");
658 }
659 _ => panic!("expected image variant"),
660 }
661 }
662
663 #[test]
664 fn sampling_request_optional_fields_omitted() {
665 let request = SamplingRequest {
666 messages: vec![],
667 system_prompt: None,
668 model_preferences: None,
669 max_tokens: None,
670 temperature: None,
671 };
672
673 let json = serde_json::to_string(&request).unwrap();
674
675 assert!(!json.contains("systemPrompt"));
677 assert!(!json.contains("modelPreferences"));
678 assert!(!json.contains("maxTokens"));
679 assert!(!json.contains("temperature"));
680 }
681
682 #[test]
683 fn sampling_message_deserialization_from_mcp_format() {
684 let json = r#"{
686 "role": "user",
687 "content": { "type": "text", "text": "What is 2+2?" }
688 }"#;
689
690 let msg: SamplingMessage = serde_json::from_str(json).unwrap();
691 assert_eq!(msg.role, "user");
692 match &msg.content {
693 SamplingContent::Text { text } => assert_eq!(text, "What is 2+2?"),
694 _ => panic!("expected text content"),
695 }
696 }
697
698 #[test]
699 fn model_preferences_empty_hints_omitted() {
700 let prefs = ModelPreferences {
701 hints: vec![],
702 cost_priority: Some(0.5),
703 speed_priority: None,
704 intelligence_priority: None,
705 };
706
707 let json = serde_json::to_string(&prefs).unwrap();
708 assert!(!json.contains("hints"));
709 assert!(json.contains("costPriority"));
710 }
711
712 #[test]
713 fn llm_sampling_handler_is_send_sync() {
714 fn require_send_sync<T: Send + Sync>() {}
715 require_send_sync::<LlmSamplingHandler>();
716 }
717
718 #[test]
719 fn sampling_request_to_llm_request_preserves_messages() {
720 let request = SamplingRequest {
721 messages: vec![
722 SamplingMessage::new("user", SamplingContent::text("Hello")),
723 SamplingMessage::new("assistant", SamplingContent::text("Hi there")),
724 SamplingMessage::new("user", SamplingContent::text("How are you?")),
725 ],
726 system_prompt: None,
727 model_preferences: None,
728 max_tokens: None,
729 temperature: None,
730 };
731
732 let llm_req = sampling_request_to_llm_request(&request, "test-model");
733
734 assert_eq!(llm_req.contents.len(), 3);
736 assert_eq!(llm_req.contents[0].role, "user");
737 assert_eq!(llm_req.contents[1].role, "model"); assert_eq!(llm_req.contents[2].role, "user");
739
740 match &llm_req.contents[0].parts[0] {
742 Part::Text { text } => assert_eq!(text, "Hello"),
743 _ => panic!("expected text part"),
744 }
745 }
746
747 #[test]
748 fn sampling_request_to_llm_request_preserves_system_prompt() {
749 let request = SamplingRequest {
750 messages: vec![SamplingMessage::new("user", SamplingContent::text("Hi"))],
751 system_prompt: Some("You are a helpful assistant.".to_string()),
752 model_preferences: None,
753 max_tokens: None,
754 temperature: None,
755 };
756
757 let llm_req = sampling_request_to_llm_request(&request, "test-model");
758
759 assert_eq!(llm_req.contents.len(), 2);
761 assert_eq!(llm_req.contents[0].role, "system");
762 match &llm_req.contents[0].parts[0] {
763 Part::Text { text } => assert_eq!(text, "You are a helpful assistant."),
764 _ => panic!("expected text part"),
765 }
766 }
767
768 #[test]
769 fn sampling_request_to_llm_request_preserves_config() {
770 let request = SamplingRequest {
771 messages: vec![],
772 system_prompt: None,
773 model_preferences: None,
774 max_tokens: Some(500),
775 temperature: Some(0.7),
776 };
777
778 let llm_req = sampling_request_to_llm_request(&request, "test-model");
779
780 let config = llm_req.config.unwrap();
781 assert_eq!(config.max_output_tokens, Some(500));
782 assert!((config.temperature.unwrap() - 0.7f32).abs() < 0.001);
784 }
785
786 #[test]
787 fn llm_response_to_sampling_response_preserves_text() {
788 use adk_core::model::{FinishReason, LlmResponse};
789
790 let llm_resp = LlmResponse {
791 content: Some(Content::new("model").with_text("The answer is 42.")),
792 finish_reason: Some(FinishReason::Stop),
793 ..Default::default()
794 };
795
796 let sampling_resp = llm_response_to_sampling_response(llm_resp, "gemini-2.0-flash");
797
798 assert_eq!(sampling_resp.model, "gemini-2.0-flash");
799 assert_eq!(sampling_resp.stop_reason, "endTurn");
800 match &sampling_resp.content {
801 SamplingContent::Text { text } => assert_eq!(text, "The answer is 42."),
802 _ => panic!("expected text content"),
803 }
804 }
805
806 #[test]
807 fn llm_response_to_sampling_response_maps_finish_reasons() {
808 use adk_core::model::{FinishReason, LlmResponse};
809
810 let cases = vec![
811 (Some(FinishReason::Stop), "endTurn"),
812 (Some(FinishReason::MaxTokens), "maxTokens"),
813 (Some(FinishReason::Safety), "safety"),
814 (Some(FinishReason::Recitation), "recitation"),
815 (Some(FinishReason::Refusal), "refusal"),
816 (Some(FinishReason::MalformedToolCall), "malformedToolCall"),
817 (Some(FinishReason::Other), "other"),
818 (None, "endTurn"),
819 ];
820
821 for (finish_reason, expected_stop) in cases {
822 let llm_resp = LlmResponse {
823 content: Some(Content::new("model").with_text("test")),
824 finish_reason,
825 ..Default::default()
826 };
827 let sampling_resp = llm_response_to_sampling_response(llm_resp, "model");
828 assert_eq!(sampling_resp.stop_reason, expected_stop);
829 }
830 }
831
832 #[test]
833 fn llm_response_to_sampling_response_empty_content() {
834 use adk_core::model::LlmResponse;
835
836 let llm_resp = LlmResponse { content: None, ..Default::default() };
837 let sampling_resp = llm_response_to_sampling_response(llm_resp, "model");
838
839 match &sampling_resp.content {
840 SamplingContent::Text { text } => assert_eq!(text, ""),
841 _ => panic!("expected empty text content"),
842 }
843 }
844}