gadk-engine 0.4.6

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
// 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.

//! Parity port of Go internal/llminternal/streaming_tool_test.go.

use std::{
    any::Any,
    collections::HashMap,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

use async_trait::async_trait;
use gadk_agent::{
    AgentConfig, AgentError, Context, InvocationContext, LiveRequest, LiveSession, Tool, agent,
};
use gadk_genai::{Content, FunctionCall, Part};
use gadk_model::LlmResponse;
use gadk_session::Event;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;

use crate::{
    llm::{
        flow::Flow,
        functions::{handle_function_calls, handle_function_calls_live},
        live::session::LiveSessionImpl,
    },
    tool::{FunctionToolConfig, StreamingFunctionTool},
};

#[derive(Deserialize, schemars::JsonSchema)]
struct Args {
    count: i64,
}

/// A model event carrying the given function calls `(id, name, args)`.
fn call_event(calls: &[(&str, &str, Value)]) -> Event {
    Event {
        response: LlmResponse {
            content: Some(Content {
                role: "model".into(),
                parts: calls
                    .iter()
                    .map(|(id, name, args)| Part {
                        function_call: Some(FunctionCall {
                            id: (*id).into(),
                            name: (*name).into(),
                            args: args.as_object().unwrap().clone(),
                            ..Default::default()
                        }),
                        ..Default::default()
                    })
                    .collect(),
            }),
            ..Default::default()
        },
        ..Default::default()
    }
}

fn inv_ctx() -> InvocationContext {
    InvocationContext::builder()
        .invocation_id("inv_1")
        .agent(
            agent::new(AgentConfig {
                name: "agent_1".into(),
                ..Default::default()
            })
            .unwrap(),
        )
        .build_invocation()
}

/// The only function response of `ev`, as its `response` map.
fn single_response(ev: &Event) -> serde_json::Map<String, Value> {
    let parts = &ev.response.content.as_ref().unwrap().parts;
    assert_eq!(parts.len(), 1, "expected 1 part");
    parts[0]
        .function_response
        .as_ref()
        .expect("FunctionResponse part")
        .response
        .clone()
}

/// Go mockLiveSession: records every request it is sent.
struct MockLiveSession {
    tx: tokio::sync::mpsc::UnboundedSender<LiveRequest>,
}

#[async_trait]
impl LiveSession for MockLiveSession {
    async fn send(&self, req: LiveRequest) -> Result<(), AgentError> {
        let _ = self.tx.send(req);
        Ok(())
    }
    async fn close(&self) -> Result<(), AgentError> {
        Ok(())
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_handle_function_calls_streaming() {
    let stream_tool: Arc<dyn Tool> = StreamingFunctionTool::new(
        FunctionToolConfig::new("test_stream", "streams chunks"),
        |_ctx: Context, a: Args| {
            futures::stream::iter((0..a.count).map(|i| Ok(format!("chunk {i}"))))
        },
    )
    .unwrap();
    let tools = HashMap::from([("test_stream".to_owned(), stream_tool.clone())]);
    let call_ev = call_event(&[("call_1", "test_stream", json!({"count": 3}))]);

    // Subtest "Live Mode (Streaming)".
    {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mock: Arc<dyn LiveSession> = Arc::new(MockLiveSession { tx });
        let flow = Flow {
            tools: parking_lot::RwLock::new(vec![stream_tool.clone()]),
            ..Default::default()
        };
        let merged = handle_function_calls_live(&inv_ctx(), &flow, &tools, &call_ev, mock)
            .await
            .unwrap()
            .expect("non-None merged event");
        // The immediate response says the call is pending.
        assert_eq!(
            single_response(&merged).get("status"),
            Some(&json!(
                "The function is running asynchronously and the results are pending."
            ))
        );
        // Wait for the background stream (Go wg.Wait for 3 sends).
        let mut received = Vec::new();
        while received.len() < 3 {
            let req = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .expect("timed out waiting for a streamed chunk")
                .expect("session dropped");
            if let Some(c) = &req.content
                && let Some(p) = c.parts.first()
            {
                assert_eq!(c.role, "user");
                received.push(p.text.clone());
            }
        }
        assert_eq!(
            received,
            vec![
                "Function test_stream returned: chunk 0",
                "Function test_stream returned: chunk 1",
                "Function test_stream returned: chunk 2",
            ]
        );
    }

    // Subtest "Non-Live Mode (Aggregation)".
    {
        let flow = Flow {
            tools: parking_lot::RwLock::new(vec![stream_tool.clone()]),
            ..Default::default()
        };
        let merged = handle_function_calls(&inv_ctx(), &flow, &tools, &call_ev, None)
            .await
            .unwrap()
            .expect("non-None merged event");
        assert_eq!(
            single_response(&merged).get("result"),
            Some(&json!("chunk 0chunk 1chunk 2"))
        );
    }
}

#[derive(Deserialize, schemars::JsonSchema)]
struct NoArgs {}

#[tokio::test]
async fn test_handle_function_calls_streaming_tool_errors() {
    type Handler = fn(
        Context,
        NoArgs,
    )
        -> futures::stream::BoxStream<'static, Result<String, gadk_agent::ToolError>>;
    let panics: Handler = |_, _| {
        Box::pin(futures::stream::poll_fn(
            |_| -> std::task::Poll<Option<Result<String, gadk_agent::ToolError>>> {
                panic!("boom")
            },
        ))
    };
    let errors: Handler = |_, _| {
        Box::pin(futures::stream::iter([Err(
            gadk_agent::ToolError::Execution("order not found".into()),
        )]))
    };
    let cases: [(&str, Handler, &str); 2] = [
        (
            "panic is hidden from the model",
            panics,
            "Invoking `test_stream()` failed with an internal error.",
        ),
        (
            "returned error reaches the model",
            errors,
            "order not found",
        ),
    ];
    for (name, handler, want) in cases {
        let stream_tool: Arc<dyn Tool> =
            StreamingFunctionTool::new(FunctionToolConfig::new("test_stream", ""), handler)
                .unwrap();
        let tools = HashMap::from([("test_stream".to_owned(), stream_tool)]);
        let call_ev = call_event(&[("call_1", "test_stream", json!({}))]);
        let merged = handle_function_calls(&inv_ctx(), &Flow::default(), &tools, &call_ev, None)
            .await
            .unwrap_or_else(|e| panic!("{name}: handleFunctionCalls error: {e}"))
            .expect("non-None merged event");
        assert_eq!(
            single_response(&merged).get("error"),
            Some(&json!(want)),
            "{name}: FunctionResponse error"
        );
    }
}

#[derive(Deserialize, schemars::JsonSchema)]
#[allow(dead_code)] // Go's handler ignores DelayMS too; the field only shapes the schema.
struct DelayArgs {
    delay_ms: i64,
}

/// Counts one cancellation when the handler's stream ends, whether it saw its context cancelled
/// (Go `case <-ctx.Done()`) or was dropped by its consumer (Go `!yield(...)`).
struct CountOnDrop(Arc<AtomicUsize>);

impl Drop for CountOnDrop {
    fn drop(&mut self) {
        self.0.fetch_add(1, Ordering::SeqCst);
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_handle_function_calls_live_control_plane() {
    let cancel_count = Arc::new(AtomicUsize::new(0));
    let counter = cancel_count.clone();
    let stream_tool: Arc<dyn Tool> = StreamingFunctionTool::new(
        FunctionToolConfig::new("count_forever", "counts indefinitely"),
        move |ctx: Context, _a: DelayArgs| {
            let guard = CountOnDrop(counter.clone());
            futures::stream::unfold((ctx, guard, 0u64), |(ctx, guard, i)| async move {
                tokio::time::sleep(Duration::from_millis(1)).await;
                if ctx.cancellation_token().is_cancelled() {
                    return None;
                }
                Some((Ok(format!("number {i}")), (ctx, guard, i + 1)))
            })
        },
    )
    .unwrap();
    let tools = HashMap::from([("count_forever".to_owned(), stream_tool.clone())]);
    let ctx = inv_ctx();
    let flow = Flow {
        tools: parking_lot::RwLock::new(vec![stream_tool]),
        ..Default::default()
    };

    let live_sess = LiveSessionImpl::new();
    // Go: `go func() { for range liveSess.inputCh {} }()` — drain what the tools send.
    let drain = live_sess.clone();
    let drainer = tokio::spawn(async move {
        let never = CancellationToken::new();
        while drain.next_input(&never).await.is_some() {}
    });
    let live: Arc<dyn LiveSession> = live_sess.clone();

    let start = call_event(&[
        ("call_forever_1", "count_forever", json!({"delay_ms": 1})),
        ("call_forever_2", "count_forever", json!({"delay_ms": 1})),
    ]);
    handle_function_calls_live(&ctx, &flow, &tools, &start, live.clone())
        .await
        .unwrap();
    assert_eq!(
        live_sess.active_streaming_tool_count("count_forever"),
        2,
        "expected 2 active tasks"
    );

    let stop = call_event(&[(
        "call_stop_1",
        "stop_streaming",
        json!({"function_name": "count_forever"}),
    )]);
    let merged = handle_function_calls_live(&ctx, &flow, &tools, &stop, live.clone())
        .await
        .unwrap()
        .expect("non-None mergedStopEvent");
    assert_eq!(
        single_response(&merged).get("status"),
        Some(&json!(
            "Successfully stopped all running instances of count_forever"
        ))
    );

    // Wait (up to 5 s) for both streams to see the cancellation, as assert_no_run_live_leak waits.
    for _ in 0..250 {
        if cancel_count.load(Ordering::SeqCst) >= 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    assert_eq!(
        cancel_count.load(Ordering::SeqCst),
        2,
        "expected exactly 2 streams to be cancelled"
    );
    assert_eq!(
        live_sess.active_streaming_tool_count("count_forever"),
        0,
        "expected registry to be empty after cancellation"
    );

    live.close().await.unwrap();
    tokio::time::timeout(Duration::from_secs(5), drainer)
        .await
        .expect("drainer ends once the session is closed")
        .unwrap();
}

/// Go argsCapturingStreamTool: sends the args RunStream is called with to `got_args`.
struct ArgsCapturingStreamTool {
    got_args: tokio::sync::mpsc::UnboundedSender<Value>,
}

impl Tool for ArgsCapturingStreamTool {
    fn name(&self) -> &str {
        "capture_stream"
    }
    fn description(&self) -> &str {
        "captures its args"
    }
    fn declaration(&self) -> Option<gadk_genai::FunctionDeclaration> {
        Some(gadk_genai::FunctionDeclaration {
            name: self.name().into(),
            description: self.description().into(),
            ..Default::default()
        })
    }
    fn as_streaming(&self) -> Option<&dyn gadk_agent::StreamingTool> {
        Some(self)
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl gadk_agent::StreamingTool for ArgsCapturingStreamTool {
    fn run_stream(
        &self,
        _ctx: Context,
        args: Value,
    ) -> futures::stream::BoxStream<'static, Result<String, gadk_agent::ToolError>> {
        let _ = self.got_args.send(args);
        Box::pin(futures::stream::empty())
    }
}

/// A live-mode call without args reaches the streaming tool as an empty map.
// parity: adapted: a gadk FunctionCall's args are a map (Rust has no nil map), so "no args" is the empty map.
#[tokio::test]
async fn test_handle_function_calls_no_args_reach_live_streaming_tool_as_empty_map() {
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    let st: Arc<dyn Tool> = Arc::new(ArgsCapturingStreamTool { got_args: tx });
    let tools = HashMap::from([("capture_stream".to_owned(), st)]);
    let call_ev = call_event(&[("call_1", "capture_stream", json!({}))]);
    let (live_tx, _live_rx) = tokio::sync::mpsc::unbounded_channel();
    let live: Arc<dyn LiveSession> = Arc::new(MockLiveSession { tx: live_tx });
    handle_function_calls_live(&inv_ctx(), &Flow::default(), &tools, &call_ev, live)
        .await
        .unwrap();
    let got = tokio::time::timeout(Duration::from_secs(5), rx.recv())
        .await
        .expect("streaming tool was not run")
        .expect("streaming tool was not run");
    assert_eq!(got, json!({}), "live streaming tool args");
}

/// Go noRunTool: neither a function tool nor a streaming one.
struct NoRunTool;

impl Tool for NoRunTool {
    fn name(&self) -> &str {
        "no_run"
    }
    fn description(&self) -> &str {
        "has no Run method"
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A call without args to a tool that cannot be run reaches the on-tool-error callback as an
/// empty map.
// parity: adapted: a gadk FunctionCall's args are a map (Rust has no nil map), so "no args" is the empty map.
#[tokio::test]
async fn test_handle_function_calls_no_args_reach_on_tool_error_for_non_function_tool() {
    let got_args = Arc::new(parking_lot::Mutex::new(
        None::<serde_json::Map<String, Value>>,
    ));
    let g = got_args.clone();
    let flow = Flow {
        on_tool_error_callbacks: vec![Arc::new(move |_, _, args, _| {
            *g.lock() = Some(args);
            Box::pin(async { Ok(Some(json!({"handled": true}).as_object().cloned().unwrap())) })
        })],
        ..Default::default()
    };
    let tools: HashMap<String, Arc<dyn Tool>> =
        HashMap::from([("no_run".to_owned(), Arc::new(NoRunTool) as Arc<dyn Tool>)]);
    let call_ev = call_event(&[("call_1", "no_run", json!({}))]);
    handle_function_calls(&inv_ctx(), &flow, &tools, &call_ev, None)
        .await
        .unwrap();
    let got = got_args
        .lock()
        .clone()
        .expect("on-tool-error callback not called");
    assert_eq!(got, serde_json::Map::new(), "on-tool-error args");
}