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

# Atomic Agents

> Capture Atomic Agents runs, model calls, and tool calls with the built-in instrumentor

## 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 Atomic Agents application.
Org ID: your-org-id
Instrument the real AtomicAgent.run() path and verify one fresh interaction.
```

## Manual setup: Agnost AI SDK

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

```python theme={null}
import agnost
from atomic_agents import BasicChatInputSchema

agnost.init("your-org-id")
interaction = agnost.begin(
    user_id="u-42",
    agent_name="atomic-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 = agent.run(BasicChatInputSchema(chat_message=prompt))
    interaction.end(output=reply.chat_message)
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

Atomic Agents ships `AtomicAgentsInstrumentor` in `atomic_agents.observability`. It emits OpenTelemetry spans that follow the GenAI semantic conventions: one `invoke_agent` span per agent run, one `chat` span per model call Instructor makes, and one `execute_tool` span per `BaseTool` run. Agnost AI ingests those spans directly. The `phoenix` extra adds OpenInference attributes, which lets `using_attributes` put the session and user on every span.

### 1. Install

```bash theme={null}
pip install "atomic-agents[phoenix]" "instructor[anthropic]" \
            opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
```

Tested with `atomic-agents` 2.16.2, `instructor` 1.17.0, `anthropic` 0.93.0, `openinference-instrumentation` 0.1.83, and `opentelemetry-sdk` 1.45.2 on Python 3.12.

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

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

import anthropic
import instructor
from atomic_agents import (
    AgentConfig,
    AtomicAgent,
    BaseIOSchema,
    BaseTool,
    BaseToolConfig,
    BasicChatInputSchema,
    BasicChatOutputSchema,
)
from atomic_agents.observability import AtomicAgentsInstrumentor, TracingConfig
from openinference.instrumentation import using_attributes
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-atomic-agent"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint="https://otel.agnost.ai/v1/traces",
    headers={"X-Agnost-Org-ID": os.environ["AGNOST_ORG_ID"]},
)))
AtomicAgentsInstrumentor().instrument(
    tracer_provider=provider,
    config=TracingConfig(capture_messages=True),  # also record prompts and replies on model spans
)
tracer = provider.get_tracer("agnost")


class OrderStatusInput(BaseIOSchema):
    """Look up the shipping status of an order."""

    order_id: str


class OrderStatusOutput(BaseIOSchema):
    """The shipping status of an order."""

    status: str


class OrderStatusTool(BaseTool[OrderStatusInput, OrderStatusOutput]):
    def run(self, params: OrderStatusInput) -> OrderStatusOutput:
        return OrderStatusOutput(status="shipped")


order_status = OrderStatusTool(BaseToolConfig(title="get_order_status"))
agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](
    AgentConfig(
        client=instructor.from_anthropic(anthropic.Anthropic()),
        model="claude-haiku-4-5",
        name="support-agent",
        model_api_parameters={"max_tokens": 1024},
    )
)


def run_turn(message: str, order_id: str, user_id: str, session_id: str) -> str:
    """Run one turn (tool, then agent) and record it as one Agnost AI conversation turn."""
    with using_attributes(user_id=user_id, session_id=session_id):
        with tracer.start_as_current_span("agent_turn", attributes={
            "gen_ai.operation.name": "invoke_agent",
            "gen_ai.agent.name": "support-agent",
            "user.id": user_id,
            "session.id": session_id,
            "gen_ai.input.messages": json.dumps(
                [{"role": "user", "parts": [{"type": "text", "content": message}]}]),
        }) as span:
            status = order_status.run(OrderStatusInput(order_id=order_id)).status
            reply = agent.run(BasicChatInputSchema(
                chat_message=f"{message}\n\nOrder {order_id} status: {status}"))
            answer = reply.chat_message
            span.set_attribute("gen_ai.output.messages", json.dumps(
                [{"role": "assistant", "parts": [{"type": "text", "content": answer}]}]))
            return answer


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

What each piece does:

* **`AtomicAgentsInstrumentor().instrument()`** traces `AtomicAgent.run` (and `run_async`, `run_stream`, `run_async_stream`), every `BaseTool.run`, and each model call Instructor makes, including retries after a validation error.
* **`TracingConfig(capture_messages=True)`** adds `gen_ai.input.messages` and `gen_ai.output.messages` to model spans. Without it, model spans carry only the model name and token counts. Agent and tool spans record their input and output either way.
* **`using_attributes(user_id=..., session_id=...)`** puts `session.id`, `gen_ai.conversation.id`, and `user.id` on every Atomic Agents span inside the block. Every turn with the same `session_id` lands in the same Agnost AI conversation. This needs the `phoenix` extra.
* **The `agent_turn` span** becomes the root of each trace. Atomic Agents has no tool loop: your code calls tools and agents one after another, and without a parent each call is its own trace and its own transcript entry. Agnost AI builds the conversation transcript from each trace's root span, so the wrapper holds the user's message and the final answer.

In a long-running server, create the `TracerProvider` and call `instrument()` 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 `using_attributes`.
* **Messages**: the user's message and the agent's answer for each turn, from the `agent_turn` span.
* **Events**: the turn and the `support-agent` run (both `agent`, the run with its input and output schemas as JSON), each model call (`llm`) with the request messages and token counts, and each tool run (`tool`) with the tool name, arguments, and result. Atomic Agents gets structured output from Claude as a tool call, so model events show no reply text. The reply is on the agent event.

### 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, a `get_order_status` tool event with arguments and a result, and a `support-agent` event.

### 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.
* **`ModuleNotFoundError` from `instrument()`**: install `"atomic-agents[observability]"` or `"atomic-agents[phoenix]"`.
* **User or conversation is missing**: install the `phoenix` extra, and call the agent inside the `using_attributes` block. Without OpenInference installed, use `atomic_agents.observability.using_conversation(session_id)` for the conversation, and set `user.id` on the `agent_turn` span.
* **Each tool and agent call is a separate transcript turn**: run them inside the `agent_turn` span.
* **Model events have no message text**: pass `TracingConfig(capture_messages=True)`, or set `ATOMIC_AGENTS_TRACE_CAPTURE_MESSAGES=true`.
* **Each model call appears twice**: you also run a provider instrumentor such as `openinference-instrumentation-anthropic`. Remove it, or pass `TracingConfig(llm_spans=False)`.
* **The tool shows up as its input schema's class name**: set `BaseToolConfig(title=...)` to the name you want.

### References

* [Atomic Agents observability guide](https://github.com/eigenwise/atomic-agents/blob/main/docs/guides/observability.md)
* [Atomic Agents Phoenix tracing example](https://github.com/eigenwise/atomic-agents/tree/main/atomic-examples/phoenix-tracing)
* [OpenInference tracing helpers](https://github.com/Arize-ai/openinference/tree/main/python/openinference-instrumentation)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete Atomic Agents 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.