gadk-engine 0.5.9

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

//! The LLM agent: construction (`new`, task-tool installation), the run closure, live mode
//! (`LlmLive`, installed as `AgentState.live`) and output-key saving, plus the `WrappedSession`
//! used when the agent runs as a workflow node.
//!
//! `Agent::find_agent` is the provided method; workflow nodes run an LLM agent through explicit
//! `run_llm_agent_as_node` calls.

use std::any::Any;
use std::sync::Arc;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::StreamExt;
use gadk_agent::{
    Agent, AgentConfig, AgentError, AgentRunFn, AgentState, AgentType, ContextDelta, EventStream,
    InvocationContext, LiveAgent, LiveSession, Mode,
};
use gadk_session::{Event, Session, State};
use serde_json::{Map, Value};

use crate::llm::config::LlmAgentConfig;
use crate::llm::flow::Flow;
use crate::llm::mode::resolve_mode;
use crate::llm::processors::{default_request_processors, default_response_processors};
use crate::llm::state::{LlmAgentState, reveal, reveal_arc};
use crate::tool::finish_task::FinishTaskTool;
use crate::tool::single_turn::SingleTurnTool;
use crate::tool::task_agent_tool::TaskAgentTool;
use crate::workflow::route::go_quote;

/// Builds an LLM agent from its configuration.
pub fn new(cfg: LlmAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
    // The state starts with a clone of the configured tools.
    let state = Arc::new(LlmAgentState::new(cfg.clone()));

    let run_state = Arc::clone(&state);
    let run: AgentRunFn =
        Arc::new(move |ctx: InvocationContext| run_flow(Arc::clone(&run_state), ctx));

    let hook_state = Arc::clone(&state);
    let agent_state = AgentState {
        agent_type: AgentType::LlmAgent,
        config: Some(Arc::clone(&state) as Arc<dyn Any + Send + Sync>),
        // The before-agent-callback event hook. A before-agent
        // callback that returns content short-circuits the run, so its event never reaches
        // run_flow; this gives it the same output_key handling.
        on_before_agent_callback_event: Some(Arc::new(move |ev: &mut Event| {
            maybe_save_output_to_state(&hook_state, ev)
        })),
        // The agent supports live mode.
        live: Some(Arc::new(LlmLive)),
    };

    let agent = gadk_agent::agent::new_with_state(
        AgentConfig {
            name: cfg.name,
            description: cfg.description,
            sub_agents: cfg.sub_agents,
            before_agent_callbacks: cfg.before_agent_callbacks,
            after_agent_callbacks: cfg.after_agent_callbacks,
            run: Some(run),
        },
        agent_state,
    )
    .map_err(|e| AgentError::Config(format!("failed to create agent: {e}")))?;

    install_task_tools(&agent, &state)?;
    Ok(agent)
}

/// Installs the task tools: for a task-mode agent its `finish_task` tool, and for each task or
/// single_turn sub-agent a delegation tool.
///
/// Creating a single_turn tool never fails and a task-agent tool fails only for a missing
/// agent, which Rust cannot express, so neither has an error branch here.
fn install_task_tools(agent: &Arc<dyn Agent>, state: &LlmAgentState) -> Result<(), AgentError> {
    if state.cfg.mode == Mode::Task {
        let finish = FinishTaskTool::new(agent.as_ref()).map_err(|e| {
            AgentError::Config(format!(
                "installing `finish_task` tool for agent {}: {e}",
                go_quote(agent.name())
            ))
        })?;
        state.tools.write().push(finish);
    }
    for sub in agent.sub_agents() {
        let Some(sub_state) = reveal(sub.as_ref()) else {
            continue;
        };
        // A sub-agent that declares no mode is a chat peer, reached via transfer_to_agent
        // rather than through a tool on the parent. The declaration is read on purpose: this
        // decides the tree shape, not a per-run placement.
        match resolve_mode(sub_state.cfg.mode, Mode::Chat) {
            Mode::SingleTurn => state
                .tools
                .write()
                .push(SingleTurnTool::new(Arc::clone(sub))),
            Mode::Task => state
                .tools
                .write()
                .push(TaskAgentTool::new(Arc::clone(sub))),
            Mode::Unset | Mode::Chat => {}
        }
    }
    Ok(())
}

