use crate::schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
use crate::{Result, types::Content};
use async_trait::async_trait;
use futures::stream::Stream;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
pub type LlmResponseStream = Pin<Box<dyn Stream<Item = Result<LlmResponse>> + Send>>;
#[async_trait]
pub trait Llm: Send + Sync {
fn name(&self) -> &str;
async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream>;
async fn generate_content_metered(
&self,
scope: &crate::ModelCallScope,
req: LlmRequest,
stream: bool,
) -> Result<LlmResponseStream> {
scope.generate_one_call(self, req, stream).await
}
fn schema_adapter(&self) -> &dyn SchemaAdapter {
&GenericSchemaAdapter
}
fn uses_interactions_api(&self) -> bool {
false
}
fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
let _ = request;
None
}
fn context_window(&self) -> Option<u64> {
None
}
fn native_web_search(&self) -> Option<NativeWebSearch> {
None
}
fn native_compaction(&self) -> Option<NativeCompaction> {
None
}
async fn prewarm(&self) -> Result<()> {
Ok(())
}
fn data_locality(&self) -> DataLocality {
DataLocality::Remote
}
fn data_destinations(&self) -> Vec<DataDestination> {
Vec::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DataDestination {
pub provider: String,
pub hosts: Vec<String>,
}
impl DataDestination {
pub fn new(
provider: impl Into<String>,
hosts: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self { provider: provider.into(), hosts: hosts.into_iter().map(Into::into).collect() }
}
pub fn of_url(provider: impl Into<String>, url: &str) -> Self {
let host = url::Url::parse(url.trim()).ok().and_then(|parsed| {
let host = parsed.host_str()?.trim_end_matches('.').to_ascii_lowercase();
Some(match parsed.port_or_known_default() {
Some(443) | None => host,
Some(port) => format!("{host}:{port}"),
})
});
Self { provider: provider.into(), hosts: host.into_iter().collect() }
}
pub fn all_hosts(destinations: &[DataDestination]) -> Vec<String> {
let mut hosts: Vec<String> = Vec::new();
for host in destinations.iter().flat_map(|d| d.hosts.iter()) {
if !hosts.contains(host) {
hosts.push(host.clone());
}
}
hosts
}
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum DataLocality {
InProcess,
Loopback,
#[default]
Remote,
}
impl DataLocality {
pub fn of_url(url: &str) -> Self {
let Ok(parsed) = url::Url::parse(url.trim()) else {
return Self::Remote;
};
let loopback = match parsed.host() {
Some(url::Host::Domain(domain)) => {
let domain = domain.trim_end_matches('.').to_ascii_lowercase();
domain == "localhost" || domain.ends_with(".localhost")
}
Some(url::Host::Ipv4(address)) => address.is_loopback(),
Some(url::Host::Ipv6(address)) => {
address.is_loopback()
|| address.to_ipv4_mapped().is_some_and(|mapped| mapped.is_loopback())
}
None => false,
};
if loopback { Self::Loopback } else { Self::Remote }
}
pub fn least_local(localities: impl IntoIterator<Item = DataLocality>) -> Self {
localities.into_iter().max().unwrap_or(Self::Remote)
}
pub fn leaves_machine(self) -> bool {
self == Self::Remote
}
pub fn leaves_process(self) -> bool {
self != Self::InProcess
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ToolDeclarations {
entries: Vec<(String, serde_json::Value)>,
}
impl ToolDeclarations {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn insert(
&mut self,
name: String,
declaration: serde_json::Value,
) -> Option<serde_json::Value> {
match self.entries.iter_mut().find(|(existing, _)| *existing == name) {
Some((_, slot)) => Some(std::mem::replace(slot, declaration)),
None => {
self.entries.push((name, declaration));
None
}
}
}
pub fn get(&self, name: &str) -> Option<&serde_json::Value> {
self.entries.iter().find(|(existing, _)| existing == name).map(|(_, value)| value)
}
pub fn get_mut(&mut self, name: &str) -> Option<&mut serde_json::Value> {
self.entries.iter_mut().find(|(existing, _)| existing == name).map(|(_, value)| value)
}
pub fn contains_key(&self, name: &str) -> bool {
self.get(name).is_some()
}
pub fn remove(&mut self, name: &str) -> Option<serde_json::Value> {
let index = self.entries.iter().position(|(existing, _)| existing == name)?;
Some(self.entries.remove(index).1)
}
pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut serde_json::Value) -> bool) {
self.entries.retain_mut(|(name, value)| keep(name, value));
}
pub fn iter(&self) -> ToolDeclarationsIter<'_> {
self.entries.iter().map(|(name, value)| (name, value))
}
pub fn keys(&self) -> ToolDeclarationsKeys<'_> {
ToolDeclarationsKeys { entries: self.entries.iter() }
}
pub fn values(&self) -> ToolDeclarationsValues<'_> {
ToolDeclarationsValues { entries: self.entries.iter() }
}
}
#[derive(Clone)]
pub struct ToolDeclarationsKeys<'a> {
entries: std::slice::Iter<'a, (String, serde_json::Value)>,
}
impl<'a> Iterator for ToolDeclarationsKeys<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<&'a String> {
self.entries.next().map(|(name, _)| name)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.entries.size_hint()
}
}
impl DoubleEndedIterator for ToolDeclarationsKeys<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.entries.next_back().map(|(name, _)| name)
}
}
impl ExactSizeIterator for ToolDeclarationsKeys<'_> {}
impl std::fmt::Debug for ToolDeclarationsKeys<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
#[derive(Clone)]
pub struct ToolDeclarationsValues<'a> {
entries: std::slice::Iter<'a, (String, serde_json::Value)>,
}
impl<'a> Iterator for ToolDeclarationsValues<'a> {
type Item = &'a serde_json::Value;
fn next(&mut self) -> Option<&'a serde_json::Value> {
self.entries.next().map(|(_, value)| value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.entries.size_hint()
}
}
impl DoubleEndedIterator for ToolDeclarationsValues<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.entries.next_back().map(|(_, value)| value)
}
}
impl ExactSizeIterator for ToolDeclarationsValues<'_> {}
impl std::fmt::Debug for ToolDeclarationsValues<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub type ToolDeclarationsIter<'a> = std::iter::Map<
std::slice::Iter<'a, (String, serde_json::Value)>,
fn(&'a (String, serde_json::Value)) -> (&'a String, &'a serde_json::Value),
>;
impl std::ops::Index<&str> for ToolDeclarations {
type Output = serde_json::Value;
fn index(&self, name: &str) -> &serde_json::Value {
self.get(name).unwrap_or_else(|| panic!("tool {name} is not declared"))
}
}
impl<'a> IntoIterator for &'a ToolDeclarations {
type Item = (&'a String, &'a serde_json::Value);
type IntoIter = ToolDeclarationsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for ToolDeclarations {
type Item = (String, serde_json::Value);
type IntoIter = std::vec::IntoIter<(String, serde_json::Value)>;
fn into_iter(self) -> Self::IntoIter {
self.entries.into_iter()
}
}
impl<K: Into<String>> FromIterator<(K, serde_json::Value)> for ToolDeclarations {
fn from_iter<I: IntoIterator<Item = (K, serde_json::Value)>>(iter: I) -> Self {
let mut tools = Self::new();
tools.extend(iter);
tools
}
}
impl<K: Into<String>> Extend<(K, serde_json::Value)> for ToolDeclarations {
fn extend<I: IntoIterator<Item = (K, serde_json::Value)>>(&mut self, iter: I) {
for (name, declaration) in iter {
self.insert(name.into(), declaration);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmRequest {
pub model: String,
pub contents: Vec<Content>,
pub config: Option<GenerateContentConfig>,
#[serde(skip)]
pub tools: ToolDeclarations,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub previous_response_id: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
Low,
Medium,
High,
}
impl Effort {
pub const ALL: [Effort; 3] = [Effort::Low, Effort::Medium, Effort::High];
pub const fn as_str(self) -> &'static str {
match self {
Effort::Low => "low",
Effort::Medium => "medium",
Effort::High => "high",
}
}
}
impl std::fmt::Display for Effort {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for Effort {
type Err = String;
fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().as_str() {
"low" => Ok(Effort::Low),
"medium" => Ok(Effort::Medium),
"high" => Ok(Effort::High),
other => Err(format!("unknown effort '{other}'; use low, medium or high")),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GenerateContentConfig {
pub temperature: Option<f32>,
pub top_p: Option<f32>,
pub top_k: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub frequency_penalty: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub presence_penalty: Option<f32>,
pub max_output_tokens: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub seed: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub top_logprobs: Option<u8>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stop_sequences: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_schema: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub response_modalities: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub cached_content: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effort: Option<Effort>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub extensions: serde_json::Map<String, serde_json::Value>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LlmResponse {
pub content: Option<Content>,
pub usage_metadata: Option<UsageMetadata>,
pub finish_reason: Option<FinishReason>,
#[serde(skip_serializing_if = "Option::is_none")]
pub citation_metadata: Option<CitationMetadata>,
pub partial: bool,
pub turn_complete: bool,
pub interrupted: bool,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub provider_metadata: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub interaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub provider: Option<String>,
}
#[async_trait]
pub trait CacheCapable: Send + Sync {
async fn create_cache(
&self,
system_instruction: &str,
tools: &ToolDeclarations,
ttl_seconds: u32,
) -> Result<String>;
async fn delete_cache(&self, name: &str) -> Result<()>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextCacheConfig {
pub min_tokens: u32,
pub ttl_seconds: u32,
pub cache_intervals: u32,
}
impl Default for ContextCacheConfig {
fn default() -> Self {
Self { min_tokens: 4096, ttl_seconds: 600, cache_intervals: 3 }
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UsageMetadata {
pub prompt_token_count: i32,
pub candidates_token_count: i32,
pub total_token_count: i32,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub cache_read_input_token_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub cache_creation_input_token_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub thinking_token_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub audio_input_token_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub audio_output_token_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub cost: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub is_byok: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub provider_usage: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub builtin_tool_uses: Vec<BuiltinToolUse>,
}
impl UsageMetadata {
pub fn builtin_tool_use_count(&self) -> u64 {
self.builtin_tool_uses.iter().map(|used| u64::from(used.count)).sum()
}
}
pub fn nullable_count<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: Deserialize<'de> + Default,
{
Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuiltinToolUse {
pub kind: String,
pub count: u32,
}
impl BuiltinToolUse {
pub fn new(kind: impl Into<String>, count: u32) -> Self {
Self { kind: kind.into(), count }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NativeWebSearchTool {
GoogleSearch,
AnthropicWebSearch,
OpenAiWebSearch,
DeepSeekWebSearch,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct NativeWebSearch {
pub provider: &'static str,
pub tool: NativeWebSearchTool,
pub allowed_domains: bool,
}
impl NativeWebSearch {
pub fn new(provider: &'static str, tool: NativeWebSearchTool, allowed_domains: bool) -> Self {
Self { provider, tool, allowed_domains }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct NativeCompaction {
pub provider: &'static str,
pub keeps_thinking: bool,
}
impl NativeCompaction {
pub fn new(provider: &'static str) -> Self {
Self { provider, keeps_thinking: false }
}
pub fn keeping_thinking(mut self) -> Self {
self.keeps_thinking = true;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationMetadata {
#[serde(default)]
pub citation_sources: Vec<CitationSource>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationSource {
pub uri: Option<String>,
pub title: Option<String>,
pub start_index: Option<i32>,
pub end_index: Option<i32>,
pub license: Option<String>,
pub publication_date: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum FinishReason {
Stop,
MaxTokens,
Safety,
Recitation,
Refusal,
MalformedToolCall,
#[serde(other)]
Other,
}
impl LlmRequest {
pub fn new(model: impl Into<String>, contents: Vec<Content>) -> Self {
Self {
model: model.into(),
contents,
config: None,
tools: ToolDeclarations::new(),
previous_response_id: None,
}
}
pub fn with_response_schema(mut self, schema: serde_json::Value) -> Self {
let config = self.config.get_or_insert(GenerateContentConfig::default());
config.response_schema = Some(schema);
self
}
pub fn with_config(mut self, config: GenerateContentConfig) -> Self {
self.config = Some(config);
self
}
}
impl LlmResponse {
pub fn new(content: Content) -> Self {
Self {
content: Some(content),
usage_metadata: None,
finish_reason: Some(FinishReason::Stop),
citation_metadata: None,
partial: false,
turn_complete: true,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_loopback_host_is_loopback_and_every_other_host_remote() {
for url in [
"http://localhost:11434",
"http://LOCALHOST.:8000/v1",
"http://vllm.localhost/v1",
"http://127.0.0.1:1234/v1",
"http://127.8.9.10",
"http://[::1]:8080",
"http://[::ffff:127.0.0.1]:8080",
" https://localhost/v1/ ",
] {
assert_eq!(DataLocality::of_url(url), DataLocality::Loopback, "{url}");
}
for url in [
"https://api.openai.com/v1",
"http://localhost.example.com",
"http://0.0.0.0:11434",
"http://10.0.0.5:11434",
"http://[::2]",
"localhost:11434",
"not a url",
"",
] {
assert_eq!(DataLocality::of_url(url), DataLocality::Remote, "{url}");
}
}
#[test]
fn the_least_local_of_several_localities_wins() {
use DataLocality::{InProcess, Loopback, Remote};
assert_eq!(DataLocality::least_local([InProcess, InProcess]), InProcess);
assert_eq!(DataLocality::least_local([InProcess, Loopback]), Loopback);
assert_eq!(DataLocality::least_local([Loopback, Remote, InProcess]), Remote);
assert_eq!(DataLocality::least_local([]), Remote);
assert_eq!(DataLocality::default(), Remote);
assert!(Remote.leaves_machine() && Remote.leaves_process());
assert!(!Loopback.leaves_machine() && Loopback.leaves_process());
assert!(!InProcess.leaves_machine() && !InProcess.leaves_process());
for locality in [InProcess, Loopback, Remote] {
let wire = serde_json::to_value(locality).unwrap();
assert_eq!(serde_json::from_value::<DataLocality>(wire).unwrap(), locality);
}
}
#[test]
fn a_metered_model_reports_the_wrapped_models_locality() {
struct Local;
#[async_trait]
impl Llm for Local {
fn name(&self) -> &str {
"local"
}
async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
Ok(Box::pin(futures::stream::empty()))
}
fn data_locality(&self) -> DataLocality {
DataLocality::InProcess
}
fn data_destinations(&self) -> Vec<DataDestination> {
vec![DataDestination::new("local", ["127.0.0.1:8080"])]
}
}
let metered = crate::MeteredLlm::new(std::sync::Arc::new(Local));
assert_eq!(metered.data_locality(), DataLocality::InProcess);
assert_eq!(
metered.data_destinations(),
vec![DataDestination::new("local", ["127.0.0.1:8080"])]
);
}
#[test]
fn a_destination_names_the_endpoint_host_and_any_port_but_443() {
for (url, host) in [
("https://api.anthropic.com", "api.anthropic.com"),
("https://API.OpenAI.com./v1", "api.openai.com"),
(
"https://bedrock-runtime.eu-west-1.amazonaws.com:443/x",
"bedrock-runtime.eu-west-1.amazonaws.com",
),
("http://localhost:11434", "localhost:11434"),
("http://gpu-box/v1", "gpu-box:80"),
("https://nim.internal:8443/v1", "nim.internal:8443"),
("http://[::1]:8000/v1", "[::1]:8000"),
] {
assert_eq!(
DataDestination::of_url("p", url),
DataDestination::new("p", [host]),
"{url}"
);
}
for url in ["not a url", "", "data:text/plain,x"] {
assert!(DataDestination::of_url("p", url).hosts.is_empty(), "{url}");
}
}
#[test]
fn a_model_that_does_not_say_has_no_destination() {
struct Silent;
#[async_trait]
impl Llm for Silent {
fn name(&self) -> &str {
"silent"
}
async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
Ok(Box::pin(futures::stream::empty()))
}
}
assert!(Silent.data_destinations().is_empty());
}
#[test]
fn tool_names_and_declarations_print_as_lists() {
let tools: ToolDeclarations = [
("search", serde_json::json!({"name": "search"})),
("add", serde_json::json!({"name": "add"})),
]
.into_iter()
.collect();
assert_eq!(format!("{:?}", tools.keys()), r#"["search", "add"]"#);
assert_eq!(
format!("{:?}", tools.values()),
r#"[Object {"name": String("search")}, Object {"name": String("add")}]"#
);
assert_eq!(tools.keys().len(), 2);
assert_eq!(tools.keys().next_back().map(String::as_str), Some("add"));
}
#[test]
fn test_llm_request_creation() {
let req = LlmRequest::new("test-model", vec![]);
assert_eq!(req.model, "test-model");
assert!(req.contents.is_empty());
}
#[test]
fn test_llm_request_with_response_schema() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string" }
}
});
let req = LlmRequest::new("test-model", vec![]).with_response_schema(schema.clone());
assert!(req.config.is_some());
let config = req.config.unwrap();
assert!(config.response_schema.is_some());
assert_eq!(config.response_schema.unwrap(), schema);
}
#[test]
fn test_llm_request_with_config() {
let config = GenerateContentConfig {
temperature: Some(0.7),
top_p: Some(0.9),
top_k: Some(40),
frequency_penalty: Some(0.2),
presence_penalty: Some(-0.3),
max_output_tokens: Some(1024),
seed: Some(42),
top_logprobs: Some(5),
stop_sequences: vec!["END".to_string()],
..Default::default()
};
let req = LlmRequest::new("test-model", vec![]).with_config(config);
assert!(req.config.is_some());
let config = req.config.unwrap();
assert_eq!(config.temperature, Some(0.7));
assert_eq!(config.max_output_tokens, Some(1024));
assert_eq!(config.frequency_penalty, Some(0.2));
assert_eq!(config.presence_penalty, Some(-0.3));
assert_eq!(config.seed, Some(42));
assert_eq!(config.top_logprobs, Some(5));
assert_eq!(config.stop_sequences, vec!["END"]);
}
#[test]
fn test_llm_response_creation() {
let content = Content::new("assistant");
let resp = LlmResponse::new(content);
assert!(resp.content.is_some());
assert!(resp.turn_complete);
assert!(!resp.partial);
assert_eq!(resp.finish_reason, Some(FinishReason::Stop));
assert!(resp.citation_metadata.is_none());
assert!(resp.provider_metadata.is_none());
}
#[test]
fn test_llm_response_deserialize_without_citations() {
let json = serde_json::json!({
"content": {
"role": "model",
"parts": [{"text": "hello"}]
},
"partial": false,
"turn_complete": true,
"interrupted": false
});
let response: LlmResponse = serde_json::from_value(json).expect("should deserialize");
assert!(response.citation_metadata.is_none());
}
#[test]
fn test_llm_response_roundtrip_with_citations() {
let response = LlmResponse {
content: Some(Content::new("model").with_text("hello")),
usage_metadata: None,
finish_reason: Some(FinishReason::Stop),
citation_metadata: Some(CitationMetadata {
citation_sources: vec![CitationSource {
uri: Some("https://example.com".to_string()),
title: Some("Example".to_string()),
start_index: Some(0),
end_index: Some(5),
license: None,
publication_date: Some("2026-01-01T00:00:00Z".to_string()),
}],
}),
partial: false,
turn_complete: true,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
};
let encoded = serde_json::to_string(&response).expect("serialize");
let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded.citation_metadata, response.citation_metadata);
}
#[test]
fn test_generate_content_config_roundtrip_with_extensions() {
let mut extensions = serde_json::Map::new();
extensions.insert(
"openrouter".to_string(),
serde_json::json!({
"provider": {
"zdr": true,
"order": ["openai", "anthropic"]
},
"plugins": [
{ "id": "web", "enabled": true }
]
}),
);
let config = GenerateContentConfig {
temperature: Some(0.4),
top_p: Some(0.8),
top_k: Some(12),
frequency_penalty: Some(0.1),
presence_penalty: Some(0.2),
max_output_tokens: Some(512),
seed: Some(7),
top_logprobs: Some(3),
stop_sequences: vec!["STOP".to_string(), "DONE".to_string()],
response_schema: Some(serde_json::json!({
"type": "object",
"properties": { "answer": { "type": "string" } },
"required": ["answer"]
})),
response_modalities: Some(vec!["TEXT".to_string(), "IMAGE".to_string()]),
cached_content: Some("cachedContents/abc123".to_string()),
effort: Some(Effort::Medium),
extensions,
};
let encoded = serde_json::to_string(&config).expect("serialize");
let decoded: GenerateContentConfig = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded.temperature, config.temperature);
assert_eq!(decoded.top_p, config.top_p);
assert_eq!(decoded.top_k, config.top_k);
assert_eq!(decoded.frequency_penalty, config.frequency_penalty);
assert_eq!(decoded.presence_penalty, config.presence_penalty);
assert_eq!(decoded.max_output_tokens, config.max_output_tokens);
assert_eq!(decoded.seed, config.seed);
assert_eq!(decoded.top_logprobs, config.top_logprobs);
assert_eq!(decoded.stop_sequences, config.stop_sequences);
assert_eq!(decoded.response_schema, config.response_schema);
assert_eq!(decoded.cached_content, config.cached_content);
assert_eq!(decoded.extensions, config.extensions);
assert_eq!(decoded.response_modalities, config.response_modalities);
assert_eq!(decoded.effort, config.effort);
}
#[test]
fn a_config_without_effort_reads_and_writes_as_before() {
let legacy: GenerateContentConfig =
serde_json::from_value(serde_json::json!({ "temperature": 0.2 })).unwrap();
assert_eq!(legacy.effort, None);
assert_eq!(serde_json::to_value(&legacy).unwrap().get("effort"), None);
let set: GenerateContentConfig =
serde_json::from_value(serde_json::json!({ "effort": "low" })).unwrap();
assert_eq!(set.effort, Some(Effort::Low));
}
#[test]
fn test_llm_response_and_usage_roundtrip_with_provider_metadata() {
let response = LlmResponse {
content: Some(Content::new("model").with_text("hello")),
usage_metadata: Some(UsageMetadata {
prompt_token_count: 10,
candidates_token_count: 20,
total_token_count: 30,
cache_read_input_token_count: Some(5),
cache_creation_input_token_count: Some(2),
thinking_token_count: Some(3),
audio_input_token_count: Some(4),
audio_output_token_count: Some(6),
cost: Some(0.0125),
is_byok: Some(true),
provider_usage: Some(serde_json::json!({
"server_tool_use": {
"web_search_requests": 1
},
"prompt_tokens_details": {
"video_tokens": 8
}
})),
builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 1)],
}),
finish_reason: Some(FinishReason::Stop),
citation_metadata: None,
partial: false,
turn_complete: true,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: Some(serde_json::json!({
"openrouter": {
"responseId": "resp_123",
"outputItems": 2
}
})),
interaction_id: None,
model: None,
provider: None,
};
let encoded = serde_json::to_string(&response).expect("serialize");
let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded.provider_metadata, response.provider_metadata);
assert_eq!(
decoded.usage_metadata.as_ref().and_then(|u| u.cost),
response.usage_metadata.as_ref().and_then(|u| u.cost),
);
assert_eq!(
decoded.usage_metadata.as_ref().and_then(|u| u.is_byok),
response.usage_metadata.as_ref().and_then(|u| u.is_byok),
);
assert_eq!(
decoded.usage_metadata.as_ref().map(|u| u.builtin_tool_uses.clone()),
Some(vec![BuiltinToolUse::new("web_search", 1)]),
);
assert_eq!(
decoded.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
response.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
);
}
#[test]
fn test_finish_reason() {
assert_eq!(FinishReason::Stop, FinishReason::Stop);
assert_ne!(FinishReason::Stop, FinishReason::MaxTokens);
}
#[test]
fn finish_reason_wire_names_are_stable() {
let names = [
(FinishReason::Stop, "Stop"),
(FinishReason::MaxTokens, "MaxTokens"),
(FinishReason::Safety, "Safety"),
(FinishReason::Recitation, "Recitation"),
(FinishReason::Refusal, "Refusal"),
(FinishReason::MalformedToolCall, "MalformedToolCall"),
(FinishReason::Other, "Other"),
];
for (reason, name) in names {
assert_eq!(serde_json::to_value(reason).unwrap(), serde_json::json!(name));
assert_eq!(
serde_json::from_value::<FinishReason>(serde_json::json!(name)).unwrap(),
reason
);
}
assert_eq!(
serde_json::from_value::<FinishReason>(serde_json::json!("ReasonFromALaterRelease"))
.unwrap(),
FinishReason::Other
);
}
#[test]
fn a_persisted_response_still_loads() {
let stored = serde_json::json!({
"content": null,
"usage_metadata": null,
"finish_reason": "Safety",
"partial": false,
"turn_complete": true,
"interrupted": false,
"error_code": null,
"error_message": null
});
let response: LlmResponse = serde_json::from_value(stored).unwrap();
assert_eq!(response.finish_reason, Some(FinishReason::Safety));
}
}