gadk-engine 0.4.2

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

//! Port of Go plugin/functioncallmodifier/plugin_test.go.

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};

/// Go `SimpleArgs`.
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)] // only its schema matters
struct SimpleArgs {
    #[serde(rename = "Num")]
    num: i64,
}

/// Go `okFunc`.
async fn ok_func(_ctx: Context, _args: SimpleArgs) -> Result<String, ToolError> {
    Ok("ok".to_string())
}

/// Go's plugin config, shared by both tests: `predicate` accepts exactly `names`.
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}"
            )
        })),
    }
}

/// Go `&llminternal.TransferToAgentTool{}` (no supported agents). The engine's transfer tool is
/// crate-private, so this stub has Go's name, description and declaration
/// (internal/llminternal/agent_transfer.go:123-154).
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
    }
}

/// Go `createAgentTool(t, name, desc, nil)`: an agent tool over an agent with no input schema.
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)
}

/// A request with one declaration in `config.tools` and `tool` packed under `name`.
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()
    }
}

/// Go `findDeclaration`.
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],
}

// parity: adapted: TransferToAgentTool is crate-private, so a stub with Go's declaration is used; Go's cloneLLMRequest is unnecessary because each case builds its own request
#[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(&current_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
            );
        }
    }
}

/// A content with one function-call part.
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()
    }
}

/// Go's `originalDecls` field is unused by the Go test body and is not ported.
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,
}

/// Go's per-key state check: a string value when expected; otherwise (for a non-empty key)
/// `ErrStateKeyNotExist`.
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}"
            ),
        }
    }
}

// parity: adapted: Go checks the args edited in place in tc.content; Rust checks the response the callback hands back (R1); Rust parts cannot be nil, so the nil-part case puts an empty Part first
#[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 {
            // A nil part in a model response (a degenerate provider chunk) is
            // skipped, not dereferenced; the function call after it is still
            // rewritten.
            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);
        }

        // Check if args are pruned, on the first function-call part.
        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 session state
        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,
        );
    }
}

/// Go `contentlessModel`: answers the request with a response that carries no content, as a
/// model does when it stops on MAX_TOKENS or SAFETY.
fn contentless_model() -> Arc<MockModel> {
    MockModel::new(vec![Ok(LlmResponse {
        finish_reason: Some(FinishReason::MaxTokens),
        error_code: "MAX_TOKENS".into(),
        ..Default::default()
    })])
}

// TestAfterModelCallback_ContentlessResponseKeepsChain pins that the plugin
// leaves a response with nothing to rewrite to the rest of the after-model
// chain, so an agent's own AfterModelCallbacks still see it.
#[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");
}

/// Go `cachedDeclarationTool`: hands out one declaration on every call, as the task and
/// single_turn tools do.
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
    }
}

/// Go `propertyNames`.
fn property_names(decl: &FunctionDeclaration) -> Vec<String> {
    decl.parameters
        .as_ref()
        .map(|p| p.properties.keys().cloned().collect())
        .unwrap_or_default()
}

// TestBeforeModelCallback_LeavesToolDeclarationUnchanged pins that the plugin
// edits only the request. A task agent tool hands out the same declaration on
// every call, and an agent tool reuses its agent's InputSchema, so editing
// them in place would wrap the description once more on every request and add
// the arguments to the agent's own schema. It also pins that the request's
// copy keeps every other field of the tool's declaration.
// parity: adapted: the "task agent tool" case is dropped (gadk's TaskAgentTool is crate-private; CachedDeclarationTool covers the same shared-declaration shape); Rust declarations are owned values, so the tool side is unchanged by construction
#[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);
        // The request's copy may differ from the tool's declaration only in its
        // description and the added skill_id, plus the object schema that holds
        // skill_id when the declaration has no parameters.
        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"
    );
}