1use std::collections::BTreeMap;
21use std::sync::Arc;
22
23use futures::future::{BoxFuture, ready};
24use gadk_agent::{
25 AfterModelCallback, AgentError, BeforeModelCallback, Context, Plugin, PluginConfig,
26};
27use gadk_genai::{Schema, Type};
28use gadk_model::{LlmRequest, LlmResponse, ModelError};
29
30use crate::llm::flow::model_error_into_agent;
31use crate::llm::processors::wrap_err;
32
33const NAME: &str = "FunctionCallModifierPlugin";
34
35type RequestResult = BoxFuture<'static, (LlmRequest, Result<Option<LlmResponse>, AgentError>)>;
36type ResponseResult = BoxFuture<'static, (LlmResponse, Result<Option<LlmResponse>, AgentError>)>;
37
38#[derive(Clone)]
40pub struct FunctionCallModifierConfig {
41 pub predicate: Arc<dyn Fn(&str) -> bool + Send + Sync>,
43 pub args: BTreeMap<String, Schema>,
46 #[allow(clippy::type_complexity)] pub override_description: Option<Arc<dyn Fn(&str) -> String + Send + Sync>>,
49}
50
51pub fn new_function_call_modifier_plugin(cfg: FunctionCallModifierConfig) -> Plugin {
54 let cfg = Arc::new(cfg);
55 let before_model: BeforeModelCallback = {
56 let cfg = cfg.clone();
57 Arc::new(move |_ctx: Context, mut req: LlmRequest| -> RequestResult {
58 add_args(&cfg, &mut req);
59 Box::pin(ready((req, Ok(None))))
60 })
61 };
62 let after_model: AfterModelCallback = Arc::new(
63 move |ctx: Context, resp: LlmResponse, err: Option<Arc<ModelError>>| -> ResponseResult {
64 Box::pin(ready(strip_args(&cfg, &ctx, resp, err)))
65 },
66 );
67 Plugin::new(PluginConfig {
68 name: NAME.into(),
69 before_model_callback: Some(before_model),
70 after_model_callback: Some(after_model),
71 ..Default::default()
72 })
73}
74
75fn add_args(cfg: &FunctionCallModifierConfig, req: &mut LlmRequest) {
79 let LlmRequest { config, tools, .. } = req;
80 let Some(config) = config.as_mut() else {
81 return;
82 };
83 for tool in &mut config.tools {
84 for decl in &mut tool.function_declarations {
85 if !tools.contains_key(decl.name.as_str()) || !(cfg.predicate)(decl.name.as_str()) {
86 continue;
87 }
88 let params = decl.parameters.get_or_insert_with(|| Schema {
89 r#type: Some(Type::Object),
90 ..Default::default()
91 });
92 params
93 .properties
94 .extend(cfg.args.iter().map(|(k, v)| (k.clone(), v.clone())));
95 if let Some(override_description) = &cfg.override_description {
96 decl.description = override_description(decl.description.as_str());
97 }
98 }
99 }
100}
101
102fn strip_args(
105 cfg: &FunctionCallModifierConfig,
106 ctx: &Context,
107 mut resp: LlmResponse,
108 err: Option<Arc<ModelError>>,
109) -> (LlmResponse, Result<Option<LlmResponse>, AgentError>) {
110 if let Some(err) = err {
111 return (resp, Err(model_error_into_agent(err)));
117 }
118 if resp.content.as_ref().is_none_or(|c| c.parts.is_empty()) {
119 return (resp, Ok(None));
122 }
123
124 let state = ctx.state();
125 let mut failure = None;
126 if let Some(content) = resp.content.as_mut() {
127 'parts: for part in &mut content.parts {
128 let Some(fc) = part.function_call.as_mut() else {
129 continue;
130 };
131 if !(cfg.predicate)(fc.name.as_str()) {
132 continue;
133 }
134 for name in cfg.args.keys() {
135 let Some(arg) = fc.args.remove(name) else {
136 continue;
137 };
138 let state_key = format!("{}/{}", fc.id, name);
139 if let Err(e) = state.set(&state_key, arg) {
140 failure = Some(wrap_err("failed to set state", e));
141 break 'parts;
142 }
143 }
144 }
145 }
146 match failure {
147 Some(e) => (resp, Err(e)),
149 None => (resp, Ok(None)),
151 }
152}
153
154#[cfg(test)]
155#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
156mod tests {
157 use gadk_genai::{Content, FunctionCall, Part};
158 use serde_json::{Map, json};
159
160 use super::*;
161
162 fn cfg() -> FunctionCallModifierConfig {
163 FunctionCallModifierConfig {
164 predicate: Arc::new(|_: &str| true),
165 args: BTreeMap::from([("skill_id".to_string(), Schema::default())]),
166 override_description: None,
167 }
168 }
169
170 #[test]
171 fn plugin_is_named_like_go() {
172 let p = new_function_call_modifier_plugin(cfg());
173 assert_eq!(p.name(), "FunctionCallModifierPlugin");
174 assert!(p.before_model_callback().is_some());
175 assert!(p.after_model_callback().is_some());
176 }
177
178 #[tokio::test]
180 async fn after_model_passes_a_model_error_through() {
181 let cb = new_function_call_modifier_plugin(cfg())
182 .after_model_callback()
183 .unwrap();
184 let (_, res) = cb(
185 Context::builder().build(),
186 LlmResponse::default(),
187 Some(Arc::new(ModelError::EmptyResponse)),
188 )
189 .await;
190 let err = res.unwrap_err();
191 assert!(
192 matches!(err, AgentError::Model(ModelError::EmptyResponse)),
193 "{err:?}"
194 );
195 assert_eq!(err.to_string(), "empty response");
196 }
197
198 #[tokio::test]
200 async fn after_model_leaves_a_partless_response_to_the_chain() {
201 let cb = new_function_call_modifier_plugin(cfg())
202 .after_model_callback()
203 .unwrap();
204 let (resp, res) = cb(Context::builder().build(), LlmResponse::default(), None).await;
205 assert_eq!(resp, LlmResponse::default());
206 assert_eq!(res.unwrap(), None);
207 }
208
209 #[tokio::test]
210 async fn after_model_hands_back_the_stripped_response_with_ok_none() {
211 let cb = new_function_call_modifier_plugin(cfg())
212 .after_model_callback()
213 .unwrap();
214 let resp = LlmResponse {
215 content: Some(Content {
216 parts: vec![Part {
217 function_call: Some(FunctionCall {
218 id: "id1".into(),
219 name: "t".into(),
220 args: json!({"skill_id": "s", "x": 1})
221 .as_object()
222 .cloned()
223 .unwrap(),
224 ..Default::default()
225 }),
226 ..Default::default()
227 }],
228 ..Default::default()
229 }),
230 ..Default::default()
231 };
232 let ctx = Context::builder().build();
233 let (got, res) = cb(ctx.clone(), resp, None).await;
234 assert!(matches!(res, Ok(None)), "{res:?}");
235 let fc = got.content.unwrap().parts[0].function_call.clone().unwrap();
236 let want: Map<String, serde_json::Value> = json!({"x": 1}).as_object().cloned().unwrap();
237 assert_eq!(fc.args, want);
238 assert_eq!(ctx.state().get("id1/skill_id").unwrap(), json!("s"));
239 }
240
241 #[test]
242 fn before_model_adds_object_parameters_only_to_packed_selected_declarations() {
243 use gadk_genai::{FunctionDeclaration, GenerateContentConfig, Tool as GenaiTool};
244 let mut req = LlmRequest {
245 config: Some(GenerateContentConfig {
246 tools: vec![GenaiTool {
247 function_declarations: vec![
248 FunctionDeclaration {
249 name: "packed".into(),
250 ..Default::default()
251 },
252 FunctionDeclaration {
253 name: "unpacked".into(),
254 ..Default::default()
255 },
256 ],
257 ..Default::default()
258 }],
259 ..Default::default()
260 }),
261 ..Default::default()
262 };
263 req.tools.insert(
264 "packed".into(),
265 Arc::new(()) as Arc<dyn std::any::Any + Send + Sync>,
266 );
267 add_args(&cfg(), &mut req);
268 let decls = &req.config.as_ref().unwrap().tools[0].function_declarations;
269 let p = decls[0].parameters.as_ref().unwrap();
270 assert_eq!(p.r#type, Some(Type::Object));
271 assert!(p.properties.contains_key("skill_id"));
272 assert!(p.required.is_empty());
273 assert!(decls[1].parameters.is_none());
274 }
275}