#![deny(unsafe_code)]
use super::super::{part, Body, Part, Step};
use super::tool_arg;
use crate::json::Value;
pub(super) fn body_block(blocks: &[Value]) -> Option<usize> {
let says = |b: &Value, key: &str| {
b.get("type").and_then(|t| t.as_str()) == Some(key)
&& b.get(key).and_then(|t| t.as_str()).is_some_and(|t| !t.trim().is_empty())
};
if let Some(i) = blocks.iter().position(|b| says(b, "text")) {
return Some(i);
}
blocks.iter().position(|b| says(b, "thinking"))
}
pub(super) fn block_body(block: &Value, i: usize) -> Option<Body> {
let kind = block.get("type").and_then(|t| t.as_str())?;
let text = block.get(kind)?.as_str()?;
let at = match kind {
"text" => text_at(i),
_ => thinking_at(i),
};
Some(Body::new(text, at))
}
pub(super) fn text_part(block: &Value, key: &str, label: &'static str, at: Vec<Step>) -> Option<Part> {
let text = block.get(key)?.as_str()?;
match text.trim().is_empty() {
true => None,
false => Some(Part::Text { label, body: Body::new(text, at) }),
}
}
pub(super) fn call_part(block: &Value) -> Part {
let tool = block.get("name").and_then(|n| n.as_str()).unwrap_or("tool");
let input = block.get("input");
Part::Call {
tool: tool.to_string(),
arg: input.and_then(tool_arg).unwrap_or_default(),
args: input.map(input_args).unwrap_or_default(),
result: None,
}
}
pub(super) fn input_args(input: &Value) -> Vec<(String, Body)> {
part::args_of(input)
}
pub(super) fn text_at(i: usize) -> Vec<Step> {
vec![
Step::Key("message"),
Step::Key("content"),
Step::At(i),
Step::Key("text"),
]
}
pub(super) fn result_body(content: Option<&Value>, i: usize) -> Option<Body> {
let content = content?;
if let Some(text) = content.as_str() {
let at = vec![
Step::Key("message"),
Step::Key("content"),
Step::At(i),
Step::Key("content"),
];
return Some(Body::new(text, at));
}
let text = joined_text(content)?;
Some(Body::new(&text, Vec::new()))
}
pub(super) fn joined_text(content: &Value) -> Option<String> {
let items = content.as_array()?;
Some(
items
.iter()
.map(|b| match b.get("text").and_then(|t| t.as_str()) {
Some(text) => text.to_string(),
None => part::as_text(b),
})
.collect::<Vec<_>>()
.join("\n"),
)
}
pub(super) fn thinking_at(i: usize) -> Vec<Step> {
vec![
Step::Key("message"),
Step::Key("content"),
Step::At(i),
Step::Key("thinking"),
]
}