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

# smolagents

> Capture traces from Hugging Face smolagents with the OpenInference 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 smolagents application.
Org ID: your-org-id
Instrument the real agent.run() path, set session and user 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="smolagents-support",
    input=task,
    conversation_id="sess-123",  # groups turns into one conversation
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
try:
    answer = agent.run(task)
    interaction.end(output=str(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

smolagents uses the OpenInference instrumentor `openinference-instrumentation-smolagents` for OpenTelemetry tracing. It traces each agent run, each step, each model call, and each tool call. Send those spans to Agnost AI with a standard OTLP exporter.

### Install

```bash theme={null}
pip install 'smolagents[litellm]' openinference-instrumentation-smolagents \
            opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
```

The `litellm` extra provides `LiteLLMModel`, which this example uses to call Claude. Any smolagents model class works the same way.

### Setup

```python theme={null}
from openinference.instrumentation import using_attributes
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from smolagents import LiteLLMModel, ToolCallingAgent, tool

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint="https://otel.agnost.ai/v1/traces",
    headers={"X-Agnost-Org-ID": "your-org-id"},
)))
trace.set_tracer_provider(provider)
SmolagentsInstrumentor().instrument(tracer_provider=provider)


@tool
def get_weather(city: str) -> str:
    """Return the current weather for a city.

    Args:
        city: The city name.
    """
    return f"It is sunny in {city}."


agent = ToolCallingAgent(
    tools=[get_weather],
    model=LiteLLMModel(model_id="anthropic/claude-haiku-4-5"),
    name="weather_agent",
)

with using_attributes(session_id="sess-123", user_id="u-42"):
    agent.run("What's the weather in Paris?")
    agent.run("And in Tokyo?", reset=False)

provider.force_flush()
```

`using_attributes` puts `session.id` and `user.id` on every span created inside the block. Agnost AI groups all runs with the same `session.id` into one conversation and attributes it to `user.id`. Wrap each request in its own `using_attributes` block with that request's session and user. Pass `reset=False` to keep the agent's memory between turns of the same session.

`CodeAgent` is traced the same way. Call `SmolagentsInstrumentor().instrument()` once at startup, before any agent runs.

### 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` from `using_attributes`.
* **Messages**: one turn per `agent.run(...)` call, from the root `<agent name>.run` span. The answer is the agent's final answer. The user side shows smolagents' run arguments as JSON, with your prompt in the `task` field.
* **Events**: the agent run, `Step N` spans, model calls such as `LiteLLMModel.generate` with token counts, and tool calls with arguments and results.

### Verify

Run one `agent.run` call, wait about 30 seconds, then open **Conversations** in Agnost AI. Confirm the conversation shows your `user_id`, the task and the final answer, and a tool event for `get_weather` with arguments and a result.

### Troubleshooting

* **Nothing arrives**: confirm the exporter header is `X-Agnost-Org-ID` and the endpoint ends in `/v1/traces`. Short scripts must call `provider.force_flush()` before they exit.
* **Each run is its own conversation, or the user is empty**: the run happened outside a `using_attributes(session_id=..., user_id=...)` block.
* **Tool events are named `SimpleTool`**: OpenInference names tool spans after the tool's Python class, and every function decorated with `@tool` is a `SimpleTool`. The real tool name is in the event metadata as `tool.name`. Subclass `Tool` with a descriptive class name if you need distinct names in the events list.
* **No spans at all**: call `SmolagentsInstrumentor().instrument()` before you create or run agents.

### References

* [smolagents: Inspecting runs with OpenTelemetry](https://huggingface.co/docs/smolagents/tutorials/inspect_runs)
* [smolagents models](https://huggingface.co/docs/smolagents/reference/models)
* [OpenInference smolagents instrumentor](https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-smolagents)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete smolagents session.
* [Events](https://docs.agnost.ai/using-events.md): inspect agent steps, model calls, and tool calls.
* [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.