Skip to main content

gadk_engine/plugin/
function_call_modifier.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A plugin that adds configured arguments to selected tools' declarations before each model
17//! call. After the call it moves those arguments out of the model's function calls into session
18//! state under `<function_call_id>/<arg>`, so the tools never see them.
19
20use 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/// The configuration of the function-call-modifier plugin.
39#[derive(Clone)]
40pub struct FunctionCallModifierConfig {
41    /// Whether the named tool gets the extra arguments.
42    pub predicate: Arc<dyn Fn(&str) -> bool + Send + Sync>,
43    /// The extra arguments by name. They are added to each selected declaration's typed
44    /// `parameters` and moved from its function calls into session state.
45    pub args: BTreeMap<String, Schema>,
46    /// Maps a selected declaration's description to its new one.
47    #[allow(clippy::type_complexity)] // an optional shared closure: spelled out in place
48    pub override_description: Option<Arc<dyn Fn(&str) -> String + Send + Sync>>,
49}
50
51/// Builds the plugin (construction never fails): a plugin named `FunctionCallModifierPlugin`
52/// with a before-model and an after-model callback.
53pub 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
75/// The before-model callback. Each declaration that is packed in `req.tools` and passes the
76/// predicate gets typed `OBJECT` parameters if it has none, gets `cfg.args` copied into its
77/// properties (overwriting, never touching `required`), and has its description overridden.
78fn 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
102/// The after-model callback: moves the configured arguments out of the response's function calls
103/// into session state.
104fn 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        // A model error passes through. The flow never reaches this: it passes `None` here and
112        // routes model errors to the on-model-error callbacks. A caller
113        // going through the PluginManager keeps its own clone of the `Arc`, so the error is
114        // shared and surfaces as `AgentError::Other` (same text); only the `Arc`'s sole owner
115        // gets `AgentError::Model` back.
116        return (resp, Err(model_error_into_agent(err)));
117    }
118    if resp.content.as_ref().is_none_or(|c| c.parts.is_empty()) {
119        // Leave a content-less response to the rest of the after-model chain (the agent's own
120        // callbacks included).
121        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        // A state write failed: `failed to set state: <err>`.
148        Some(e) => (resp, Err(e)),
149        // The response was edited in place; no replacement is returned.
150        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    // Called directly with the sole `Arc`, so the error comes back as `AgentError::Model`.
179    #[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    // Go returns the response itself when it has no parts, which ends the after-model chain.
199    #[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}