/// The flow built by both `run` and live mode. `Flow::tools` stays at
/// its default: the tools processor fills it.
fn build_flow(state: &LlmAgentState) -> Arc<Flow> {
    let cfg = &state.cfg;
    Arc::new(Flow {
        model: cfg.model.clone(),
        request_processors: default_request_processors(),
        response_processors: default_response_processors(),
        before_model_callbacks: cfg.before_model_callbacks.clone(),
        after_model_callbacks: cfg.after_model_callbacks.clone(),
        on_model_error_callbacks: cfg.on_model_error_callbacks.clone(),
        before_tool_callbacks: cfg.before_tool_callbacks.clone(),
        after_tool_callbacks: cfg.after_tool_callbacks.clone(),
        on_tool_error_callbacks: cfg.on_tool_error_callbacks.clone(),
        ..Default::default()
    })
}

/// The agent's run closure: builds the flow and runs it.
///
/// `CustomAgent::run` (built by `new_with_state`) already rebinds `ctx`'s agent to this agent
/// before calling this closure, so no rebinding happens here.
fn run_flow(state: Arc<LlmAgentState>, ctx: InvocationContext) -> EventStream {
    let flow = build_flow(&state);
    Box::pin(flow.run(ctx).map(move |item| {
        item.map(|mut ev| {
            maybe_save_output_to_state(&state, &mut ev);
            ev
        })
    }))
}

/// Live-mode entry point, installed as `AgentState.live` by [`new`]. Stateless: it resolves
/// the agent from `ctx.agent()` (the caller passes a context whose current agent is this agent),
/// so it holds no reference to the agent and creates no cycle.
pub(crate) struct LlmLive;

#[async_trait]
impl LiveAgent for LlmLive {
    /// A fresh invocation context, the agent's flow in live mode, and the output_key
    /// save on every event that is not an error.
    ///
    /// `ctx.agent()` must be this agent: the agent (its model, tools and output key) is resolved
    /// from the context, so a context whose current agent is another agent runs that agent
    /// instead. `Agent::as_live` callers derive the context for the agent they call it on.
    async fn run_live(
        &self,
        ctx: InvocationContext,
    ) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
        let agent = ctx.agent();
        let state = reveal_arc(&*agent).ok_or_else(|| {
            AgentError::Config(format!(
                "agent {} is not an LlmAgent",
                go_quote(agent.name())
            ))
        })?;
        // `fresh_invocation` resets the isolation scope,
        // so it is set back to the caller's; the other params carry over unchanged.
        let ictx = ctx.with_delta(ContextDelta {
            agent: Some(Arc::clone(&agent)),
            isolation_scope: Some(ctx.isolation_scope()),
            fresh_invocation: true,
            ..Default::default()
        });
        let flow = build_flow(&state);
        let (sess, inner) = crate::llm::live::flow::run_live(flow, ictx)?;
        let wrapped = inner.map(move |item| {
            item.map(|mut ev| {
                maybe_save_output_to_state(&state, &mut ev);
                ev
            })
        });
        Ok((sess, Box::pin(wrapped)))
    }
}

/// Saves the model output to `state_delta[output_key]` when this agent authored a final text
/// response. Never
/// touches `event.output` (the node wrapper stamps output). A task agent's text turns are never
/// saved: its result is the finish_task output, which the node wrapper's
/// `run_task` writes to `output_key` when the agent is entered as a node.
pub(crate) fn maybe_save_output_to_state(state: &LlmAgentState, event: &mut Event) {
    if event.author != state.cfg.name {
        // Skip: the event was authored by another agent.
        return;
    }
    // A task agent delivers its result through finish_task, which run_task writes to
    // output_key. Its text turns (a clarification question, a greeting) are not the result.
    // run_task runs only when the task agent is entered as a node, whichever agent sits above
    // it; when it is run through `run` (as the sequential, loop and parallel agents do) or
    // `run_live`, nothing writes the finish_task output, so output_key stays unset. Matches
    // adk-python's __maybe_save_output_to_state.
    if state.cfg.mode == Mode::Task {
        return;
    }
    if state.cfg.output_key.is_empty() || !event.is_final_response() {
        return;
    }
    let Some(content) = event.response.content.as_ref() else {
        return;
    };
    if content.parts.is_empty() {
        return;
    }
    let mut result = String::new();
    let mut has_text_part = false;
    for part in &content.parts {
        if !part.text.is_empty() && !part.thought {
            has_text_part = true;
            result.push_str(&part.text);
        }
    }
    if !has_text_part {
        return;
    }
    // Output schema validation and unmarshalling are not done here. An all-whitespace result is the
    // empty final chunk of a stream; do not save it.
    if state.cfg.output_schema.is_some() && result.trim().is_empty() {
        return;
    }
    event
        .actions
        .state_delta
        .get_or_insert_with(Map::new)
        .insert(state.cfg.output_key.clone(), Value::String(result));
}

