---
title: "Event Filtering and Redirection Between Autonomous Sub-Agents"
date: "2026-11-30T10:02:02+07:00"
description: "Filter Google ADK's event stream by author, type, and finality, then redirect control between sub-agents with transfer signals and tool actions."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-event-filtering-redirection-sub-agents.jpg"
alt: "Event stream flowing between autonomous ADK sub-agents with filtering and redirection"
tags: ['google-adk', 'multi-agent', 'event-stream', 'control-flow', 'python']
---

Run a coordinator with three sub-agents and print every event the `Runner` yields, and you will see why raw streams are unusable: partial text chunks, function-call requests, function responses, state deltas, transfer signals, and duplicate-looking messages from five different authors, all interleaved in one sequence. Your UI shows tool noise as chat. Your logger double-counts tokens. And somewhere in there, an agent handed control to the wrong peer and nobody noticed.

Events are the *only* medium of communication in the Google Agent Development Kit — the `Runner` yields them, the `SessionService` appends them, agents direct control through them. That makes an event pipeline two things at once: a **filter** (which of these events is user-visible, which belongs to whom) and a **router** (which of these events redirects control).

This tutorial walks both: reading the real fields on `google.adk.events.Event`, filtering a multi-agent stream into per-agent channels, and then driving redirection deliberately — with `transfer_to_agent`, escalation signals, and the auto-return behavior of ADK's collaboration modes.

---

## 1. Anatomy of an ADK Event

An `Event` extends the model's response with ADK metadata. The fields that matter for filtering and redirection:

```
Event
├── author            'user' or the agent name that produced it
├── invocation_id     the whole user-input → final-output cycle
├── id / timestamp    unique id, creation time
├── branch            hierarchy path of the producing agent
├── partial           True while text is still streaming
├── content           google.genai Content (parts: text / function calls / responses)
├── long_running_tool_ids   non-empty ⇒ a long-running tool was called
└── actions (EventActions)
      ├── transfer_to_agent    str   ⇐ redirect control to a named agent
      ├── escalate             bool  ⇐ terminate the enclosing loop
      ├── skip_summarization   bool  ⇐ surface raw tool result as final
      ├── state_delta          dict  ⇐ session.state changes
      └── artifact_delta       dict  ⇐ saved artifacts
```

