> ## 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.

# AG2

> Capture AG2 agent turns, model calls, and tool calls with AG2's built-in OpenTelemetry tracing

## 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}
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 AG2 application.
Org ID: your-org-id
Instrument the real agent.ask() path 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="ag2-support",
    input=prompt,
    conversation_id="sess-123",  # groups turns into one conversation
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
try:
    reply = await agent.ask(prompt)
    interaction.end(output=reply.body)
except Exception as exc:
    interaction.end(output=str(exc), success=False)
    raise
```

Call `agnost.shutdown()` once when the application exits, not after each request.
Shutting down per request disables telemetry for later agent runs in the same process.

## Manual setup: OpenTelemetry

AG2 1.x ships `TelemetryMiddleware`, which emits OpenTelemetry spans that follow the GenAI semantic conventions: one `invoke_agent` span per turn, one `chat` span per model call, and one `execute_tool` span per tool call. Agnost AI ingests those spans directly. Send them over OTLP, stamp the session and user on them, and wrap each turn in one short span that carries the user's message and the agent's answer.

### 1. Install

```bash theme={null}
pip install "ag2[anthropic,tracing]" opentelemetry-exporter-otlp-proto-http
```

Tested with `ag2` 1.3.4, `anthropic` 2.14.0, and `opentelemetry-sdk` 1.45.2 on Python 3.12.

### 2. Point OpenTelemetry at Agnost AI and run an agent

```python theme={null}
import asyncio
import json
import os

from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.middleware.builtin import TelemetryMiddleware
from ag2.tools import tool
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

provider = TracerProvider(resource=Resource.create({"service.name": "my-ag2-agent"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint="https://otel.agnost.ai/v1/traces",
    headers={"X-Agnost-Org-ID": os.environ["AGNOST_ORG_ID"]},
)))
tracer = provider.get_tracer("agnost")


@tool
def get_order_status(order_id: str) -> str:
    """Look up the shipping status of an order."""
    return "shipped"


agent = Agent(
    "support-agent",
    prompt="You are a support agent for an online store. Keep answers short.",
    # open_telemetry=False: only AG2's spans, not a second span from the anthropic SDK.
    config=AnthropicConfig(model="claude-haiku-4-5", open_telemetry=False),
    tools=[get_order_status],
)


async def run_turn(message: str, user_id: str, session_id: str) -> str:
    """Run one agent turn and record it as one Agnost AI conversation turn."""
    telemetry = TelemetryMiddleware(
        tracer_provider=provider,
        agent_name="support-agent",
        span_attributes={"gen_ai.conversation.id": session_id, "user.id": user_id},
    )
    with tracer.start_as_current_span("agent_turn", attributes={
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.agent.name": "support-agent",
        "gen_ai.conversation.id": session_id,
        "user.id": user_id,
        "gen_ai.input.messages": json.dumps(
            [{"role": "user", "parts": [{"type": "text", "content": message}]}]),
    }) as span:
        reply = await agent.ask(message, middleware=[telemetry])
        answer = reply.body
        span.set_attribute("gen_ai.output.messages", json.dumps(
            [{"role": "assistant", "parts": [{"type": "text", "content": answer}]}]))
        return answer


print(asyncio.run(run_turn("Where is my order A-1042?", user_id="user-42", session_id="session-abc")))
provider.shutdown()  # flush spans before a short script exits
```

What each piece does:

* **`TelemetryMiddleware`** traces the agent turn, each model call, and each tool call. Content capture is on by default, so model spans carry `gen_ai.input.messages` and `gen_ai.output.messages`, and tool spans carry `gen_ai.tool.call.arguments` and `gen_ai.tool.call.result`.
* **`span_attributes`** stamps `gen_ai.conversation.id` and `user.id` onto every span the middleware emits. Every turn with the same `session_id` lands in the same Agnost AI conversation. Because the values change per request, the middleware is created per turn and passed to `agent.ask(..., middleware=[...])` rather than to the `Agent` constructor.
* **The `agent_turn` span** becomes the root of each trace. Agnost AI builds the conversation transcript from each trace's root span, and AG2's `invoke_agent` span carries no message text. The wrapper puts the user's message and the final answer there.
* **`open_telemetry=False`** stops the `anthropic` SDK from adding its own `chat` span under every AG2 `chat` span, so each model call is recorded once.

In a long-running server, create the `TracerProvider` once at startup, call `run_turn` per request, and call `provider.shutdown()` on graceful shutdown.

### What appears in Agnost AI

* **Conversations**: one per `session_id`. Agnost AI keeps the raw session ID as `original_conversation_id` in the conversation metadata.
* **Users**: the `user_id` you pass to `span_attributes`.
* **Messages**: the user's message and the agent's answer for each turn, from the `agent_turn` span.
* **Events**: the `support-agent` turn (`agent`), each model call (`llm`) with input and output messages and token counts, and each tool call (`tool`) with the tool name, arguments, and result. AG2 also emits a `record_usage` span per model call with the same token counts.

### Verify

Run the script, wait up to a minute for ingestion, then open **Conversations** in Agnost AI. Confirm the conversation shows your `user_id`, a user message and an assistant answer, and a `get_order_status` tool event with arguments and a result.

### Troubleshooting

* **Nothing arrives**: confirm the exporter's headers contain `X-Agnost-Org-ID`, and that the script calls `provider.shutdown()` or `provider.force_flush()` before it exits. `BatchSpanProcessor` exports in the background.
* **`TelemetryMiddleware` import fails**: install the `tracing` extra, `pip install "ag2[tracing]"`.
* **Events arrive but the conversation has no messages**: the turn ran outside the `agent_turn` span. Call `agent.ask()` inside it.
* **Every turn is a separate conversation, or the user is missing**: pass `span_attributes` with `gen_ai.conversation.id` and `user.id` on each turn.
* **Each model call appears twice**: set `open_telemetry=False` on `AnthropicConfig`, or set `ANTHROPIC_OPEN_TELEMETRY=false`.
* **Model and tool events have no text**: `capture_content` was set to `False` on `TelemetryMiddleware`.
* **You use AG2 0.x** (`from autogen import ConversableAgent`): `TelemetryMiddleware` is part of the AG2 1.x API. Upgrade to `ag2` 1.x, or use the Agnost AI SDK setup above.

### References

* [AG2 agent telemetry](https://docs.ag2.ai/docs/user-guide/telemetry/agent/)
* [OpenTelemetry GenAI agent spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/)
* [AG2 on GitHub](https://github.com/ag2ai/ag2)

## Next steps

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


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