/// A read view of `inner` with
/// one synthetic seed event inserted at the event count snapshotted at creation. The seed is
/// never written to `inner`.
pub(crate) struct WrappedSession {
    inner: Arc<dyn Session>,
    seed: Event,
    insert_at: usize,
}

impl WrappedSession {
    /// A view of `inner` with `seed` inserted at the current event count.
    pub(crate) fn new(inner: Arc<dyn Session>, seed: Event) -> Self {
        let insert_at = inner.events().len();
        Self {
            inner,
            seed,
            insert_at,
        }
    }

    /// The session underneath the view.
    pub(crate) fn inner(&self) -> &Arc<dyn Session> {
        &self.inner
    }
}

impl Session for WrappedSession {
    fn id(&self) -> &str {
        self.inner.id()
    }

    fn app_name(&self) -> &str {
        self.inner.app_name()
    }

    fn user_id(&self) -> &str {
        self.inner.user_id()
    }

    fn state(&self) -> &dyn State {
        self.inner.state()
    }

    /// All of the view's events (collapsed, as Rust `Session::events` returns a
    /// `Vec`): the seed sits at `insert_at`, or at the end when the underlying session has
    /// fewer events than at the snapshot.
    fn events(&self) -> Vec<Event> {
        let mut evs = self.inner.events();
        let at = self.insert_at.min(evs.len());
        evs.insert(at, self.seed.clone());
        evs
    }

