> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agnost.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Google ADK

> Capture traces from Agent Development Kit (ADK) agents with ADK's built-in OpenTelemetry export

## Choose a setup method

| Method | Use it when |
| - | - |
| **Agnost AI skill** | You want your coding agent to inspect the app, make the change, and verify it. |
| **Agnost AI SDK** | You want explicit control over the interaction boundaries and fields. |
| **OpenTelemetry** | The framework already emits useful spans or you operate an OTel pipeline. |

Start with one method for a call path. Combining SDK tracking with framework
OpenTelemetry on the same call can create duplicate interactions.

## Recommended: Agnost AI skill

> [!NOTE]
>
> **Recommended.** Choose this path when you want your coding agent to inspect the
> project, select a supported transport, make the smallest instrumentation change,
> send a test event, and verify that it reached Agnost AI.

Install the skill once in your coding-agent environment:

```bash theme={null} theme={null} theme={null} theme={null} theme={null}
npx skills add AgnostAI/skills --skill agnost-ai
```

Run the framework-specific prompt below from the application root. Review the
resulting diff before deploying it.

```text theme={null}
Use the agnost-ai skill to add Agnost AI analytics to this Google ADK application.
Org ID: your-org-id
Instrument the real Runner.run_async() path, set user and session IDs, and verify one fresh interaction.
```

## Manual setup: Agnost AI SDK

```bash theme={null}
pip install agnost
```

```python theme={null}
import agnost

agnost.init("your-org-id")
interaction = agnost.begin(user_id="u-42", agent_name="adk-support", input=prompt)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
try:
    answer = ""
    async for event in runner.run_async(user_id="u-42", session_id=session_id, new_message=message):
        if event.is_final_response() and event.content and event.content.parts:
            answer = event.content.parts[0].text or ""
    interaction.end(output=answer)
except Exception as exc:
    interaction.end(output=str(exc), success=False)
    raise
```

Call `agnost.shutdown()` once when the application exits, not after each request.

## Manual setup: OpenTelemetry

ADK emits OpenTelemetry spans for every workflow, agent, model call, and tool call. Point its OTLP exporter at Agnost AI, turn on span content capture, and add a short plugin that writes the user ID and each turn's input and answer onto the root span.

### 1. Install

```bash theme={null}
pip install google-adk opentelemetry-exporter-otlp-proto-http
```

ADK's built-in OTLP setup uses the HTTP/protobuf exporter. Without this package it logs a warning and sends nothing.

### 2. Point ADK at Agnost AI

Set these before ADK starts:

```bash theme={null}
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://otel.agnost.ai/v1/traces"
export OTEL_EXPORTER_OTLP_TRACES_HEADERS="X-Agnost-Org-ID=your-org-id"
export OTEL_SERVICE_NAME="my-adk-agent"
export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT="SPAN_ONLY"
```

`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY` is required on ADK 2.x. Without it, ADK keeps prompts, answers, and tool arguments off its spans, and Agnost AI receives model and tool events with no content.

Use the `_TRACES_` variables rather than `OTEL_EXPORTER_OTLP_ENDPOINT`. Agnost AI stores traces only, and the general variable also sends metrics and logs.

`adk web` and `adk api_server` read these variables directly. In your own process, call `maybe_set_otel_providers()` once at startup:

```python theme={null}
from google.adk.telemetry.setup import maybe_set_otel_providers

maybe_set_otel_providers()
```

### 3. Add the Agnost plugin for users and transcripts

ADK writes the session ID onto its spans as `gen_ai.conversation.id`, so Agnost AI groups each ADK session as one conversation without any extra code. Two things need a plugin:

* **User ID**: ADK records `user.id` on log records only, not on spans.
* **Transcript**: Agnost AI builds the conversation transcript from each trace's root span. In ADK that root is `invoke_workflow`, which carries no message content.

ADK runs plugin callbacks for the user's message and each event inside the root span. This plugin uses those callbacks to copy the user ID, the user's message, and the final answer onto that span:

