ADK capstone: write the support assistant contract
Define the allowed tools, session rules, response schema, escalation rules, budget and evaluation targets for the support assistant.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.
In short
Before writing agent code, write the contract: what the support assistant may do, for whom, in what shape it answers, when it stops or hands off to a person, and how you will know it works. The contract lists two read-only tools, per-user session rules, a typed response schema, escalation and stop rules, a cost and time budget, and evaluation targets. Every later build and release step is checked against this one page.
Think of it like this: The contract is the job description you give a new support hire: which systems they may look at, how to reply, when to call a supervisor and how their work will be reviewed.
Explained simply
The capstone is a small support assistant. It answers questions from public product docs and tells signed-in users the status of their own tickets. The tickets are fake, made up for the course, and the assistant can only read, never change anything.
Before building it, you write a contract. A contract here is a single page that says exactly what the assistant may do, how it must reply, when it must stop, and how you will test it. Think of it as the rules you would give a new support colleague on day one.
The contract has five parts. Tools: which lookups are allowed. Sessions: whose conversation is whose and how long it is kept. Response schema: the exact shape of every answer. Stop and escalation rules: when to give up safely or hand the case to a person. Budget and targets: how much each answer may cost and what pass rate counts as good enough.
Writing this first saves time later. When the model does something surprising, you check it against the contract instead of arguing about it. And because the targets are written before you see any results, the tests stay honest.
Press Play on a diagram to walk through it one step at a time.
- Allowed tools
- search_docs: public docs, returns source IDs
- get_ticket_status: mock tickets, owner only
- No write tools
- Sessions
- user_id from verified token
- One active run per session
- 30-day retention, delete on request
- Response schema
- answer
- citations (source IDs)
- ticket_refs
- escalate + reason
- Stop and escalate
- Max 6 model calls
- 15 s deadline
- No source found
- Asks for a change or refund
- Targets
- Answer and citation accuracy
- Expected tool use
- Timeout and escalation cases
- Cost per turn
- 1Grounded answer
Citations valid, escalate false
- 2No source
Say so, reason no_source, offer escalation
- 3Change requested
reason needs_action, human follows up
- 4Limit or deadline hit
reason limit_reached, safe reply
- 5Tools failing
reason tool_error after two failures
In depth
Allowed tools and their scope
List every tool with its purpose, inputs, outputs, data source and scope rule. The assistant gets exactly two. search_docs(query) searches a small set of public doc pages stored in fixtures/docs.json and returns up to four passages, each with a source ID such as doc-billing-03 and a title. get_ticket_status(ticket_id) reads fixtures/tickets.json and returns status, priority and last update only if the ticket's owner equals tool_context.user_id; otherwise it returns NOT_FOUND, the same as for a missing ticket, so it never reveals that the ticket exists. Both tools are read-only and return errors as data with a fixed error_code. Anything else the user wants, such as closing, reopening or refunding, is out of scope and leads to escalation. Write that rule into the contract explicitly, because users will ask.
- search_docs: public docs only, k=4, returns source IDs
- get_ticket_status: owner check in code
- Error codes: NOT_FOUND, INVALID_ID, TIMEOUT, UNAVAILABLE
- No write, email or payment tools
Session and user scope
The API takes the user ID from a verified bearer token and passes it to runner.run_async as user_id. The model never sees a way to change it, and no tool accepts a user ID argument. Sessions are created by the API under that user, so a session ID is only meaningful together with its owner. State keys follow ADK's prefixes: plain keys for this session, user: keys for preferences shared across that user's sessions, and temp: keys for values that should not be saved. The contract also states retention: sessions kept 30 days, deleted on request through delete_session, and no ticket data copied into user: state. One active run per session; a second concurrent turn gets HTTP 409.
- Sessions
- s-a1
- s-a2
- Created only by the API
- State
- s-a1 keys: this chat only
- user:language: all of user-a's chats
- temp: keys: never saved
- Visible tickets
- T-1001 (owner user-a)
- T-1003 (owner user-a)
- Never visible
- T-1002 (owner user-b)
- user-b sessions
The response schema
Every final answer is a SupportReply: answer text, a list of citations (doc source IDs), a list of ticket_refs, an escalate flag and a reason code. Set it with output_schema on the agent; in Python, ADK allows output_schema together with tools and applies the schema only to the final response. Add output_key if you want the last reply saved into session state. A typed schema turns fuzzy checks into code: every citation must be a source ID that search_docs actually returned in this turn, every ticket_ref must have appeared in a successful get_ticket_status result, and escalate must be true whenever reason is not none. These three rules become post-response checks in the API and test assertions in the evaluation set.
Escalation and stop rules
Stop rules must be numbers, not wishes. Set RunConfig(max_llm_calls=6); when the cap is passed, ADK raises LlmCallsLimitExceededError, which the API catches and turns into a limit_reached reply. Add a 15-second deadline around the whole run with asyncio.timeout, a 2-second timeout per tool, and a rule that two failed tool calls in one turn end the run with a tool_error reply. Escalate when there is no source for a docs question, when the user asks for any change, when a ticket is not found twice, or when the user asks for a person. An escalation reply says what happens next in plain words and includes a short summary for the human, built from the turn's tool results, never from hidden instructions.
- max_llm_calls=6 per turn
- 15 s per turn, 2 s per tool
- Two tool failures: stop
- No source: say so and escalate
- Change requested: escalate, never act
Budget and evaluation targets
Write the budget as limits you can measure in traces: at most 6 model calls, about 8,000 input tokens and 15 seconds per turn, and a monthly cap you set in billing alerts if you use a paid model. Then write targets per category of the evaluation matrix. For fixture runs with the fake model, everything must pass exactly. For live-model runs, set thresholds before the first run, for example 18 of 20 answers correct, 19 of 20 citations valid, tool trajectory score at least 0.9 with IN_ORDER matching where extra lookups are harmless, 100 percent of denial and isolation cases passing, and every timeout case ending with a fallback reply. Security cases have no threshold below 100 percent.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1List allowed read-only tools~50m
- 2Define session and user scope~50m
- 3Write the response schema~50m
- 4Set escalation and stop rules~50m
- 5Set budget and evaluation targets~50m
Key points
- Only read-only tools are allowed; anything that would change data becomes an escalation, not an action.
- The user ID comes from the verified token on every request, never from the message text or the model.
- A typed response schema with citations and an escalate flag makes answers testable in code.
- Stop rules are numbers: a maximum of model calls, a deadline, a tool-failure limit and an empty-result rule.
- Evaluation targets are written before the build so they cannot be tuned to fit the result.
Key terms
Tap a card to flip it. 0/6 known
Examples
from typing import Literal
from pydantic import BaseModel, Field
class SupportReply(BaseModel):
answer: str = Field(max_length=1200)
citations: list[str] = Field(default_factory=list, description="Doc source IDs, e.g. doc-billing-03")
ticket_refs: list[str] = Field(default_factory=list, description="Mock ticket IDs, e.g. T-1001")
escalate: bool = False
reason: Literal["none", "no_source", "needs_action", "limit_reached", "tool_error"] = "none"
# Agent(..., output_schema=SupportReply) applies to the final response only.In Python, ADK allows output_schema together with tools; the schema applies to the final reply.
Turning a request into contract rules
The brief says: help customers with docs and ticket status. Step 1: list intents from 30 synthetic messages: how-to questions, ticket status, change requests, complaints. Step 2: map each to a tool or an escalation. How-to goes to search_docs, status to get_ticket_status, change requests and complaints to escalation. Step 3: write the scope rule for each tool. Step 4: write one example input and expected SupportReply per intent. These examples become the first evaluation cases.
The contract as a checked-in config
Keeping the numbers in one file means the API, the tests and the guide read the same values. The API builds RunConfig and timeouts from it, and a test asserts that the agent's tool list matches the allowed list exactly, so adding a tool without updating the contract fails CI.
CONTRACT = {
"adk_version": "2.15.1",
"allowed_tools": {"search_docs", "get_ticket_status"},
"max_llm_calls": 6,
"turn_deadline_s": 15,
"tool_timeout_s": 2,
"max_tool_failures": 2,
"retention_days": 30,
}
def test_tools_match_contract():
names = {t.__name__ for t in root_agent.tools}
assert names == CONTRACT["allowed_tools"]Quick reference
- Two tools only: search_docs (public docs) and get_ticket_status (owner-checked mock tickets).
- user_id comes from the verified token; no tool takes a user ID argument.
- Final answers use output_schema=SupportReply with citations and an escalate flag.
- RunConfig(max_llm_calls=6); catch LlmCallsLimitExceededError and reply limit_reached.
- Deadline per turn with asyncio.timeout; timeout per tool call.
- Write thresholds before the first live run; security cases must pass 100 percent.
- Any request to change data is an escalation, not an action.
Common mistakes
- Leaving the contract vague ("helps with tickets") so no test can fail.
- Letting the prompt carry the access rules instead of code that checks the token's user ID.
- Setting targets after seeing results, which turns evaluation into a formality.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write the scope rule and error codes for get_ticket_status in two or three lines.
- Exercise 2medium
Write a post-response check that rejects citations not returned by search_docs in the same turn.
- Exercise 3hard
Draft the full one-page contract for the support assistant, including targets for each matrix category.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a paid Gemini key for the capstone?
- No. Every step has a fake-model path. A key is only needed for the optional live-model evaluation and real latency figures.
- Can the assistant ever perform an action?
- Not in this capstone. Actions are escalations; module 6 shows how a write would become a dry-run proposal with human approval.
- Why not let the model decide when to escalate?
- The model can suggest it, but code also enforces the hard rules, such as escalating on a change request or a reached limit, so they hold every time.