Skip to content
Visual explainer 2h 30m to learn 5 steps

Trace ADK model and tool calls with redaction

Trace model and tool calls with execution IDs, tool latency, errors and cost while redacting private content.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.

Topic 18 of 29

In short

ADK emits OpenTelemetry traces: a span for each agent invocation, model call and tool call, with timing, errors and token counts. Traces are how you find a slow tool or a costly prompt, but by default they can also contain prompts, responses and tool arguments. Turn on tracing, tag spans with execution IDs, compute cost from token counts, and switch off content capture or redact it before anything leaves the process.

Explained simply

When a user says the assistant was slow or gave a strange answer, you need to see what happened inside. Which model calls ran, which tools were used, how long each took, and whether anything failed. That record is called a trace.

ADK creates traces for you using OpenTelemetry, a common standard. Each step becomes a span: one for the agent run, one per model call and one per tool call. In the adk web developer UI you can already open a run and see these spans on your own machine.

Traces can also contain the conversation itself: prompts, answers and tool arguments. That is handy on your laptop and risky in a shared system, because it may include names, emails or ticket details. So before you send traces anywhere, you turn off message capture and redact what remains.

The goal is traces that answer how and how much without telling who said what. You keep IDs to join records, durations, error types and token counts, and you work out cost from the token counts.

Press Play on a diagram to walk through it one step at a time.

MapSpans in one ADK invocation
invoke_agent support_agent
  • generate_content (first model call)
    • input and output tokens
    • finish reason
  • execute_tool get_ticket_status
    • duration
    • error type if it failed
  • generate_content (final answer)
    • input and output tokens
CompareKeep in traces or keep out
Keep
  • Invocation, session and request IDs
  • Tool name, duration and status
  • Token counts and model name
  • Error type and a safe message
Keep out or redact
  • Prompt and response text
  • Tool arguments with personal data
  • Raw tool results
  • Tokens, keys and emails
FlowFrom span to exported record
  1. 1
    ADK creates span

    Content capture set to false

  2. 2
    Your attributes

    request_id, hashed user

  3. 3
    Redaction processor

    Mask emails, keys, free text

  4. 4
    Exporter

    OTLP to collector

  5. 5
    Backend

    Access limited, retention set

In depth

Turn on ADK traces

ADK 2.15.1 always creates OpenTelemetry spans; the question is where they go. Locally, adk web keeps recent traces in memory and shows them in its UI, so you can inspect a run with no setup.

To send spans to a collector, set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT before starting adk web or adk api_server, plus OTEL_SERVICE_NAME to name your service. A free local option is a Jaeger or OpenTelemetry Collector container listening on port 4318. In your own FastAPI wrapper, call maybe_set_otel_providers() from google.adk.telemetry.setup at startup; it reads the same environment variables.

For Google Cloud Trace, adk web and adk api_server accept --otel_to_cloud (the older --trace_to_cloud flag is deprecated). Cloud Trace needs a project with billing and the right IAM roles, so the local collector is the default for this course.

  • Local, no setup: the trace view in adk web
  • Any backend: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
  • Google Cloud Trace: --otel_to_cloud (paid project)
  • Own app: maybe_set_otel_providers() at startup

Tag spans with execution IDs

ADK spans already carry useful IDs: the invocation ID for one run, the session ID as gen_ai.conversation.id, and event IDs. Your API layer adds the rest. Create a request ID for each HTTP call, return it to the client in a header, and put it on your log lines and on a span attribute. Support staff can then ask a user for the request ID and find the exact trace.

User IDs need care. A raw user ID in every span is personal data spread across your telemetry backend. A common approach is to record a keyed hash of the user ID: you can still group spans by user and look someone up if you hold the key, but the backend does not store the ID itself.

Put the same IDs in logs. ADK logs through Python's logging module under the google_adk logger name, so a logging filter can add the request ID to every record.

FlowFollowing one request across signals
  1. 1
    HTTP request

    Wrapper creates request_id

  2. 2
    ADK run

    Invocation ID and session ID on spans

  3. 3
    Logs

    Filter adds request_id to each line

  4. 4
    Audit rows

    Store invocation ID with proposals

  5. 5
    Support lookup

    One ID finds trace, logs and audit

Measure tool latency, errors and cost

Each tool call gets an execute_tool span named after the tool, so its duration is the tool latency. Group by tool name and look at the 95th percentile, not just the average: one slow ticket lookup in twenty is what users notice. Failed tools record an error on the span; you can also add a plugin with on_tool_error_callback to count errors by type.

Model calls appear as generate_content spans with gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. ADK does not know your prices, so cost is your calculation: tokens times the current per-token price for that model, kept in a small config table you update when prices change. Sum per invocation to get the cost of one answer, and per day to watch the budget.

Agents often make several model calls per question, one to pick a tool and one to answer, so cost per answer is usually higher than one call suggests.

  • Tool latency: execute_tool span duration, p50 and p95
  • Tool errors: error status on the span, count by type
  • Tokens: gen_ai.usage.input_tokens and output_tokens
  • Cost per answer: sum over all model calls in the invocation

Redact private content

By default in 2.15.1, ADK's legacy span content setting, ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS, is on. With it on, spans can include the model request and response and tool arguments and results, in attributes such as gcp.vertex.agent.llm_request and gcp.vertex.agent.tool_call_args. Set it to false anywhere except your own laptop, and leave the OpenTelemetry GenAI content capture variable, OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT, unset or false.

