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

# Microsoft Agent Framework

> Capture traces from Microsoft Agent Framework agents with its built-in OpenTelemetry instrumentation

## 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 Microsoft Agent Framework application.
Org ID: your-org-id
Instrument the real agent.run() path, set session and user IDs on the spans, 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="maf-support",
    input=question,
    conversation_id=session.session_id,  # groups turns into one conversation
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
try:
    response = await agent.run(question, session=session)
    interaction.end(output=response.text)
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

Agent Framework instruments every `Agent` with OpenTelemetry using the GenAI semantic conventions. It emits an `invoke_agent` span per run, a `chat` span per model call, and an `execute_tool` span per tool call. Export those spans to Agnost AI, turn on content capture, and add a small span processor that writes your session and user IDs onto every span. This guide uses the Python package.

### Install

```bash theme={null}
pip install agent-framework-anthropic opentelemetry-exporter-otlp-proto-http --pre
```

`agent-framework-anthropic` is a prerelease package and pulls in `agent-framework-core`. Use the client package of your model provider instead if you do not use Claude. Agent Framework does not install an OTLP exporter for you.

### Setup

```python theme={null}
import asyncio
import contextvars

from agent_framework import Agent, tool
from agent_framework.anthropic import AnthropicClient
from agent_framework.observability import configure_otel_providers
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import SpanProcessor

configure_otel_providers(
    exporters=[OTLPSpanExporter(
        endpoint="https://otel.agnost.ai/v1/traces",
        headers={"X-Agnost-Org-ID": "your-org-id"},
    )],
    enable_sensitive_data=True,
)

agnost_context = contextvars.ContextVar("agnost_context", default={})


class AgnostContextProcessor(SpanProcessor):
    """Copies the current session and user onto every span."""

    def on_start(self, span, parent_context=None):
        span.set_attributes(agnost_context.get())


trace.get_tracer_provider().add_span_processor(AgnostContextProcessor())


@tool(approval_mode="never_require")
def get_weather(city: str) -> str:
    """Return the current weather for a city."""
    return f"It is sunny in {city}."


agent = Agent(
    client=AnthropicClient(model="claude-haiku-4-5"),
    name="weather-agent",
    instructions="Answer weather questions with get_weather.",
    tools=[get_weather],
)


async def ask(session, user_id, question):
    token = agnost_context.set({"session.id": session.session_id, "user.id": user_id})
    try:
        response = await agent.run(question, session=session)
    finally:
        agnost_context.reset(token)
    return response.text


async def main():
    session = agent.create_session(session_id="sess-123")
    print(await ask(session, "u-42", "What's the weather in Paris?"))
    print(await ask(session, "u-42", "And in Tokyo?"))


asyncio.run(main())
trace.get_tracer_provider().force_flush()
```

Three parts matter:

* **`exporters=[OTLPSpanExporter(...)]`** sends traces only. Agnost AI stores traces, so do not set `OTEL_EXPORTER_OTLP_ENDPOINT` for it, which would also send logs and metrics.
* **`enable_sensitive_data=True`** adds prompts, answers, tool arguments, and tool results to the spans. Without it, Agnost AI receives the events with no content. You can set `ENABLE_SENSITIVE_DATA=true` instead.
* **`AgnostContextProcessor`** adds `session.id` and `user.id` to each span. Agent Framework sets `gen_ai.conversation.id` only when the provider manages the conversation on its side, and it never records a user ID. Agnost AI groups all runs with the same `session.id` into one conversation and attributes it to `user.id`.

If your app already configures OpenTelemetry, add the Agnost AI exporter and `AgnostContextProcessor` to your own tracer provider and call `enable_instrumentation(enable_sensitive_data=True)` from `agent_framework.observability` instead of `configure_otel_providers()`.

### What appears in Agnost AI

* **Conversations**: one per `session.id`. The raw value is kept as `original_conversation_id` in the conversation metadata.
* **Users**: the `user.id` set in `ask`.
* **Messages**: the user's message and the agent's final answer for each `agent.run(...)` call, from the root `invoke_agent` span.
* **Events**: `invoke_agent`, `chat`, and `execute_tool` spans in a nested tree. Model events carry token counts. Tool events carry the tool name, arguments, and result.

### Verify

Run one agent turn, wait about 30 seconds, then open **Conversations** in Agnost AI. Confirm the conversation shows your user ID, a user message and an assistant answer, and a `get_weather` tool event with arguments and a result.

### Troubleshooting

* **Nothing arrives**: install `opentelemetry-exporter-otlp-proto-http`, confirm the header is `X-Agnost-Org-ID` and the endpoint ends in `/v1/traces`. Short scripts must call `trace.get_tracer_provider().force_flush()` before they exit.
* **Events have no prompts, answers, or tool arguments**: pass `enable_sensitive_data=True` or set `ENABLE_SENSITIVE_DATA=true`.
* **Each turn is its own conversation, or the user is empty**: the run happened outside `ask`, or `AgnostContextProcessor` was not added to the tracer provider.
* **Model calls appear twice**: the Anthropic Python SDK 2.x also emits its own `anthropic.messages.create` span for each API call, without message content. Set `ANTHROPIC_OPEN_TELEMETRY=false` to turn it off.

### References

* [Agent Framework observability](https://learn.microsoft.com/en-us/agent-framework/agents/observability)
* [Agent Framework Anthropic provider](https://learn.microsoft.com/en-us/agent-framework/integrations/by-component/model-providers/anthropic)
* [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 Agent Framework 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.