|
|
ADK Custom Event Handlers
Author: Venkata Sudhakar
ADK agents emit lifecycle events at every stage of execution - before a tool is called, after it returns, when the model generates a response, and when an error occurs. Custom callbacks let you hook into these events to add cross-cutting concerns like structured logging, latency monitoring, tool call auditing, and Slack alerts - all without touching the core agent logic.
ShopMax India production agents must meet compliance requirements for tool call auditing and have SLA monitoring for response latency. Rather than adding logging code inside every tool function, the engineering team attaches callbacks to the agent that intercept every tool invocation, log it to Cloud Logging, and alert on slow responses automatically.
The below example shows how to implement ADK callbacks for tool call logging and latency tracking in a ShopMax India agent.
It gives the following output,
Order agent initialised with full lifecycle callbacks.
Callbacks registered:
before_model_callback : latency timer start
after_model_callback : latency check + SLA alert (>3000ms)
before_tool_callback : audit log entry
after_tool_callback : audit log exit
The below example shows the agent running a session with all callbacks firing, producing structured audit log output for a ShopMax India order status query.
It gives the following output,
2026-04-06 04:06:00 INFO [sess_abc123] LLM call started | turn=1 | model=order_agent
2026-04-06 04:06:00 INFO [sess_abc123] LLM call done | latency=412ms | tokens=89
2026-04-06 04:06:00 INFO [TOOL CALL] get_order_status | args={'order_id': 'ORD-20260406-9921'} | session=sess_abc123
2026-04-06 04:06:00 INFO [TOOL DONE] get_order_status | response_keys=['order_id', 'status', 'eta']
2026-04-06 04:06:00 INFO [sess_abc123] LLM call started | turn=3 | model=order_agent
2026-04-06 04:06:00 INFO [sess_abc123] LLM call done | latency=388ms | tokens=124
Agent: Your order ORD-20260406-9921 has been shipped and is expected to
arrive by 8th April 2026. You will receive a tracking SMS shortly.
ADK callbacks give ShopMax India production-grade observability without polluting agent or tool code with logging concerns. Every tool call is audited, every LLM invocation is timed, and SLA breaches trigger alerts automatically. The same callback functions can be attached to any agent in the fleet, making it trivial to roll out consistent observability across all ShopMax India ADK agents.
|
|