That removes most content, but your own code can leak it again. Check custom log lines, exception messages that include arguments, and debugging plugins: ADK's LoggingPlugin prints messages to the console by design, so use it only in development.

For the attributes you keep, add a redaction step in code, such as an OpenTelemetry span processor or a logging filter, that masks emails, tokens and ticket text. Then test it: run a synthetic conversation containing alice@example.com and a fake key, export to a local collector, and search the output for them.

Learn it in 5 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Turn on ADK traces~30m
  2. 2
    Tag spans with execution IDs~30m
  3. 3
    Measure tool latency and errors~30m
  4. 4
    Record token use and cost~30m
  5. 5
    Redact private content~30m

Key points

  • Local: the adk web UI shows each run's spans; remote: set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or use --otel_to_cloud.
  • Model spans record gen_ai.usage.input_tokens and gen_ai.usage.output_tokens; multiply by your price table for cost.
  • ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS defaults to on in 2.15.1; set it to false outside local development.
  • Put the invocation ID and a hashed user ID on logs and spans so you can join them without storing who said what.
  • Redact in code before export, and test the redaction with synthetic secrets.

Key terms

Tap a card to flip it. 0/6 known

Examples

bash
export ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false      # no prompt or response text in spans
export OTEL_SERVICE_NAME=support-agent
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
adk web .     # spans go to your local OTLP collector and the dev UI

Point the endpoint at a local collector such as Jaeger for a free, offline setup.

Local tracing with a free collector

Prerequisites: Docker and the support agent. Step 1: start Jaeger, which accepts OTLP on port 4318 and shows a UI on 16686. Step 2: export the variables and start adk web. Step 3: ask two questions, one that uses get_ticket_status. Evidence: in Jaeger, service support-agent has traces with invoke_agent, generate_content and execute_tool spans, token counts on the model spans, and no message text in the attributes. Cleanup: stop adk web and run docker rm -f jaeger.

bash
docker run -d --name jaeger -p 16686:16686 -p 4318:4318 jaegertracing/all-in-one
export OTEL_SERVICE_NAME=support-agent
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
export ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false
adk web .
# open http://localhost:16686 and search service support-agent
docker rm -f jaeger   # cleanup

A plugin that records tool latency and errors without content

This plugin times each tool call and logs only the tool name, duration, outcome and invocation ID. It never logs arguments or results. Register it with Runner(..., plugins=[ToolMetrics()]) so it covers every agent in the app. Evidence: one log line per tool call, with no ticket text, and an error line when you make the fixture store raise.

python
import logging, time
from google.adk.plugins.base_plugin import BasePlugin
log = logging.getLogger("support.tools")

class ToolMetrics(BasePlugin):
    def __init__(self):
        super().__init__(name="tool_metrics")
    async def before_tool_callback(self, *, tool, tool_args, tool_context):
        tool_context.state[f"temp:t0:{tool_context.function_call_id}"] = time.monotonic()
    async def after_tool_callback(self, *, tool, tool_args, tool_context, result):
        ms = (time.monotonic() - tool_context.state[f"temp:t0:{tool_context.function_call_id}"]) * 1000
        log.info("tool=%s ms=%.0f inv=%s ok", tool.name, ms, tool_context.invocation_id)
    async def on_tool_error_callback(self, *, tool, tool_args, tool_context, error):
        log.warning("tool=%s inv=%s error=%s", tool.name, tool_context.invocation_id, type(error).__name__)

Quick reference

  • ADK span names: invoke_agent, generate_content, execute_tool (plus the agent, model or tool name)
  • Export: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and OTEL_SERVICE_NAME
  • Cloud Trace: adk web or api_server --otel_to_cloud (paid project)
  • ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false outside local dev (default is on)
  • Tokens: gen_ai.usage.input_tokens and gen_ai.usage.output_tokens
  • Cost = tokens x your price table, summed per invocation
  • Log IDs, durations and error types; never prompts, args or results
  • Test redaction with synthetic secrets like alice@example.com

Common mistakes

  • Shipping traces to a shared backend with content capture still on, so customer messages end up in it.
  • Logging raw tool arguments in a callback while the spans are carefully redacted.
  • Estimating cost from request counts rather than token counts per model.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which span tells you how long the ticket lookup took?

Question 2

2What is the default for ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS in google-adk 2.15.1?

Question 3

3How do you get the cost of one answer?

Question 4

4Why record a keyed hash of the user ID instead of the raw ID?

Question 5

5Which of these is most likely to leak content even with span capture off?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run the agent with adk web, ask one question that uses a tool, and write down the span names and durations you see in the trace view.

  2. Exercise 2medium

    Write a function that takes a list of model call records (model, input_tokens, output_tokens) and a price table, and returns the cost of one invocation.

  3. Exercise 3hard

    Add a logging filter that masks emails and anything that looks like an API key, and a test that proves a synthetic secret never reaches the log output.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need Google Cloud to use ADK tracing?
No. The adk web UI shows traces locally, and any OpenTelemetry collector such as Jaeger can receive them. Cloud Trace is one optional, paid destination.
Should I ever capture prompts in traces?
On your own machine with synthetic data, it is very helpful. In shared or production systems, keep it off, or capture only with strict access, short retention and a clear reason.
Why are my token counts higher than the user's message length?
Every model call also sends the instruction, tool definitions and conversation history, and an agent often calls the model more than once per answer.

Go deeper

ShareXLinkedInWhatsApp