use std::any::Any;
use std::sync::Arc;
use gadk_genai::{
Content, FunctionCall, GenerateContentConfig, Part, ROLE_USER, Tool as GenaiTool,
};
use gadk_model::LlmRequest;
use gadk_platform::go_type_name;
use serde_json::{Map, Value};
use crate::error::ToolError;
use crate::go_fmt::go_quote;
use crate::tool::Tool;
pub fn pack_tool(req: &mut LlmRequest, tool: &Arc<dyn Tool>) -> Result<(), ToolError> {
let name = tool.name().to_string();
if req.tools.contains_key(&name) {
return Err(ToolError::InvalidArgument(format!(
"duplicate tool: {}",
go_quote(&name)
)));
}
req.tools
.insert(name, Arc::new(tool.clone()) as Arc<dyn Any + Send + Sync>);
let config = req
.config
.get_or_insert_with(GenerateContentConfig::default);
let Some(decl) = tool.declaration() else {
return Ok(());
};
match config
.tools
.iter_mut()
.find(|t| !t.function_declarations.is_empty())
{
Some(t) => t.function_declarations.push(decl),
None => config.tools.push(GenaiTool {
function_declarations: vec![decl],
..Default::default()
}),
}
Ok(())
}
pub fn tool_from_request(req: &LlmRequest, name: &str) -> Option<Arc<dyn Tool>> {
req.tools
.get(name)?
.downcast_ref::<Arc<dyn Tool>>()
.cloned()
}
pub fn append_instructions(req: &mut LlmRequest, instructions: &[&str]) {
if instructions.is_empty() {
return;
}
let inst = instructions.join("\n\n");
let cfg = req
.config
.get_or_insert_with(GenerateContentConfig::default);
let Some(si) = cfg.system_instruction.as_mut() else {
cfg.system_instruction = Some(Content::from_text(inst, ROLE_USER));
return;
};
if let Some(last) = si.parts.last_mut()
&& !last.text.is_empty()
{
last.text.push_str("\n\n");
last.text.push_str(&inst);
return;
}
si.parts.push(Part::from_text(inst));
}
pub const REQUEST_CONFIRMATION_FUNCTION_CALL_NAME: &str = "adk_request_confirmation";
pub fn original_call_from(fc: &FunctionCall) -> Result<FunctionCall, ToolError> {
const KEY: &str = "originalFunctionCall";
if fc.args.is_empty() {
return Err(ToolError::InvalidArgument(
"functionCall or its arguments cannot be nil".into(),
));
}
let Some(val) = fc.args.get(KEY) else {
return Err(ToolError::InvalidArgument(format!(
"required argument {} is missing from call with ID {}",
go_quote(KEY),
fc.id
)));
};
let Value::Object(raw) = val else {
return Err(ToolError::InvalidArgument(format!(
"argument {} has invalid type: expected JSON object (map[string]any) or *genai.FunctionCall, got {}",
go_quote(KEY),
go_type_name(val)
)));
};
const FIELDS: [&str; 5] = ["id", "args", "name", "partialArgs", "willContinue"];
let normalized: Map<String, Value> = raw
.iter()
.filter_map(|(k, v)| {
FIELDS
.iter()
.find(|f| f.eq_ignore_ascii_case(k))
.map(|f| ((*f).to_string(), v.clone()))
})
.collect();
serde_json::from_value(Value::Object(normalized)).map_err(|e| {
ToolError::InvalidArgument(format!(
"failed to decode {} structure for call ID {}: {e}",
go_quote(KEY),
fc.id
))
})
}