---
title: "Combining Deterministic Python Logic with Probabilistic Agent Handoffs"
date: "2026-11-30T10:27:02+07:00"
description: "Blend guaranteed Python checks with LLM-driven handoffs in Google ADK: custom BaseAgent policy gates, session state as the contract, and bounded workflow loops."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-deterministic-logic-probabilistic-handoffs.jpg"
alt: "Diagram of deterministic Python gate agent handing off to probabilistic LLM agents in Google ADK"
tags: ['google-adk', 'multi-agent', 'deterministic-logic', 'handoffs', 'python', 'workflow-agents']
---

A refund endpoint either refunds the money or it does not. A tax calculation either produces the correct number or it does not. Yet almost every agent tutorial puts a language model in charge of exactly these steps, and then teams wonder why their "agentic refund flow" occasionally approves a $900 refund on a $9 order.

The real production shape of an agent system is a sandwich: **deterministic Python code for anything that must be true, probabilistic LLM agents for anything that must be understood**. The hard part is not writing either half — it is the seam between them: when and how does control move from verified code into a model that guesses, and back again?

In this tutorial we build that seam in Google Agent Development Kit (ADK). We will write a custom non-LLM agent that performs hard validation in plain Python, use session state as the contract between deterministic and probabilistic layers, and wire LLM handoffs with `sub_agents`, `SequentialAgent`, and `LoopAgent` so the stochastic parts only run when the deterministic gates say they may.

---

## 1. The Two Kinds of Logic, and the Handoff Problem

It helps to classify every step of your workflow along one axis:

```
   DETERMINISTIC                                PROBABILISTIC
   ─────────────────────────────────────────────────────────────►
   schema checks      business rules        intent parsing
   arithmetic         idempotency guards    free-text repair
   permission checks  state machines        customer replies
        │                                          │
        └────────────── who decides? ──────────────┘
                   (this is the handoff)
```

A **handoff** in ADK is any moment where control moves from one agent to another. ADK gives you two flavors:

- **Deterministic handoffs**: your Python code explicitly calls `sub_agent.run_async(ctx)` (inside a custom `BaseAgent`) or relies on a template workflow such as `SequentialAgent` to run sub-agents in a fixed order. The model never chooses the next step.
- **Probabilistic handoffs**: an `LlmAgent` decides, via the `transfer_to_agent(agent_name=...)` function call exposed by ADK's auto flow, which sub-agent should take over next.

Most failures come from letting the second kind decide things that belong to the first kind. The fix is architecture, not prompt engineering.

---

## 2. Mapping the Spectrum onto ADK Primitives

ADK's component model maps cleanly onto the spectrum:

| Layer | ADK primitive | Behavior |
|---|---|---|
| Hard rules | Custom `BaseAgent` subclass | `async def _run_async_impl(self, ctx)` — pure Python, yields `Event`s, zero model calls |
| Ordering | `SequentialAgent` | Runs `sub_agents` in list order against the same `InvocationContext` |
| Retries | `LoopAgent` | Repeats sub-agents until `max_iterations` or an `Event` with `escalate=True` |
| Choice | `Agent(sub_agents=[...])` | Model picks the next agent with `transfer_to_agent` |
| Composition | `AgentTool` | Exposes a whole agent as a callable tool of another agent |

The mental model is a pipeline where the model is only consulted where ambiguity actually exists:

```
   ┌────────────────────┐     ┌────────────────────┐     ┌────────────────────┐
   │  ValidateOrder     │     │  ClarifyIntent     │     │  DraftReply        │
   │  (custom BaseAgent)│ ──► │  (LlmAgent,        │ ──► │  (LlmAgent,        │
   │  pure Python       │     │   probabilistic)   │     │   probabilistic)   │
   └────────────────────┘     └────────────────────┘     └────────────────────┘
         gate: pass/fail             handoff: transfer      handoff: none
         rule: always                 rule: model decides    rule: always
```

A quick note on version drift: ADK 2.0 introduces graph-based and dynamic workflows that supersede some template-workflow patterns, and `SequentialAgent` / `ParallelAgent` / `LoopAgent` are deprecated in the Python and TypeScript SDKs in favor of the newer `Workflow` construct. The architecture in this post is unchanged either way — the gate-then-handoff split is what matters, and both the template workflows and the newer graph workflows express it the same way.

---

## 3. Building the Deterministic Gate Agent

The gate is a class that inherits from `google.adk.agents.BaseAgent` and implements `_run_async_impl`. No model, no prompt, no temperature — just Python, plus an `Event` carrying the verdict.

```python
from typing import AsyncGenerator, Any

from google.adk.agents import BaseAgent, Agent, SequentialAgent, LoopAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event, EventActions
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from pydantic import BaseModel


class RefundRequest(BaseModel):
    order_id: str
    amount_usd: float
    customer_id: str


class RefundGate(BaseAgent):
    """Deterministic policy check. Emits events, never calls a model."""

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        request = ctx.session.state.get("refund_request")
        errors = []

        if not request:
            errors.append("missing_refund_request")
        else:
            if request.amount_usd <= 0:
                errors.append("non_positive_amount")
            if request.amount_usd > 250.0:
                errors.append("exceeds_auto_approve_limit")
            if not request.order_id.startswith("ORD-"):
                errors.append("malformed_order_id")

        passed = not errors
        # Every write to session state is surfaced as event.actions.state_delta
        ctx.session.state["gate_result"] = "pass" if passed else "fail"
        ctx.session.state["gate_errors"] = errors

        yield Event(
            author=self.name,
            content=None,
            actions=EventActions(),
        )
```

