use std::collections::HashSet;
use crate::attachment;
use adk_core::{Content, FinishReason, LlmResponse, Part, UsageMetadata};
use ollama_rs::generation::chat::{ChatMessage, ChatMessageResponse};
use ollama_rs::generation::images::Image;
use serde_json::Value;
fn is_native_image(mime_type: &str) -> bool {
let mime_type = mime_type.split(';').next().unwrap_or_default().trim();
["image/png", "image/jpeg", "image/jpg", "image/gif"]
.iter()
.any(|native| mime_type.eq_ignore_ascii_case(native))
}
pub fn content_to_chat_message(content: &Content) -> Option<ChatMessage> {
let mut texts = Vec::new();
let mut images = Vec::new();
for part in &content.parts {
match part {
Part::Text { text } => texts.push(text.clone()),
Part::Thinking { thinking, .. } => texts.push(thinking.clone()),
Part::InlineData { mime_type, data, .. } if is_native_image(mime_type) => {
images.push(Image::from_base64(attachment::encode_base64(data)));
}
Part::InlineData { mime_type, data, .. } => {
texts.push(attachment::inline_attachment_to_text(mime_type, data));
}
Part::FileData { mime_type, file_uri, .. } => {
texts.push(attachment::file_attachment_to_text(mime_type, file_uri));
}
_ => {}
}
}
let text = texts.join("\n");
let with_images = |message: ChatMessage| {
if images.is_empty() { message } else { message.with_images(images.clone()) }
};
match content.role.as_str() {
"user" => Some(with_images(ChatMessage::user(text))),
"model" | "assistant" => Some(with_images(ChatMessage::assistant(text))),
"system" => Some(with_images(ChatMessage::system(text))),
"function" | "tool" => {
let mut response_texts = Vec::new();
for part in &content.parts {
if let Part::FunctionResponse { function_response, .. } = part {
response_texts.push(format!(
"{}: {}",
function_response.name,
crate::tool_result::serialize_tool_result(&function_response.response)
));
}
}
if !response_texts.is_empty() {
Some(ChatMessage::tool(response_texts.join("\n")))
} else if !text.is_empty() {
Some(ChatMessage::tool(text))
} else {
None
}
}
_ => None,
}
}
const METRICS: [&str; 6] = [
"total_duration",
"load_duration",
"prompt_eval_count",
"prompt_eval_duration",
"eval_count",
"eval_duration",
];
pub fn usage(line: &Value) -> Option<UsageMetadata> {
use crate::usage_json::count;
let object = line.as_object()?;
let metrics: serde_json::Map<String, Value> = METRICS
.iter()
.filter_map(|key| Some(((*key).to_string(), object.get(*key)?.clone())))
.collect();
let prompt = count(line, "/prompt_eval_count").unwrap_or_default();
let output = count(line, "/eval_count").unwrap_or_default();
Some(UsageMetadata {
prompt_token_count: prompt,
candidates_token_count: output,
total_token_count: prompt.saturating_add(output),
provider_usage: (!metrics.is_empty()).then_some(Value::Object(metrics)),
..Default::default()
})
}
fn finish_reason(line: &Value) -> FinishReason {
match line.get("done_reason").and_then(Value::as_str) {
None | Some("stop") => FinishReason::Stop,
Some("length") => FinishReason::MaxTokens,
Some(_) => FinishReason::Other,
}
}
pub fn chat_response_to_llm_response(
response: &ChatMessageResponse,
line: &Value,
partial: bool,
declared_tools: &HashSet<String>,
) -> LlmResponse {
let mut parts = Vec::new();
if let Some(thinking) = &response.message.thinking
&& !thinking.is_empty()
{
parts.push(Part::Thinking { thinking: thinking.clone(), signature: None });
}
if !response.message.content.is_empty() {
if response.message.tool_calls.is_empty() {
if let Some(parsed_parts) = crate::tool_call_parser::parse_declared_tool_calls(
&response.message.content,
declared_tools,
) {
parts.extend(parsed_parts);
} else {
parts.push(Part::Text { text: response.message.content.clone() });
}
} else {
parts.push(Part::Text { text: response.message.content.clone() });
}
}
for tool_call in &response.message.tool_calls {
parts.push(Part::FunctionCall {
name: tool_call.function.name.clone(),
args: tool_call.function.arguments.clone(),
id: None, thought_signature: None,
});
}
let content =
if parts.is_empty() { None } else { Some(Content { role: "model".to_string(), parts }) };
let finish_reason = response.done.then(|| finish_reason(line));
let usage_metadata = if response.done { usage(line) } else { None };
LlmResponse {
content,
usage_metadata,
finish_reason,
citation_metadata: None,
partial,
turn_complete: response.done,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
}
}
pub fn take_logprobs(line: &mut Value) -> Vec<Value> {
match line.as_object_mut().and_then(|line| line.remove("logprobs")) {
Some(Value::Array(entries)) => entries,
Some(_) | None => Vec::new(),
}
}
pub fn logprobs_metadata(logprobs: Vec<Value>) -> Option<Value> {
(!logprobs.is_empty()).then(|| serde_json::json!({"logprobs": {"content": logprobs}}))
}
pub fn part_delta_response(part: Part) -> LlmResponse {
LlmResponse {
content: Some(Content { role: "model".to_string(), parts: vec![part] }),
usage_metadata: None,
finish_reason: None,
citation_metadata: None,
partial: true,
turn_complete: false,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
}
}
pub fn thinking_delta_response(thinking: &str) -> LlmResponse {
LlmResponse {
content: Some(Content {
role: "model".to_string(),
parts: vec![Part::Thinking { thinking: thinking.to_string(), signature: None }],
}),
usage_metadata: None,
finish_reason: None,
citation_metadata: None,
partial: true,
turn_complete: false,
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 content_to_chat_message_keeps_inline_attachment_payload() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::inline_data("application/pdf", b"%PDF".to_vec())],
};
let message = content_to_chat_message(&content).expect("message should be created");
assert!(message.content.contains("application/pdf"));
assert!(message.content.contains("encoding=\"base64\""));
}
#[test]
fn images_go_out_as_native_images_and_other_attachments_as_text() {
let png = vec![0x89, b'P', b'N', b'G', 1, 2, 3];
let jpeg = vec![0xFF, 0xD8, 0xFF, 4, 5];
let content = Content {
role: "user".to_string(),
parts: vec![
Part::text_part("What is on these?"),
Part::inline_data("image/png", png.clone()),
Part::inline_data("IMAGE/JPEG", jpeg.clone()),
Part::inline_data("image/webp", b"RIFF0000WEBP".to_vec()),
Part::inline_data("application/pdf", b"%PDF".to_vec()),
],
};
let message = content_to_chat_message(&content).expect("message should be created");
let images: Vec<&str> =
message.images.iter().flatten().map(Image::to_base64).collect::<Vec<_>>();
assert_eq!(
images,
[attachment::encode_base64(&png), attachment::encode_base64(&jpeg)]
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
);
assert!(message.content.starts_with("What is on these?\n"), "{}", message.content);
assert!(!message.content.contains(&attachment::encode_base64(&png)));
assert!(message.content.contains("mime_type=\"image/webp\""));
assert!(message.content.contains("mime_type=\"application/pdf\""));
let wire = serde_json::to_value(&message).unwrap();
assert_eq!(
wire["images"],
serde_json::json!([attachment::encode_base64(&png), attachment::encode_base64(&jpeg)])
);
let text = content_to_chat_message(&Content::new("user").with_text("hi")).unwrap();
assert!(serde_json::to_value(&text).unwrap().get("images").is_none());
}
#[test]
fn content_to_chat_message_keeps_file_attachment_payload() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::file_data("text/csv", "https://example.com/data.csv")],
};
let message = content_to_chat_message(&content).expect("message should be created");
assert!(message.content.contains("text/csv"));
assert!(message.content.contains("https://example.com/data.csv"));
}
#[test]
fn final_response_maps_done_reason() {
let finish = |done_reason: Option<&str>| {
let mut line = serde_json::json!({
"model": "qwen3",
"created_at": "2026-10-17T00:00:00Z",
"message": {"role": "assistant", "content": "partial answer"},
"done": true
});
if let Some(reason) = done_reason {
line["done_reason"] = serde_json::json!(reason);
}
let response: ChatMessageResponse = serde_json::from_value(line.clone()).unwrap();
chat_response_to_llm_response(&response, &line, false, &HashSet::new()).finish_reason
};
assert_eq!(
[None, Some("stop"), Some("length"), Some("unload")].map(finish),
[
Some(FinishReason::Stop),
Some(FinishReason::Stop),
Some(FinishReason::MaxTokens),
Some(FinishReason::Other),
]
);
}
#[test]
fn final_response_reads_usage_from_the_line_as_received() {
let mut line = serde_json::json!({
"model": "qwen3",
"created_at": "2026-10-17T00:00:00Z",
"message": {"role": "assistant", "content": "done"},
"done": true,
"total_duration": 2000,
"load_duration": 10,
"prompt_eval_count": 44,
"prompt_eval_duration": 300,
"eval_count": 8,
"eval_duration": 700
});
let final_usage = |line: &Value| {
let response: ChatMessageResponse = serde_json::from_value(line.clone()).unwrap();
chat_response_to_llm_response(&response, line, false, &HashSet::new())
.usage_metadata
.map(|usage| serde_json::to_value(usage).unwrap())
};
assert_eq!(
final_usage(&line),
Some(serde_json::json!({
"prompt_token_count": 44,
"candidates_token_count": 8,
"total_token_count": 52,
"provider_usage": {
"total_duration": 2000,
"load_duration": 10,
"prompt_eval_count": 44,
"prompt_eval_duration": 300,
"eval_count": 8,
"eval_duration": 700
}
}))
);
let object = line.as_object_mut().unwrap();
object.remove("prompt_eval_count");
object.remove("prompt_eval_duration");
assert_eq!(
final_usage(&line),
Some(serde_json::json!({
"prompt_token_count": 0,
"candidates_token_count": 8,
"total_token_count": 8,
"provider_usage": {
"total_duration": 2000,
"load_duration": 10,
"eval_count": 8,
"eval_duration": 700
}
}))
);
line["done"] = serde_json::json!(false);
assert_eq!(final_usage(&line), None);
}
}