use serde::{Deserialize, Serialize};
use crate::perf::TokenUsage;
use super::request::ToolCall;
use super::usage::UsageBlock;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantMessage {
pub content: Option<String>,
#[serde(default)]
pub tool_calls: Vec<ToolCall>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChoice {
pub message: AssistantMessage,
pub finish_reason: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatResponse {
pub id: String,
#[serde(default)]
pub model: String,
pub choices: Vec<ChatChoice>,
#[serde(default)]
pub usage: UsageBlock,
}
impl ChatResponse {
pub fn first_text(&self) -> Option<String> {
self.choices.first()?.message.content.clone()
}
pub fn first_tool_calls(&self) -> &[ToolCall] {
self.choices
.first()
.map(|c| c.message.tool_calls.as_slice())
.unwrap_or(&[])
}
pub fn finish_reason(&self) -> Option<&str> {
self.choices.first()?.finish_reason.as_deref()
}
pub fn token_usage(self) -> TokenUsage {
self.usage.into_token_usage()
}
pub fn resolved_model<'a>(&'a self, requested: &'a str) -> &'a str {
if self.model.is_empty() {
requested
} else {
&self.model
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chat_response_deserialises_fixture() {
let fixture = r#"{
"id": "gen-abc123",
"choices": [
{
"message": {
"role": "assistant",
"content": "Hello, world!",
"tool_calls": []
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 4,
"total_tokens": 14
}
}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise fixture");
assert_eq!(resp.id, "gen-abc123");
assert_eq!(resp.first_text().as_deref(), Some("Hello, world!"));
assert_eq!(resp.finish_reason(), Some("stop"));
assert!(resp.first_tool_calls().is_empty());
}
#[test]
fn tool_call_deserialises_from_fixture() {
let fixture = r#"{
"id": "gen-xyz",
"choices": [
{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_001",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"Seattle\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 15,
"total_tokens": 40
}
}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
assert!(resp.first_text().is_none());
let calls = resp.first_tool_calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].id, "call_001");
assert_eq!(calls[0].function.name, "get_weather");
assert_eq!(resp.finish_reason(), Some("tool_calls"));
}
#[test]
fn chat_response_usage_into_token_usage() {
let fixture = r#"{
"id": "gen-zzz",
"choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 8, "completion_tokens": 3, "total_tokens": 11,
"cache_read_input_tokens": 5, "cache_creation_input_tokens": 2}
}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
let usage = resp.token_usage();
assert_eq!(usage.prompt_tokens, 8);
assert_eq!(usage.completion_tokens, 3);
assert_eq!(usage.cache_read_tokens, 5);
assert_eq!(usage.cache_creation_tokens, 2);
}
#[test]
fn chat_response_first_text_content_empty_choices() {
let fixture = r#"{"id":"x","choices":[],"usage":{}}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
assert!(resp.first_text().is_none());
assert!(resp.first_tool_calls().is_empty());
assert!(resp.finish_reason().is_none());
}
#[test]
fn resolved_model_prefers_response_model_over_requested() {
let fixture =
r#"{"id":"x","model":"openai/gpt-4o-mini-2024-07-18","choices":[],"usage":{}}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
assert_eq!(
resp.resolved_model("openai/gpt-4o-mini"),
"openai/gpt-4o-mini-2024-07-18"
);
}
#[test]
fn resolved_model_falls_back_to_requested_when_absent() {
let fixture = r#"{"id":"x","choices":[],"usage":{}}"#;
let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
assert_eq!(
resp.resolved_model("openai/gpt-4o-mini"),
"openai/gpt-4o-mini"
);
}
}