#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::any::Any;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use futures::StreamExt;
use gadk_agent::{AfterModelCallback, AgentConfig, Context, Tool, ToolError, new_agent, pack_tool};
use gadk_engine::llm::{LlmAgentConfig, agent as llm_agent};
use gadk_engine::plugin::{FunctionCallModifierConfig, new_function_call_modifier_plugin};
use gadk_engine::runner::PluginConfig as RunnerPluginConfig;
use gadk_engine::testutil::{MockModel, TestAgentRunner};
use gadk_engine::tool::{AgentTool, FunctionTool, FunctionToolConfig};
use gadk_genai::{
Behavior, Content, FinishReason, FunctionCall, FunctionDeclaration, GenerateContentConfig,
Part, Schema, Tool as GenaiTool, Type,
};
use gadk_model::{LlmRequest, LlmResponse};
use gadk_session::{CreateRequest, InMemorySessionService, Session, SessionError, SessionService};
use serde_json::{Value, json};
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)] struct SimpleArgs {
#[serde(rename = "Num")]
num: i64,
}
async fn ok_func(_ctx: Context, _args: SimpleArgs) -> Result<String, ToolError> {
Ok("ok".to_string())
}
fn modifier_config(names: &'static [&'static str]) -> FunctionCallModifierConfig {
FunctionCallModifierConfig {
predicate: Arc::new(move |tool_name: &str| names.contains(&tool_name)),
args: BTreeMap::from([
(
"skill_id".to_string(),
Schema {
description: "The specific skill to be utilized by the agent.".into(),
r#type: Some(Type::String),
..Default::default()
},
),
(
"rationale".to_string(),
Schema {
description: "The reasoning behind selecting this agent and skill.".into(),
r#type: Some(Type::String),
..Default::default()
},
),
]),
override_description: Some(Arc::new(|original: &str| {
format!(
"This tool can now optionally accept skill_id and rationale parameters to guide skill-based orchestration. {original}"
)
})),
}
}
struct TransferToAgentTool;
impl Tool for TransferToAgentTool {
fn name(&self) -> &str {
"transfer_to_agent"
}
fn description(&self) -> &str {
"Transfer the question to another agent.\nThis tool hands off control to another agent when it's more suitable to answer the user's question according to the agent's description."
}
fn declaration(&self) -> Option<FunctionDeclaration> {
Some(FunctionDeclaration {
name: self.name().into(),
description: self.description().into(),
parameters: Some(Schema {
r#type: Some(Type::Object),
properties: BTreeMap::from([(
"agent_name".to_string(),
Schema {
r#type: Some(Type::String),
description: "the agent name to transfer to".into(),
..Default::default()
},
)]),
required: vec!["agent_name".into()],
..Default::default()
}),
..Default::default()
})
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn create_agent_tool(name: &str, desc: &str) -> Arc<dyn Tool> {
let agent = new_agent(AgentConfig {
name: name.into(),
description: desc.into(),
..Default::default()
})
.unwrap();
AgentTool::new(agent, None)
}
fn request(decl: FunctionDeclaration, name: &str, tool: &Arc<dyn Tool>) -> LlmRequest {
LlmRequest {
config: Some(GenerateContentConfig {
tools: vec![GenaiTool {
function_declarations: vec![decl],
..Default::default()
}],
..Default::default()
}),
tools: HashMap::from([(
name.to_string(),
Arc::new(tool.clone()) as Arc<dyn Any + Send + Sync>,
)]),
..Default::default()
}
}
fn find_declaration<'a>(req: &'a LlmRequest, tool_name: &str) -> Option<&'a FunctionDeclaration> {
req.config
.as_ref()?
.tools
.iter()
.flat_map(|t| t.function_declarations.iter())
.find(|d| d.name == tool_name)
}
struct BeforeCase {
name: &'static str,
req: LlmRequest,
want_params: &'static [&'static str],
check_tools: &'static [&'static str],
}
#[tokio::test]
async fn test_before_model_callback() {
let ctx = Context::builder().build();
let transfer_tool: Arc<dyn Tool> = Arc::new(TransferToAgentTool);
let transfer_tool_decl = transfer_tool.declaration().unwrap();
let agent_tool_default = create_agent_tool("agent_default", "desc");
let agent_tool_default_decl = agent_tool_default.declaration().unwrap();
let function_tool = FunctionTool::new(FunctionToolConfig::new("other_tool", ""), ok_func)
.unwrap_or_else(|e| panic!("functiontool.New failed: {e}"));
let cases = vec![
BeforeCase {
name: "no relevant tools",
req: request(
FunctionDeclaration {
name: "other_tool".into(),
..Default::default()
},
"other_tool",
&function_tool,
),
want_params: &[],
check_tools: &[],
},
BeforeCase {
name: "agent tool default schema",
req: request(
agent_tool_default_decl,
"agent_default",
&agent_tool_default,
),
want_params: &["request", "skill_id", "rationale"],
check_tools: &["agent_default"],
},
BeforeCase {
name: "transfer to agent tool",
req: request(transfer_tool_decl, "transfer_to_agent", &transfer_tool),
want_params: &["agent_name", "skill_id", "rationale"],
check_tools: &["transfer_to_agent"],
},
];
for tc in cases {
let plugin = new_function_call_modifier_plugin(modifier_config(&[
"transfer_to_agent",
"agent_default",
]));
let before_model_callback = plugin.before_model_callback().unwrap();
let (current_req, res) = before_model_callback(ctx.clone(), tc.req).await;
if let Err(e) = res {
panic!("{}: BeforeModelCallback failed: {e}", tc.name);
}
for tool_name in tc.check_tools {
let Some(decl) = find_declaration(¤t_req, tool_name) else {
panic!(
"{}: Tool {tool_name}: Declaration not found in request",
tc.name
);
};
let props = &decl
.parameters
.as_ref()
.unwrap_or_else(|| panic!("{}: Tool {tool_name}: no parameters", tc.name))
.properties;
assert_eq!(
props.len(),
tc.want_params.len(),
"{}: Tool {tool_name}: Expected {} parameters, got {}",
tc.name,
tc.want_params.len(),
props.len()
);
let params: BTreeSet<&str> = props.keys().map(String::as_str).collect();
let want: BTreeSet<&str> = tc.want_params.iter().copied().collect();
assert_eq!(
want, params,
"{}: Tool {tool_name}: Parameter mismatch",
tc.name
);
assert!(
decl.description.contains("skill-based orchestration"),
"{}: Tool {tool_name}: Description not updated",
tc.name
);
}
}
}
fn call(id: &str, name: &str, args: Value) -> Content {
Content {
parts: vec![Part {
function_call: Some(FunctionCall {
id: id.into(),
name: name.into(),
args: args.as_object().cloned().unwrap(),
..Default::default()
}),
..Default::default()
}],
..Default::default()
}
}
struct AfterCase {
name: &'static str,
content: Content,
want_args: Option<Value>,
want_skill_state_key: &'static str,
want_skill_state_value: &'static str,
want_rationale_state_key: &'static str,
want_rationale_state_value: &'static str,
should_have_skill_state: bool,
should_have_rationale_state: bool,
}
fn check_state(ses: &Arc<dyn Session>, case: &str, key: &str, should_have: bool, want: &str) {
if should_have {
match ses.state().get(key) {
Ok(Value::String(got)) => {
assert_eq!(want, got, "{case}: State value mismatch for key {key}")
}
Ok(other) => panic!("{case}: State value for key {key} is not string: {other:?}"),
Err(e) => panic!("{case}: State().Get({key:?}) unexpected error: {e}"),
}
} else if !key.is_empty() {
match ses.state().get(key) {
Ok(v) => panic!("{case}: Unexpected state key {key} found: {v:?}"),
Err(SessionError::StateKeyNotExist) => {}
Err(e) => panic!(
"{case}: State().Get({key:?}) unexpected error when expecting key not to exist: {e}"
),
}
}
}
#[tokio::test]
async fn test_after_model_callback() {
let cases = vec![
AfterCase {
name: "no function calls",
content: Content {
parts: vec![Part::from_text("hello")],
..Default::default()
},
want_args: None,
want_skill_state_key: "",
want_skill_state_value: "",
want_rationale_state_key: "",
want_rationale_state_value: "",
should_have_skill_state: false,
should_have_rationale_state: false,
},
AfterCase {
name: "unmodified function call",
content: call("", "other_tool", json!({"foo": "bar"})),
want_args: Some(json!({"foo": "bar"})),
want_skill_state_key: "",
want_skill_state_value: "",
want_rationale_state_key: "",
want_rationale_state_value: "",
should_have_skill_state: false,
should_have_rationale_state: false,
},
AfterCase {
name: "agent tool with skill and rationale",
content: call(
"fcId",
"test_agent",
json!({"request": "do", "skill_id": "s1", "rationale": "r1"}),
),
want_args: Some(json!({"request": "do"})),
want_skill_state_key: "fcId/skill_id",
want_skill_state_value: "s1",
want_rationale_state_key: "fcId/rationale",
want_rationale_state_value: "r1",
should_have_skill_state: true,
should_have_rationale_state: true,
},
AfterCase {
name: "nil part before the function call",
content: Content {
parts: vec![
Part::default(),
call(
"fcId",
"test_agent",
json!({"request": "do", "skill_id": "s1"}),
)
.parts
.remove(0),
],
..Default::default()
},
want_args: Some(json!({"request": "do"})),
want_skill_state_key: "fcId/skill_id",
want_skill_state_value: "s1",
want_rationale_state_key: "",
want_rationale_state_value: "",
should_have_skill_state: true,
should_have_rationale_state: false,
},
AfterCase {
name: "agent tool with only skill_id",
content: call(
"fcId",
"test_agent",
json!({"request": "do", "skill_id": "s1"}),
),
want_args: Some(json!({"request": "do"})),
want_skill_state_key: "fcId/skill_id",
want_skill_state_value: "s1",
want_rationale_state_key: "",
want_rationale_state_value: "",
should_have_skill_state: true,
should_have_rationale_state: false,
},
AfterCase {
name: "agent tool without skill/rationale",
content: call("fcId", "test_agent", json!({"request": "do"})),
want_args: Some(json!({"request": "do"})),
want_skill_state_key: "",
want_skill_state_value: "",
want_rationale_state_key: "",
want_rationale_state_value: "",
should_have_skill_state: false,
should_have_rationale_state: false,
},
AfterCase {
name: "transfer tool with skill and rationale",
content: call(
"fcId",
"transfer_to_agent",
json!({"agent_name": "a1", "skill_id": "s2", "rationale": "r2"}),
),
want_args: Some(json!({"agent_name": "a1"})),
want_skill_state_key: "fcId/skill_id",
want_skill_state_value: "s2",
want_rationale_state_key: "fcId/rationale",
want_rationale_state_value: "r2",
should_have_skill_state: true,
should_have_rationale_state: true,
},
];
for tc in cases {
let plugin = new_function_call_modifier_plugin(modifier_config(&[
"transfer_to_agent",
"test_agent",
]));
let service = InMemorySessionService::new();
let ses = service
.create(CreateRequest {
app_name: "test".into(),
user_id: "user".into(),
session_id: Some("ses1".into()),
state: None,
})
.await
.unwrap_or_else(|e| panic!("{}: Failed to create session: {e}", tc.name));
let ctx = Context::builder().session(ses.clone()).build();
let after_model_callback = plugin.after_model_callback().unwrap();
let (resp, res) = after_model_callback(
ctx,
LlmResponse {
content: Some(tc.content.clone()),
..Default::default()
},
None,
)
.await;
if let Err(e) = res {
panic!("{}: AfterModelCallback failed: {e}", tc.name);
}
if let (Some(want_args), Some(fc)) = (
&tc.want_args,
resp.content
.iter()
.flat_map(|c| c.parts.iter())
.find_map(|p| p.function_call.as_ref()),
) {
assert_eq!(
want_args,
&Value::Object(fc.args.clone()),
"{}: Args mismatch",
tc.name
);
}
check_state(
&ses,
tc.name,
tc.want_skill_state_key,
tc.should_have_skill_state,
tc.want_skill_state_value,
);
check_state(
&ses,
tc.name,
tc.want_rationale_state_key,
tc.should_have_rationale_state,
tc.want_rationale_state_value,
);
}
}
fn contentless_model() -> Arc<MockModel> {
MockModel::new(vec![Ok(LlmResponse {
finish_reason: Some(FinishReason::MaxTokens),
error_code: "MAX_TOKENS".into(),
..Default::default()
})])
}
#[tokio::test]
async fn test_after_model_callback_contentless_response_keeps_chain() {
let plugin = new_function_call_modifier_plugin(FunctionCallModifierConfig {
predicate: Arc::new(|_: &str| true),
args: BTreeMap::from([(
"skill_id".to_string(),
Schema {
r#type: Some(Type::String),
..Default::default()
},
)]),
override_description: None,
});
const RECOVERED: &str = "recovered from an empty response";
let agent_callback_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let calls = agent_callback_calls.clone();
let after: AfterModelCallback = Arc::new(move |_ctx, resp: LlmResponse, _err| {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let replacement = resp.content.is_none().then(|| LlmResponse {
content: Some(Content::from_text(RECOVERED, "model")),
..Default::default()
});
Box::pin(async move { (resp, Ok(replacement)) })
});
let a = llm_agent::new(LlmAgentConfig {
name: "agent".into(),
model: Some(contentless_model()),
after_model_callbacks: vec![after],
..Default::default()
})
.unwrap_or_else(|e| panic!("llmagent.New() error = {e}"));
let runner = TestAgentRunner::with_plugins(
a,
RunnerPluginConfig {
plugins: vec![plugin],
..Default::default()
},
)
.await;
let mut stream = runner.run("hi");
let mut texts = Vec::new();
while let Some(item) = stream.next().await {
let ev = item.unwrap_or_else(|e| panic!("Run() error = {e}"));
for part in ev.response.content.iter().flat_map(|c| c.parts.iter()) {
if !part.text.is_empty() {
texts.push(part.text.clone());
}
}
}
let n = agent_callback_calls.load(std::sync::atomic::Ordering::SeqCst);
assert_eq!(n, 1, "agent AfterModelCallback ran {n} times, want 1");
assert_eq!(texts, vec![RECOVERED.to_string()], "event texts");
}
struct CachedDeclarationTool {
decl: FunctionDeclaration,
}
impl Tool for CachedDeclarationTool {
fn name(&self) -> &str {
&self.decl.name
}
fn description(&self) -> &str {
&self.decl.description
}
fn declaration(&self) -> Option<FunctionDeclaration> {
Some(self.decl.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn property_names(decl: &FunctionDeclaration) -> Vec<String> {
decl.parameters
.as_ref()
.map(|p| p.properties.keys().cloned().collect())
.unwrap_or_default()
}
#[tokio::test]
async fn test_before_model_callback_leaves_tool_declaration_unchanged() {
const PREFIX: &str = "Accepts skill_id. ";
let plugin = new_function_call_modifier_plugin(FunctionCallModifierConfig {
predicate: Arc::new(|_: &str| true),
args: BTreeMap::from([(
"skill_id".to_string(),
Schema {
r#type: Some(Type::String),
..Default::default()
},
)]),
override_description: Some(Arc::new(|original: &str| format!("{PREFIX}{original}"))),
});
let input_schema = Schema {
r#type: Some(Type::Object),
properties: BTreeMap::from([(
"query".to_string(),
Schema {
r#type: Some(Type::String),
..Default::default()
},
)]),
..Default::default()
};
let schema_agent = llm_agent::new(LlmAgentConfig {
name: "schema_agent".into(),
description: "answers queries".into(),
input_schema: Some(input_schema.clone()),
..Default::default()
})
.unwrap_or_else(|e| panic!("llmagent.New() error = {e}"));
let cases: Vec<(&str, Arc<dyn Tool>)> = vec![
(
"agent tool with input schema",
AgentTool::new(schema_agent.clone(), None),
),
(
"cached declaration without parameters",
Arc::new(CachedDeclarationTool {
decl: FunctionDeclaration {
name: "no_params".into(),
description: "takes nothing".into(),
..Default::default()
},
}),
),
(
"cached declaration with response schema and behavior",
Arc::new(CachedDeclarationTool {
decl: FunctionDeclaration {
name: "full".into(),
description: "has a response schema and a behavior".into(),
behavior: Some(Behavior::NonBlocking),
parameters: Some(Schema {
r#type: Some(Type::Object),
description: "a query".into(),
required: vec!["query".into()],
properties: BTreeMap::from([(
"query".to_string(),
Schema {
r#type: Some(Type::String),
..Default::default()
},
)]),
..Default::default()
}),
response_json_schema: Some(json!({"type": "string"})),
..Default::default()
},
}),
),
];
let before = plugin.before_model_callback().unwrap();
for (name, tool) in cases {
let original = tool.declaration().unwrap();
let original_description = original.description.clone();
let original_properties = property_names(&original);
let mut want_decl = original.clone();
want_decl.parameters.get_or_insert_with(|| Schema {
r#type: Some(Type::Object),
..Default::default()
});
let ctx = Context::builder().build();
for request in 0..2 {
let mut req = LlmRequest::default();
pack_tool(&mut req, &tool).unwrap_or_else(|e| panic!("PackTool() error = {e}"));
let (req, res) = before(ctx.clone(), req).await;
if let Err(e) = res {
panic!("{name}: BeforeModelCallback() error = {e}");
}
let mut decl = find_declaration(&req, tool.name()).unwrap().clone();
assert_eq!(
decl.description,
format!("{PREFIX}{original_description}"),
"{name}: request {request}: description"
);
assert!(
property_names(&decl).iter().any(|p| p == "skill_id"),
"{name}: request {request}: declaration lacks skill_id"
);
decl.description = want_decl.description.clone();
if let Some(p) = decl.parameters.as_mut() {
p.properties.remove("skill_id");
}
assert_eq!(
decl, want_decl,
"{name}: request {request}: declaration differs beyond the description and skill_id"
);
}
let after = tool.declaration().unwrap();
assert_eq!(
after.description, original_description,
"{name}: tool description"
);
assert_eq!(
property_names(&after),
original_properties,
"{name}: tool parameters"
);
}
assert!(
!input_schema.properties.contains_key("skill_id"),
"agent InputSchema gained skill_id"
);
}