    fn last_update_time(&self) -> DateTime<Utc> {
        self.inner.last_update_time()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// The session underneath any [`WrappedSession`]. Anything that must WRITE to the
/// session (e.g. `SessionService::append_event`, whose in-memory implementation downcasts to its
/// own type) must pass `underlying_session(&ctx.session())`, never the wrapped view.
pub(crate) fn underlying_session(session: &Arc<dyn Session>) -> Arc<dyn Session> {
    match session.as_any().downcast_ref::<WrappedSession>() {
        Some(w) => underlying_session(w.inner()),
        None => Arc::clone(session),
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use gadk_genai::Content;
    use gadk_model::{Llm, LlmResponse};
    use serde_json::json;

    use crate::testutil::{MockModel, collect_events};

    #[test]
    fn task_mode_installs_finish_task_and_sub_agent_tools_in_order() {
        let st = new(LlmAgentConfig {
            name: "st".into(),
            mode: Mode::SingleTurn,
            ..Default::default()
        })
        .unwrap();
        let tk = new(LlmAgentConfig {
            name: "tk".into(),
            mode: Mode::Task,
            ..Default::default()
        })
        .unwrap();
        let chat = new(LlmAgentConfig {
            name: "chat".into(),
            ..Default::default()
        })
        .unwrap();
        let a = new(LlmAgentConfig {
            name: "root".into(),
            mode: Mode::Task,
            sub_agents: vec![st, tk, chat],
            ..Default::default()
        })
        .unwrap();
        let names: Vec<String> = reveal(a.as_ref())
            .unwrap()
            .tools
            .read()
            .iter()
            .map(|t| t.name().to_string())
            .collect();
        assert_eq!(names, vec!["finish_task", "st", "tk"]);
        let tools = reveal(a.as_ref()).unwrap().tools.read().clone();
        assert!(
            tools[1].as_any().is::<SingleTurnTool>() && tools[2].as_any().is::<TaskAgentTool>()
        );
    }

    #[test]
    fn duplicate_sub_agent_is_rejected_with_go_prefix() {
        let s = new(LlmAgentConfig {
            name: "s".into(),
            ..Default::default()
        })
        .unwrap();
        let err = new(LlmAgentConfig {
            name: "p".into(),
            sub_agents: vec![s.clone(), s],
            ..Default::default()
        })
        .err()
        .unwrap();
        assert!(
            err.to_string().starts_with("failed to create agent: "),
            "{err}"
        );
    }

    #[test]
    fn agent_state_is_llm_agent_with_save_hook() {
        let a = new(LlmAgentConfig {
            name: "a".into(),
            output_key: "k".into(),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(a.agent_state().agent_type, AgentType::LlmAgent);
        let hook = a
            .agent_state()
            .on_before_agent_callback_event
            .clone()
            .unwrap();
        let mut ev = Event {
            author: "a".into(),
            ..Default::default()
        };
        ev.response.content = Some(Content::from_text("cb text", "model"));
        hook(&mut ev);
        assert_eq!(
            ev.actions.state_delta.unwrap().get("k"),
            Some(&json!("cb text"))
        );
    }

    #[tokio::test]
    async fn run_drives_flow_and_saves_output_key() {
        let model = MockModel::new(vec![Ok(LlmResponse {
            content: Some(Content::from_text("hello", "model")),
            ..Default::default()
        })]);
        let a = new(LlmAgentConfig {
            name: "a".into(),
            model: Some(model.clone() as Arc<dyn Llm>),
            output_key: "out".into(),
            ..Default::default()
        })
        .unwrap();
        let ic = InvocationContext::builder()
            .agent(a.clone())
            .build_invocation();
        let events = collect_events(a.run(ic)).await.unwrap();
        let last = events.last().unwrap();
        assert_eq!(last.author, "a");
        assert_eq!(
            last.actions.state_delta.as_ref().unwrap().get("out"),
            Some(&json!("hello"))
        );
        assert_eq!(model.requests().len(), 1);
    }

    use futures::StreamExt;
    use gadk_agent::{LiveRunConfig, RunConfig, StreamingMode};

    use crate::llm::live::test_server::ScriptedLiveLlm;

    fn live_ctx(agent: Arc<dyn Agent>) -> InvocationContext {
        InvocationContext::builder()
            .agent(agent)
            .run_config(RunConfig {
                streaming_mode: StreamingMode::Bidi,
                live: Some(LiveRunConfig::default()),
                ..Default::default()
            })
            .build_invocation()
    }

    #[test]
    fn llm_agent_is_live_capable() {
        let a = new(LlmAgentConfig {
            name: "a".into(),
            ..Default::default()
        })
        .unwrap();
        assert!(a.as_live().is_some());
        assert!(a.agent_state().live.is_some());
    }

    /// Go llmAgent.RunLive wraps the flow's iterator with maybeSaveOutputToState for every event
    /// that carries no error.
    #[tokio::test]
    async fn run_live_saves_output_key() {
        let model = ScriptedLiveLlm::new(
            "live-model",
            vec![LlmResponse {
                content: Some(Content::from_text("hello live", "model")),
                turn_complete: true,
                ..Default::default()
            }],
        );
        let a = new(LlmAgentConfig {
            name: "a".into(),
            model: Some(model.clone() as Arc<dyn Llm>),
            output_key: "out".into(),
            ..Default::default()
        })
        .unwrap();
        let (sess, mut events) = a
            .as_live()
            .unwrap()
            .run_live(live_ctx(a.clone()))
            .await
            .unwrap();
        let ev = loop {
            let ev = tokio::time::timeout(std::time::Duration::from_secs(5), events.next())
                .await
                .expect("timed out waiting for the model event")
                .expect("stream ended before the model event")
                .unwrap();
            if ev.response.content.is_some() {
                break ev;
            }
        };
        assert_eq!(ev.author, "a");
        assert_eq!(
            ev.actions.state_delta.as_ref().unwrap().get("out"),
            Some(&json!("hello live"))
        );
        sess.close().await.unwrap();
        assert!(
            tokio::time::timeout(std::time::Duration::from_secs(5), events.next())
                .await
                .expect("the live stream did not end")
                .is_none()
        );
    }

    /// Go RunLive runs the flow on icontext.NewInvocationContext, whose resumption handle starts
    /// empty and is not the caller's: a handle the model sends is stored in the new context only.
    #[tokio::test]
    async fn run_live_uses_a_fresh_resumption_handle_slot() {
        let model = ScriptedLiveLlm::new(
            "live-model",
            vec![
                LlmResponse {
                    session_resumption_handle: "inner-handle".into(),
                    ..Default::default()
                },
                LlmResponse {
                    content: Some(Content::from_text("after handle", "model")),
                    ..Default::default()
                },
            ],
        );
        let a = new(LlmAgentConfig {
            name: "a".into(),
            model: Some(model.clone() as Arc<dyn Llm>),
            ..Default::default()
        })
        .unwrap();
        let outer = live_ctx(a.clone());
        outer.set_live_session_resumption_handle("outer-handle");
        let (sess, mut events) = a.as_live().unwrap().run_live(outer.clone()).await.unwrap();
        // The reader stores the handle before it hands the event on, so once the content event
        // arrives the flow's context already holds "inner-handle".
        loop {
            let ev = tokio::time::timeout(std::time::Duration::from_secs(5), events.next())
                .await
                .expect("timed out")
                .expect("stream ended early")
                .unwrap();
            if ev.response.content.is_some() {
                break;
            }
        }
        assert_eq!(outer.live_session_resumption_handle(), "outer-handle");
        sess.close().await.unwrap();
    }
}