use std::collections::BTreeMap;
use std::sync::OnceLock;
use adk_core::{Artifacts, Part, ToolContext};
use serde::Serialize;
use serde_json::{Value, json};
use crate::geometry::{Region, RegionSet};
use crate::manifest::{ManifestSet, ModelSource};
use crate::media::ImageRef;
use crate::runtime::CallRecord;
use crate::traits::DocumentPage;
pub const ANSWER_ARTIFACT_PREFIX: &str = "vision-answer-";
pub(crate) struct Answer {
pub(crate) regions: Vec<Region>,
pub(crate) page: Option<DocumentPage>,
pub(crate) described: Option<Value>,
pub(crate) measurements: Vec<Value>,
pub(crate) calls: Vec<CallRecord>,
}
impl Answer {
pub(crate) fn regions(regions: Vec<Region>, calls: Vec<CallRecord>) -> Self {
Self { regions, page: None, described: None, measurements: Vec::new(), calls }
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ModelFacts {
#[serde(skip_serializing_if = "Option::is_none")]
revision: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
licence: Option<String>,
built_in: bool,
}
pub fn answer_artifact_name(invocation_id: &str, call_id: &str) -> String {
let safe = |id: &str| -> String {
id.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
.collect()
};
format!("{ANSWER_ARTIFACT_PREFIX}{}.{}.json", safe(invocation_id), safe(call_id))
}
fn builtin_manifests() -> Option<&'static ManifestSet> {
static BUILTIN: OnceLock<Option<ManifestSet>> = OnceLock::new();
BUILTIN.get_or_init(|| ManifestSet::builtin().ok()).as_ref()
}
fn models_of(regions: &[Region]) -> BTreeMap<String, ModelFacts> {
let mut models = BTreeMap::new();
for region in regions {
let Some(id) = ®ion.origin.manifest else { continue };
let known = builtin_manifests().and_then(|set| set.get(id));
let revision = known.and_then(|manifest| match &manifest.source {
ModelSource::HuggingFace { revision, .. }
| ModelSource::ModelScope { revision, .. } => Some(revision.clone()),
_ => None,
});
models.entry(id.clone()).or_insert(ModelFacts {
revision,
licence: known.map(|manifest| manifest.licence.id.clone()),
built_in: known.is_some(),
});
}
models
}
pub(crate) fn record(
ctx: &dyn ToolContext,
tool: &str,
image: &ImageRef,
name: &str,
args: &Value,
answer: &Answer,
) -> Value {
let mut regions = answer.regions.clone();
let page = answer.page.as_ref().map(|page| {
regions = page.blocks.iter().map(|block| block.region.clone()).collect();
json!({
"blocks": page.blocks.iter().map(|block| {
let mut entry = json!({ "kind": block.kind, "text": block.text });
if let Some(confidence) = block.confidence {
entry["confidence"] = json!(confidence);
}
entry
}).collect::<Vec<_>>(),
"readingOrder": page.reading_order,
})
});
let models = models_of(®ions);
let set = RegionSet::new(image.digest, image.width, image.height, regions);
let mut record = json!({
"kind": "adkVisionAnswer",
"version": 1,
"tool": tool,
"callId": ctx.function_call_id(),
"invocationId": ctx.invocation_id(),
"agent": ctx.agent_name(),
"at": chrono::Utc::now(),
"image": {
"digest": image.digest,
"width": image.width,
"height": image.height,
"mimeType": image.mime_type,
"artifact": image.artifact.file_name,
"name": name,
"provenance": image.provenance,
},
"args": args,
"regionSet": set,
"calls": answer.calls,
"models": models,
});
if let Some(page) = page {
record["page"] = page;
}
if let Some(described) = &answer.described {
record["answer"] = described.clone();
}
if !answer.measurements.is_empty() {
record["measurements"] = Value::Array(answer.measurements.clone());
}
record
}
pub(crate) async fn save(
artifacts: &dyn Artifacts,
invocation_id: &str,
call_id: &str,
record: &Value,
) {
let name = answer_artifact_name(invocation_id, call_id);
let data = match serde_json::to_vec(record) {
Ok(data) => data,
Err(error) => {
tracing::warn!(error = %error, artifact.name = %name, "answer record not serialised");
return;
}
};
let part = Part::InlineData {
mime_type: "application/json".into(),
data,
uri: None,
annotations: None,
};
if let Err(error) = artifacts.save(&name, &part).await {
tracing::warn!(error = %error, artifact.name = %name, "answer record not saved");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn artifact_names_are_one_safe_file_name() {
assert_eq!(answer_artifact_name("inv-1", "c-31"), "vision-answer-inv-1.c-31.json");
assert_eq!(answer_artifact_name("i.1", "a/../b c"), "vision-answer-i_1.a____b_c.json");
}
}