```python theme={null}
import json

from google.adk.plugins.base_plugin import BasePlugin
from opentelemetry import trace


def _text(content):
    return "".join(p.text for p in (content.parts or []) if p.text) if content else ""


class AgnostPlugin(BasePlugin):
    """Adds user.id and each turn's input and answer to ADK's root span."""

    def __init__(self):
        super().__init__(name="agnost")

    async def on_user_message_callback(self, *, invocation_context, user_message):
        span = trace.get_current_span()  # the root invoke_workflow span
        span.set_attribute("user.id", invocation_context.session.user_id)
        span.set_attribute("gen_ai.input.messages", json.dumps(
            [{"role": "user", "parts": [{"type": "text", "content": _text(user_message)}]}]))

    async def on_event_callback(self, *, invocation_context, event):
        if event.is_final_response() and _text(event.content):
            trace.get_current_span().set_attribute("gen_ai.output.messages", json.dumps(
                [{"role": "assistant", "parts": [{"type": "text", "content": _text(event.content)}]}]))
```

The plugin only adds span attributes. It never returns a value, so it does not change how the agent runs.

### 4. Run the agent with a user and session

Pass the plugin to the `Runner` (or to `App(plugins=[...])` when you serve an `App` with `adk web`), then use ADK's normal session APIs:

```python theme={null}
import asyncio

from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.telemetry.setup import maybe_set_otel_providers
from google.genai import types

maybe_set_otel_providers()


def get_weather(city: str) -> dict:
    """Returns the current weather for a city."""
    return {"status": "success", "report": f"The weather in {city} is sunny."}


root_agent = Agent(
    name="weather_agent",
    model="gemini-flash-latest",
    instruction="Answer weather questions using get_weather.",
    tools=[get_weather],
)


async def main():
    sessions = InMemorySessionService()
    await sessions.create_session(app_name="weather_app", user_id="user-42", session_id="session-abc")
    runner = Runner(
        agent=root_agent,
        app_name="weather_app",
        session_service=sessions,
        plugins=[AgnostPlugin()],
    )
    async for event in runner.run_async(
        user_id="user-42",
        session_id="session-abc",
        new_message=types.Content(role="user", parts=[types.Part(text="What's the weather in Paris?")]),
    ):
        if event.is_final_response() and event.content and event.content.parts:
            print(event.content.parts[0].text)


asyncio.run(main())
```

Every `run_async` call with the same `session_id` lands in the same Agnost AI conversation, and that conversation's user is the `user_id` from the session.

### What appears in Agnost AI

* **Conversations**: one per ADK session (`gen_ai.conversation.id`). Agnost AI keeps the raw session ID as `original_conversation_id` in the conversation metadata.
* **Users**: the ADK session's `user_id`, from the plugin.
* **Messages**: the user's message and the agent's final answer for each turn, from the plugin.
* **Events**: `invoke_agent`, `generate_content`, and `execute_tool` spans in a nested tree. Model calls include the model name and input and output token counts. Tool calls include arguments and results.

### Verify

Run one agent turn, wait one to five minutes for ingestion, then open **Conversations** in Agnost AI. Confirm the conversation shows your `user_id`, a user message and an assistant answer, and a tool event with arguments and a result.

### Troubleshooting

* **Nothing arrives**: install `opentelemetry-exporter-otlp-proto-http` and confirm `OTEL_EXPORTER_OTLP_TRACES_HEADERS` contains `X-Agnost-Org-ID=your-org-id`. If your app sets its own `TracerProvider` first, ADK leaves it alone, so add an `OTLPSpanExporter` for Agnost AI to that provider instead.
* **Conversation has no messages**: make sure `AgnostPlugin` is registered on the `Runner` or `App` that serves traffic.
* **Events have no prompts, answers, or tool arguments**: set `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY` before ADK starts.
* **User is empty**: the plugin is missing, or the session was created without a `user_id`.
* **Short scripts lose spans**: ADK exports in batches. Call `trace.get_tracer_provider().force_flush()` before the process exits.

### References

* [ADK agent activity traces](https://adk.dev/observability/traces/)
* [ADK plugins](https://adk.dev/plugins/)
* [OpenTelemetry GenAI agent spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete ADK session.
* [Events](https://docs.agnost.ai/using-events.md): inspect agent, model, and tool activity.
* [Intents](https://docs.agnost.ai/using-intents.md): organize production conversations by what users wanted.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.