Building Non-LLM Base Agents: Deterministic Rules and Custom BaseAgent Subclasses
Not every agent needs a model. Subclass BaseAgent, implement _run_async_impl, and ship deterministic validators, escalators, and guards that run without a single LLM call.
Published on • November 24, 2026
AI Assistant

Most ADK examples start and end with LlmAgent, but the framework’s base class is deliberately model-free: a BaseAgent subclass with a hand-written _run_async_impl gives you an agent that runs pure Python — validators, policy checks, state escalators, external API fan-out — with zero tokens, zero latency variance, and behavior you can unit test like any other code.
This tutorial covers the BaseAgent contract, a complete deterministic agent you can drop into a hierarchy, the Pydantic-level rules that govern sub-agent wiring, and how these agents terminate loops. We stay scoped to custom non-LLM agents; for orchestration built from these pieces, see adk-agent-swarm-multi-agent-systems.md.
The Contract
A custom agent is any class inheriting from google.adk.agents.BaseAgent that implements one method:
async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
Facts that matter, from the ADK implementation:
- It must be an
async defreturning anAsyncGenerator[Event, None]; youyieldevents back to the Runner. - Skip the override and the base class raises
NotImplementedError: _run_async_impl for <class> is not implemented.the moment it runs. _run_live_implhas the same signature; without it,run_live()raisesNotImplementedError.ctxis theInvocationContext—ctx.session.stateis your read/write channel to the rest of the invocation.
A Deterministic Validator
from typing import AsyncGenerator
from google.adk.agents import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event, EventActions
from google.genai import types
class PiiGuard(BaseAgent):
"""Blocks responses that would leak PII — no model required."""
async def _run_async_impl(
self, ctx: InvocationContext
) -> AsyncGenerator[Event, None]:
draft = ctx.session.state.get("draft_reply", "")
if contains_pii(draft):
ctx.session.state["draft_reply"] = ""
yield Event(
author=self.name,
actions=EventActions(state_delta={"draft_reply": ""}),
content=types.Content(
role="model",
parts=[types.Part(text="Draft contained PII; it was dropped.")],
),
)
return
yield Event(author=self.name, actions=EventActions(escalate=False))
Everything about this agent is inspectable: the rule is a function call, the state write rides the yielded event’s state_delta (so the Runner commits it before anything downstream resumes), and tests need no API key.
Hierarchy Rules You Cannot Skip
BaseAgent is a Pydantic model with extra='forbid', and wiring it into a tree has hard rules:
coordinator = LlmAgent(
name="Coordinator",
model="gemini-flash-latest",
sub_agents=[greeter, task_doer], # task_doer is a custom non-LLM agent
)
- Declare sub-agents as fields. Because
extra='forbid', storing an undeclared attribute in__init__raisesValueError— annotate class-level fields (e.g.guard: PiiGuard) and pass them throughsuper().__init__(...). - Pass
sub_agentsto the constructor. The framework setsparent_agentfor you and needs the list for lifecycle management and introspection — even when_run_async_implcallsself.guarddirectly. - Single parent only. Re-parenting an existing instance raises
ValueError: Agent 'x' already has a parent agent...; build a second instance with a differentnameinstead. - Names must be unique identifiers in the tree and cannot be
user—find_agent(name)does a depth-first walk and returns the first match.
Escalating Out of Loops
Non-LLM agents shine as loop terminators. LoopAgent stops when any sub-agent yields an event with escalate=True in its actions, or when max_iterations is hit:
from google.adk.agents import LoopAgent, LlmAgent
class CheckCondition(BaseAgent):
async def _run_async_impl(self, ctx) -> AsyncGenerator[Event, None]:
done = ctx.session.state.get("status") == "completed"
yield Event(author=self.name, actions=EventActions(escalate=done))
poller = LoopAgent(
name="StatusPoller",
max_iterations=10,
sub_agents=[LlmAgent(name="ProcessingStep"), CheckCondition(name="Checker")],
)
The checker costs nothing per iteration — imagine paying an LLM call ten times just to read a status flag.
Lifecycle Around Your Impl
The Runner never calls _run_async_impl bare. run_async wraps it in a lifecycle: before_agent_callback first (returning truthy content skips the agent entirely), then your generator, then after_agent_callback — with after_agent_callback still firing on cancellation. Your implementation should therefore assume callbacks have already run and only yield events it wants persisted.
ADK 2.0: Check Graphs First
ADK 2.0 notes that agent-based workflows built on BaseAgent are superseded by graph-based and dynamic workflows — evaluate /graphs/ before hand-rolling orchestration. A custom non-LLM agent remains the right tool for a single deterministic unit (a guard, a checker, an adapter) that graph nodes or google-adk function tools don’t already express; google-adk-2-graph-workflows-deterministic-orchestration.md shows where the graph takes over.
Takeaway: Subclass BaseAgent, implement _run_async_impl as an async generator that yields Events, declare every sub-agent as an annotated field when passing it through sub_agents, attach state changes to the events you yield so the Runner commits them, and use EventActions(escalate=...) for loop exits — deterministic agents give you token-free control flow inside the same runtime that powers your LLM agents.