use crate::error::LocalError;
use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
use serde_json::{Map, Value};
use std::collections::BTreeSet;
use std::fmt;
use troupekit_core::message::ContentPart;
use troupekit_core::tool::ToolSpec;
pub const REPLY_MAX_BYTES: usize = 1024 * 1024;
const THINK_OPEN: &str = "<think>";
const THINK_CLOSE: &str = "</think>";
pub fn parse_reply(text: &str, tools: &[ToolSpec]) -> Result<Vec<ContentPart>, LocalError> {
if text.len() > REPLY_MAX_BYTES {
return Err(LocalError::Decode(format!(
"local reply is {} bytes, limit {REPLY_MAX_BYTES}",
text.len()
)));
}
if unclosed_think(text) {
return Err(LocalError::Decode(
"local reply ends inside its <think> block, so it holds no answer".into(),
));
}
let text = answer_of(text);
let text_part = || {
vec![ContentPart::Text {
text: text.to_string(),
}]
};
if tools.is_empty() || !text.trim_start().starts_with('{') {
return Ok(text_part());
}
let Ok(Members(members)) = serde_json::from_str::<Members>(text.trim()) else {
return Ok(text_part());
};
let mut seen = BTreeSet::new();
let unique = members.iter().all(|(key, _)| seen.insert(key.as_str()));
let map: Map<String, Value> = members.into_iter().collect();
let Some(tool) = map.get("tool") else {
return Ok(text_part());
};
if !unique {
return Err(LocalError::Decode(
"local tool call repeats a member".into(),
));
}
let Value::String(name) = tool else {
return Err(LocalError::Decode(
"local tool call has a non-string tool name".into(),
));
};
if !tools.iter().any(|t| &t.name == name) {
return Err(LocalError::Decode(format!(
"local reply calls unknown tool {name:?}"
)));
}
if map.len() != 2 {
return Err(LocalError::Decode(
"local tool call must hold only tool and arguments".into(),
));
}
let Some(arguments @ Value::Object(_)) = map.get("arguments") else {
return Err(LocalError::Decode(format!(
"local call to {name:?} has no arguments object"
)));
};
Ok(vec![ContentPart::ToolCall {
id: "local-1".to_string(),
name: name.clone(),
arguments: arguments.clone(),
}])
}
pub(crate) fn answer_of(text: &str) -> &str {
after_think(text).unwrap_or(text)
}
pub(crate) fn unclosed_think(text: &str) -> bool {
text.trim_start().starts_with(THINK_OPEN) && after_think(text).is_none()
}
pub(crate) fn after_think(text: &str) -> Option<&str> {
let body = text.trim_start().strip_prefix(THINK_OPEN)?;
let end = body.find(THINK_CLOSE)?;
Some(body[end + THINK_CLOSE.len()..].trim_start())
}
pub(crate) fn opens_think(head: &str) -> bool {
THINK_OPEN.starts_with(head) || (head.starts_with(THINK_OPEN) && after_think(head).is_none())
}
struct Members(Vec<(String, Value)>);
impl<'de> Deserialize<'de> for Members {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct MembersVisitor;
impl<'de> Visitor<'de> for MembersVisitor {
type Value = Members;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON object")
}
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Members, A::Error> {
let mut members = Vec::new();
while let Some(pair) = access.next_entry::<String, Value>()? {
members.push(pair);
}
Ok(Members(members))
}
}
deserializer.deserialize_map(MembersVisitor)
}
}