Three accessor helpers cover most needs: `event.get_function_calls()` (the model asking to run tools), `event.get_function_responses()` (tool output going back), and `event.is_final_response()` (safe to display as this turn's answer). The last one is the workhorse — it filters out partial chunks, function traffic, and mid-stream events for you.

---

## 2. How Events Flow Between Sub-Agents

```
 user message
      │
      ▼
 ┌──────────────┐  yields Event(author='coordinator')   ┌──────────────┐
 │  Runner      │──────────────────────────────────────►│ Session      │
 │  (root agent)│◄──────────────────────────────────────│ Service      │
 └──────┬───────┘   append_event(state_delta applied)   └──────────────┘
        │
        │ model emits transfer_to_agent='tier_2_engineering'
        ▼
 ┌──────────────────┐   yields Event(author='tier_2_...')   ┌──────────┐
 │ tier_2 sub-agent │─────────────────────────────────────►│ your app │
 └──────────────────┘   (filtered by your pipeline)       └──────────┘
```

Every hop is an event: the transfer itself, the sub-agent's tool calls, its responses, its final text. Your application consumes the same stream the `SessionService` records — so a filter written once serves both the live UI and the audit log.

---

## 3. Filtering the Stream Into Per-Agent Channels

The first thing every multi-agent app needs is a classifier: given an event, what is it and who owns it. Here is a compact one built entirely on the documented fields:

```python
from dataclasses import dataclass
from typing import Any, Iterator

from google.adk.events import Event
from google.adk.runners import Runner


@dataclass
class ClassifiedEvent:
    kind: str          # 'user' | 'text' | 'stream' | 'tool_call'
                       # | 'tool_result' | 'transfer' | 'state' | 'other'
    author: str
    payload: Any


def classify(event: Event) -> ClassifiedEvent:
    author = event.author or "unknown"

    if author == "user":
        return ClassifiedEvent("user", author, _text(event))

    if event.actions and event.actions.transfer_to_agent:
        return ClassifiedEvent("transfer", author,
                               event.actions.transfer_to_agent)

    if not (event.content and event.content.parts):
        if event.actions and (event.actions.state_delta
                              or event.actions.artifact_delta):
            return ClassifiedEvent("state", author,
                                   event.actions.state_delta or {})
        return ClassifiedEvent("other", author, None)

    if event.get_function_calls():
        return ClassifiedEvent("tool_call", author, event.get_function_calls())
    if event.get_function_responses():
        return ClassifiedEvent("tool_result", author,
                               event.get_function_responses())
    if event.partial:
        return ClassifiedEvent("stream", author, _text(event))
    return ClassifiedEvent("text", author, _text(event))


def _text(event: Event) -> str:
    if event.content and event.content.parts and event.content.parts[0].text:
        return event.content.parts[0].text
    return ""
```

With that in place, the three filters that show up in almost every build:

```python
def displayable(events) -> Iterator[Event]:
    """Only complete, user-visible answers — the UI channel."""
    for event in events:
        if event.is_final_response() and classify(event).kind == "text":
            yield event

def channel(events, agent_name: str) -> Iterator[Event]:
    """Everything produced by one agent — the per-agent debug channel."""
    for event in events:
        if event.author == agent_name:
            yield event

def transitions(events) -> Iterator[Event]:
    """Control handoffs only — the routing audit channel."""
    for event in events:
        c = classify(event)
        if c.kind in ("transfer",) or (event.author in ("coordinator",)
                                       and event.get_function_calls()):
            yield event
```

Two refinements worth knowing:

- **`event.partial`** is `True` while text is streaming. If you are accumulating streamed output, buffer `stream` events and flush on the first non-partial `text` event — otherwise you will print five fragments and one duplicate.
- **`event.branch`** records the hierarchy path of the producing agent. In nested trees it lets you group events by lineage rather than guessing from the author string alone.

---

## 4. Redirection: Making Control Flow Explicit

Filtering observes control flow; redirection *creates* it. There are three sanctioned mechanisms.

### 4.1 The model-initiated transfer

When an agent has `sub_agents=[...]`, ADK exposes a delegation tool for each. The model calls it, and the resulting event carries `actions.transfer_to_agent = "<target>"`. This is the ambient, LLM-driven path — appropriate for intent routing, unsuitable for guarantees.

### 4.2 The tool-initiated transfer

A function tool can redirect deterministically by declaring a `ToolContext` parameter and setting the action itself:

```python
from google.adk.tools import ToolContext

def fetch_customer_record(customer_id: str, tool_context: ToolContext) -> dict:
    """Loads a record and routes by plan tier — no LLM judgment involved."""
    plan = {"C-900": "enterprise"}.get(customer_id, "free")

    tool_context.state["support:plan"] = plan

    if plan == "enterprise":
        # Deterministic redirection: the model does not get a say.
        tool_context.actions.transfer_to_agent = "vip_desk"
        return {"status": "success", "routed_to": "vip_desk"}
    return {"status": "success", "routed_to": None}
```

The tool result and the transfer travel back in the same step, so the caller sees both *what was found* and *where control went*. Use this whenever policy — SLA eligibility, permission tiers, safety rules — decides the target.

### 4.3 Escalation and structured returns

`event.actions.escalate` tells a loop-style construct to terminate; `skip_summarization` marks a tool result as final so raw data reaches the consumer instead of being paraphrased by the model. Both are redirection in the vertical direction — out of a cycle, out of a layer — rather than sideways between peers.

ADK's collaboration modes cover the fourth case: a sub-agent declared with `mode="task"` (clarify with the user, then return) or `mode="single_turn"` (no user interaction) **returns control automatically** on completion, and a `single_turn` agent placed in a parallel workflow returns results without a `transfer_to_agent` call at all. For autonomous pipelines, that removes the single most common bug in chat-mode fleets: a specialist that finishes its work and then keeps talking.

```python
from google.adk import Agent

log_lookup = Agent(
    name="log_lookup",
    mode="single_turn",          # runs, returns, done — no handoff needed
    instruction="Fetch the trace for the given request id and return it.",
    tools=[fetch_trace],
)

orchestrator = Agent(
    name="orchestrator",
    instruction="Investigate using `log_lookup`, then summarize for the user.",
    sub_agents=[log_lookup],
)
```

---

## 5. Putting It Together: An Event Router

A small observer that combines both halves — it filters the stream and reacts to redirection signals as they pass:

```python
class EventRouter:
    """Splits a run into display, audit, and routing channels."""

    def __init__(self, runner: Runner):
        self.runner = runner
        self.transfers: list[tuple[str, str]] = []   # (from_agent, to_agent)
        self.per_agent: dict[str, list[Event]] = {}

    async def run(self, user_id: str, session_id: str, message: str):
        from google.genai import types

        chunks: list[str] = []
        async for event in self.runner.run_async(
            user_id=user_id,
            session_id=session_id,
            new_message=types.Content(role="user",
                                      parts=[types.Part(text=message)]),
        ):
            c = classify(event)
            self.per_agent.setdefault(event.author or "?", []).append(event)

            if c.kind == "transfer":
                self.transfers.append((event.author, c.payload))
                print(f"  ⇢ {event.author} -> {c.payload}")

            elif c.kind == "stream":
                chunks.append(c.payload)

            elif event.is_final_response() and c.kind == "text":
                answer = "".join(chunks) + c.payload
                chunks.clear()
                yield answer.strip()
            # 'state', 'tool_call', 'tool_result' are recorded, not displayed
```

Notice the discipline: **display channel** (`is_final_response` + text), **audit channel** (everything, bucketed by author), **routing channel** (`transfer_to_agent` events). One pass over the stream feeds all three, and nothing leaks between them — the same separation you would want from the sub-agents themselves.

---

## 6. Debugging Redirection Failures

When control goes somewhere unexpected, the event stream tells you exactly where. In order of likelihood:

1. **No transfer event at all.** The model never called the delegation tool — usually a vague `description` on the intended sub-agent.
2. **Transfer to an unintended peer.** Two sub-agent descriptions overlap; the model picked the wrong one. Narrow the descriptions before touching instructions.
3. **Transfer fired but the target never responded.** Check whether the target agent is reachable from the current agent — transfers work between agents that share a root tree.
4. **Specialist keeps talking instead of returning.** It is in default `chat` mode; either instruct an explicit `transfer_to_agent` back, or move it to `task`/`single_turn` for automatic return.
5. **Your UI shows nothing.** The output is probably partial-chunk filtered — accumulate `stream` events rather than waiting for a single non-partial one.

---

## 7. Checklist

- [ ] Classify every event once (`user` / `text` / `stream` / `tool_*` / `transfer` / `state`) and fan out to channels.
- [ ] Display only `event.is_final_response()` events; accumulate partials before flushing.
- [ ] Record `event.author`, `event.branch`, and `event.invocation_id` for audit trails.
- [ ] Use model-initiated `transfer_to_agent` for intent routing, `tool_context.actions.transfer_to_agent` for policy.
- [ ] Prefer `task` / `single_turn` modes for autonomous sub-agents so control returns automatically.
- [ ] Assert on the transfer log in tests — an unexpected handoff is a regression, not a surprise.
- [ ] Persist with a real `SessionService` so the filtered channels can be replayed after incidents.

## Sources
- Google ADK Documentation: https://adk.dev/
- Events reference: https://adk.dev/events/
- Collaborative workflows and agent modes: https://adk.dev/workflows/collaboration/
