ADK capstone: build the doc and ticket support agent
Wire a public-doc lookup, a read-only mock ticket lookup, per-user state and an authenticated API with structured events, plus local stubs and a mock model.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 12 minutes to read.
In short
The build wires the contract into code: a doc lookup that returns passages with source IDs, a read-only lookup over mock tickets filtered by the caller's user ID, per-user sessions in a durable store, and a FastAPI endpoint that verifies the token and streams ADK events as structured server-sent events. A fake model and local stubs make the whole thing run offline and repeatably. You also build one alternative, a graph workflow that routes ticket questions in code, to compare against the single-agent baseline.
Explained simply
Now you build what the contract describes. The project has four parts: two small tools, the agent that uses them, a web API in front of it, and a fake model so you can run everything on your laptop without a key or internet.
The doc tool searches a handful of public help pages saved as a JSON file and returns short passages, each with an ID so the answer can cite it. The ticket tool looks up made-up tickets and only shows a ticket to the user who owns it.
The web API checks who the caller is from their token, creates or loads their session, runs the agent and streams progress back as it happens. The user ID always comes from the token, so nobody can pretend to be someone else by editing the request.
Finally you build a second version that uses a fixed workflow instead of letting the model choose everything. Comparing the two on the same tests shows whether the agent's freedom is worth its extra cost.
Press Play on a diagram to walk through it one step at a time.
- Client to FastAPI + auth: POST turn + bearer token1POST turn + bearer token
- FastAPI + auth to ADK runner and model: run_async(user_id from token, session_id)2run_async(user_id from token, session_id)
- ADK runner and model to Read-only tools: get_ticket_status(T-1001), search_docs(...)3get_ticket_status(T-1001), search_docs(...)
- Read-only tools to ADK runner and model: Owner-checked status, passages + source IDs4Owner-checked status, passages + source IDs
- ADK runner and model to FastAPI + auth: Events: tool calls, then final SupportReply5Events: tool calls, then final SupportReply
- FastAPI + auth to Client: SSE: progress events, then final JSON6SSE: progress events, then final JSON
- 1api.py
FastAPI, token check, SSE, session lock, request IDs
- 2support_agent/agent.py
Agent, instructions, output_schema, App
- 3support_agent/tools.py
search_docs and get_ticket_status, read-only
- 4fixtures/
docs.json and tickets.json, synthetic only
- 5testing/fake_llm.py
Scripted BaseLlm for offline runs
- support_agent/
- agent.py: root_agent and app
- tools.py
- schema.py: SupportReply
- .env (not committed)
- support_workflow/
- agent.py: Workflow with code router
- api.py
- Token check, SSE, lock, request IDs
- fixtures/
- docs.json (public pages)
- tickets.json (T-1001 to T-1006)
- tests/ and evals/
- fake_llm.py and scripts
- support.evalset.json
- test_config.json
In depth
Project setup and the fake model
Prerequisites: Python 3.11 or newer, Git, and optionally a Gemini API key. Create a virtual environment, install google-adk==2.15.1 and pytest, and commit a requirements file with the exact pins. Keep GOOGLE_API_KEY in support_agent/.env, listed in .gitignore. Pick the model through an environment variable: SUPPORT_MODEL=fake loads a BaseLlm subclass that plays back scripted responses, anything else is passed to the agent as a Gemini model name. The fake model reads a script keyed by the user's text: for 'Status of T-1001?' it first returns a function call to get_ticket_status, then, when it sees the function response, returns a SupportReply JSON. Scripts live in tests/scripts/ next to the cases that use them. Expected evidence: adk run support_agent answers the scripted questions with no network access.
- pip install google-adk==2.15.1 pytest
- SUPPORT_MODEL=fake for tests and demos
- Scripts: user text to function calls and replies
- No key, no network, same result every run
The two read-only tools
Both tools are async def so ADK can run them in parallel, both validate inputs before touching data, and both return a dict with a status field. search_docs normalises the query, scores passages with a simple keyword match (good enough for 20 pages; swap in a vector index later), and returns at most four passages with source_id, title and a 300-character excerpt. If nothing scores above a threshold it returns status ok with an empty list, which the instructions tell the model to treat as no source. get_ticket_status checks the ID against the pattern T- plus four digits, loads the record, compares the owner with tool_context.user_id and returns NOT_FOUND on any mismatch. Each tool wraps its work in asyncio.wait_for with the contract's 2-second limit and returns TIMEOUT instead of raising. Unit-test both tools directly with a fake tool context before connecting them to the agent.
Per-user state and sessions
Use DatabaseSessionService with sqlite+aiosqlite locally and postgresql+asyncpg in the deployed version, so sessions survive restarts and are shared by instances. The API owns session lifecycle: on a turn it calls get_session with the token's user ID and the path's session ID, and creates the session only if it is missing, always under that user. Because ADK keys sessions by app, user and session, a session ID from user-a is simply not found for user-b. Keep only what the contract allows in state: a user:language preference and per-session notes. Ticket details stay in events, which are deleted with the session. Add a DELETE endpoint that calls delete_session for the caller's own session, and a test that proves user-b cannot delete it.
- Created by API for user-a
- Holds T-1001 events
- Visible to user-a only
- Deleted with user-a's request
- Lookup keyed by user-b and s1
- Not found
- API returns 404
- No data from user-a leaks
Authenticated streaming API
Wrap the runner in FastAPI rather than exposing adk api_server directly, because you need token checks and response shaping. A dependency validates the bearer token (locally, a fake verifier that maps dev-token-user-a to user-a; in production, a real identity provider or Google-signed ID tokens) and returns the user ID. The turn endpoint takes a request ID and text, applies the session lock and idempotency check, then runs the agent with RunConfig(max_llm_calls=6, streaming_mode=StreamingMode.SSE) inside a 15-second asyncio.timeout. It streams three event types: progress (tool started, tool finished, with tool name only), final (the validated SupportReply) and error (a code and a safe message). If the client disconnects, the generator is cancelled, the lock is released, and the request ID is marked failed so a retry can run.
- event: progress, tool name and status only
- event: final, validated SupportReply
- event: error, code and safe message
- Release lock on disconnect or timeout
A workflow alternative to compare
The baseline is one LLM agent with both tools. The alternative is a graph workflow (ADK Python 2.0 and later): a code router checks the message for a ticket ID pattern. If it finds one, a function node calls the ticket lookup directly and a small agent with no tools writes the reply from that result. Otherwise the message goes to a docs agent with only search_docs. Each branch has fewer tools to misuse and the ticket path needs one model call instead of two. The cost is rigidity: a question that mixes both, such as asking why T-1001 is waiting and what the billing docs say, needs a third branch or a fallback to the full agent. Run the same evaluation set on both designs and record calls per turn, tokens, latency and pass rates in a table for the release guide.
Learn it in 6 short steps
About 1h 40m each. Track them with a timer in your plan.
- 1Build the doc lookup with source IDs~1h 40m
- 2Build the mock ticket tool~1h 40m
- 3Scope state per user~1h 40m
- 4Serve an authenticated streaming API~1h 40m
- 5Add a mock model and local stubs~1h 40m
- 6Build a workflow alternative to compare~1h 40m
Key points
- Pin google-adk==2.15.1 (Python 3.11 or newer) and keep the model key in an untracked .env.
- Each tool checks scope in code: tickets are filtered by tool_context.user_id, docs come only from the public set.
- The API derives user_id from the verified token and never accepts it from the request body.
- Choose the model by environment variable so tests use the fake model and staging uses Gemini.
- The workflow alternative routes on a ticket ID pattern in code, so a simple status question needs fewer model calls.
Key terms
Tap a card to flip it. 0/5 known
Examples
@api.post("/sessions/{session_id}/turns")
async def turn(session_id: str, body: TurnIn, user_id: str = Depends(verified_user)):
await ensure_session(user_id, session_id) # created for this user only
msg = types.Content(role="user", parts=[types.Part(text=body.text)])
async def events():
async for e in runner.run_async(user_id=user_id, session_id=session_id,
new_message=msg, run_config=RUN_CONFIG):
kind = "final" if e.is_final_response() else "progress"
yield f"event: {kind}\ndata: {e.model_dump_json(include={'author', 'content'})}\n\n"
return StreamingResponse(events(), media_type="text/event-stream")verified_user is a FastAPI dependency that validates the bearer token; RUN_CONFIG sets max_llm_calls.
The owner-checked ticket tool
The tool validates the ID format first, then looks the record up through an async store with a 2-second limit, then checks ownership against the caller. Every failure returns a typed error, never an exception the model has to interpret. Expected evidence in tests: user-a gets T-1001's status; user-b gets NOT_FOUND for the same ID; a slow fake store returns TIMEOUT.
TICKET_ID = re.compile(r"^T-\d{4}$")
async def get_ticket_status(ticket_id: str, tool_context: ToolContext) -> dict:
"""Read the status of one of the current user's mock tickets, e.g. T-1001."""
tid = ticket_id.strip().upper()
if not TICKET_ID.match(tid):
return {"status": "error", "error_code": "INVALID_ID"}
try:
t = await asyncio.wait_for(store.get(tid), timeout=2)
except TimeoutError:
return {"status": "error", "error_code": "TIMEOUT"}
if not t or t["owner"] != tool_context.user_id:
return {"status": "error", "error_code": "NOT_FOUND"}
return {"status": "ok", "ticket_id": tid, "state": t["state"], "updated": t["updated"]}Choosing the model for each environment
The agent module picks the model from SUPPORT_MODEL. Tests and demos use the scripted fake; staging and production use a Gemini model named in configuration. The App wraps the agent so the CLI, the API and the evaluator all load the same object. Expected evidence: SUPPORT_MODEL=fake adk run support_agent works with the network off.
import os
from google.adk import Agent
from google.adk.apps import App
from .schema import SupportReply
from .tools import get_ticket_status, search_docs
from testing.fake_llm import ScriptedLlm
name = os.environ.get("SUPPORT_MODEL", "fake")
model = ScriptedLlm() if name == "fake" else name
root_agent = Agent(name="support", model=model, instruction=INSTRUCTIONS,
tools=[search_docs, get_ticket_status], output_schema=SupportReply)
app = App(name="support_agent", root_agent=root_agent)Quick reference
- Pin google-adk==2.15.1; Python 3.11 or newer; key only in an untracked .env.
- SUPPORT_MODEL=fake runs every demo and test offline with a scripted BaseLlm.
- Tools are async def, validate input first and return typed errors as data.
- Owner check: ticket owner must equal tool_context.user_id, else NOT_FOUND.
- API creates sessions under the token's user; never accept user_id from the body.
- Stream progress, final and error events; never stream raw tool payloads.
- Workflow alternative: code router on T-1234 pattern, fewer tools per branch.
Common mistakes
- Passing user_id from the JSON body, which lets any caller read another user's tickets.
- Returning raw tool errors or stack traces in the stream instead of a typed error event.
- Testing only with the live model, so failures cannot be reproduced the next day.
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
Create fixtures/tickets.json with six mock tickets split between user-a and user-b.
- Exercise 2medium
Write a FastAPI dependency that returns the user ID from a bearer token, with a fake verifier for local runs.
- Exercise 3hard
Build the graph workflow alternative with a code router and compare it with the single agent on ten cases.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I use adk api_server instead of FastAPI?
- It is fine for local testing, but it has no authentication guidance and accepts user IDs in the URL. For the capstone, put your own authenticated wrapper in front.
- Do I need a vector database for the doc lookup?
- No. A keyword score over about 20 passages is enough to learn grounding and citations. Replace it later without changing the tool's output shape.
- Is the graph Workflow API stable?
- It ships in ADK Python 2.0 and later and is not labelled preview for Python in the docs. Pin your version and check the release notes before upgrading.