Two details worth internalizing:

1. **State is the contract.** Writes to `ctx.session.state` are recorded by the `SessionService` as a `state_delta` on the event the agent emits, so your UI or audit log can read `event.actions.state_delta` and see exactly when `gate_result` flipped to `"fail"`.
2. **The gate is testable in isolation.** You can unit-test `RefundGate` with a plain `asyncio.run` harness — no API key, no flaky model. That is the entire point of keeping policy out of the prompt.

---

## 4. The Probabilistic Half: Structured, but Not Guaranteed

Once the gate passes, ambiguity is allowed back in. The downstream agent's job is wording, clarification, and tone — tasks a model is good at and a rule engine is not:

```python
refund_explainer = Agent(
    name="refund_explainer",
    model="gemini-3.8-flash",
    description="Explains an approved refund to the customer in warm, clear language.",
    instruction="""
    The session state contains 'refund_request' and gate_result='pass'.
    Write a short customer-facing message confirming the refund.
    Mention the amount and order ID exactly as they appear in state.
    Do not invent timelines, reference numbers, or policies.
    """,
    output_key="customer_message",
)
```

Note what the instruction does **not** say: it never asks the model to decide *whether* the refund is allowed. That decision already happened in `RefundGate`. The probabilistic agent operates inside a corridor the deterministic layer built for it, and `output_key="customer_message"` writes its reply back to `session.state` so the rest of the pipeline can read it.

For genuinely ambiguous routing — "is this a refund question or a shipping question?" — you let the model choose by declaring `sub_agents` on a front-facing `Agent`. ADK exposes `transfer_to_agent(agent_name=...)` to the LLM, and control moves to whichever specialist the model picks. Use this for **routing between conversations**, never for **passing business rules**.

---

## 5. Assembling the Deterministic → Probabilistic Sandwich

Now compose the pieces. The outer structure is deterministic; only the inner nodes are stochastic:

```python
validate = RefundGate(name="refund_policy_gate")          # deterministic
explain = refund_explainer                               # probabilistic

# Retry wrapper: if the drafted message fails a deterministic lint, redo it.
explain_and_check = LoopAgent(
    name="message_retry_loop",
    max_iterations=3,
    sub_agents=[
        explain,
        RefundGate(name="refund_policy_gate"),  # re-verifies state before accept
    ],
)

pipeline = SequentialAgent(
    name="refund_flow",
    sub_agents=[validate, explain_and_check],
)


async def main():
    session_service = InMemorySessionService()
    runner = Runner(
        agent=pipeline,
        app_name="refund_service",
        session_service=session_service,
    )
    session = await session_service.get_or_create(
        app_name="refund_service", user_id="customer_77"
    )
    # Seed the deterministic layer with structured input.
    session.state["refund_request"] = RefundRequest(
        order_id="ORD-10482", amount_usd=49.0, customer_id="customer_77"
    )

    async for event in runner.run_async(
        session=session, message="Please refund my last order."
    ):
        if event.actions and event.actions.state_delta:
            print("state:", event.actions.state_delta)
        if event.is_final_response() and event.content and event.content.parts:
            print("assistant:", event.content.parts[0].text)
```

The event stream makes the seam visible: first you see `{"gate_result": "pass"}` in a `state_delta`, then the LLM's tokens, then possibly another `state_delta` from the retry loop. Determinism frames the conversation; the model fills the frame.

---

## 6. Why This Split Survives Production

**Auditability.** Because policy lives in `Event`-emitting code rather than prompt text, every accept/reject is reconstructible from `session.events` — you can replay why a refund was blocked six months later.

**Cost control.** Deterministic gates run for free. Gate the expensive model calls behind them and you stop paying for LLM turns on requests that were never eligible.

**Graceful degradation.** If a model degrades or times out mid-conversation, your gates still enforce the rules. The system falls back to "no message sent," not "wrong message sent."

**Independent testing.** The probabilistic halves need evaluation datasets; the deterministic halves need unit tests. Keeping them in separate classes means each gets the testing style it deserves.

---

## 7. Checklist: Where Does Each Decision Live?

Before you ship, walk your workflow and assign every decision to exactly one layer:

1. **Money, permissions, schema, arithmetic** → custom `BaseAgent` gate, unit-tested, zero model calls.
2. **Ordering of steps** → `SequentialAgent` (or a graph workflow on ADK 2.0), never the model.
3. **Retry-until-condition** → `LoopAgent` with `max_iterations` plus an `escalate=True` exit — always cap the iterations.
4. **Wording, tone, clarification of already-validated facts** → `Agent` with an `output_key`.
5. **Routing between conversation domains** → `sub_agents` + `transfer_to_agent`, with a precise `description` per specialist.
6. **State as the only inter-layer contract** → write via `ctx.session.state` or `output_key`, read it back, and monitor `event.actions.state_delta` in your observability stack.

If a rule can be violated by a badly behaved model, it does not belong in a prompt. Put it in the gate, and let the model do what models are actually good at: talking to humans.

## Sources
- Google ADK Documentation: https://adk.dev/
- Custom agent template workflows: https://adk.dev/agents/custom-agents/
- Events: https://adk.dev/events/
- Conversational context (Session, State, Memory): https://adk.dev/sessions/
