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

# BAML

> Capture BAML function calls with the Agnost AI SDK and BAML's Collector

## 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 BAML application.
Org ID: your-org-id
Instrument the real b.<Function>() call path and verify one fresh interaction.
```

BAML runs its LLM calls inside its own Rust runtime. Python and Node.js HTTP
instrumentors (OpenInference, OpenLIT, OpenLLMetry) never see those requests, and
BAML's built-in tracing only sends to Boundary Studio. To get BAML calls into
Agnost AI, wrap each BAML function call and read the call details from a BAML
`Collector`. This guide covers BAML v0 (`baml-py` and `@boundaryml/baml`), the
current stable release.

## Manual setup: Agnost AI SDK

```bash Python theme={null}
pip install agnost baml-py
```

```bash TypeScript theme={null}
npm install agnostai @boundaryml/baml
```

Pass a fresh `Collector` to each call with `baml_options`. After the call,
`collector.last` holds the function name, token usage, and the LLM calls BAML
made, including retries and fallbacks. The selected call is the one whose result
BAML parsed.

```python Python theme={null}
import agnost
from baml_py import Collector
from baml_client import b

agnost.init("your-org-id")


def answer_ticket(message: str, user_id: str, conversation_id: str):
    collector = Collector(name="agnost")
    interaction = agnost.begin(
        user_id=user_id,
        agent_name="baml-support",
        input=message,
        conversation_id=conversation_id,  # groups turns into one conversation
    )
    if interaction is None:
        raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
    try:
        reply = b.AnswerTicket(message, baml_options={"collector": collector})
        log = collector.last
        call = log.selected_call if log else None
        if call is not None:
            interaction.set_properties({
                "baml_function": log.function_name,
                "baml_client": call.client_name,
                "provider": call.provider,
                "input_tokens": log.usage.input_tokens,
                "output_tokens": log.usage.output_tokens,
            })
        interaction.end(output=reply.model_dump_json())
        return reply
    except Exception as exc:
        interaction.end(output=str(exc), success=False)
        raise
```

```typescript TypeScript theme={null}
import { Collector } from "@boundaryml/baml";
import * as agnost from "agnostai";
import { b } from "./baml_client";

agnost.init("your-org-id");

export async function answerTicket(message: string, userId: string, conversationId: string) {
  const collector = new Collector("agnost");
  const interaction = agnost.begin({
    userId,
    agentName: "baml-support",
    input: message,
    conversationId,
  });
  if (!interaction) throw new Error("Agnost is not initialized. Call agnost.init() first.");
  try {
    const reply = await b.AnswerTicket(message, { collector });
    const log = collector.last;
    const call = log?.calls.find((c) => c.selected);
    if (log && call) {
      interaction.setProperties({
        baml_function: log.functionName,
        baml_client: call.clientName,
        provider: call.provider,
        input_tokens: log.usage.inputTokens,
        output_tokens: log.usage.outputTokens,
      });
    }
    interaction.end(JSON.stringify(reply));
    return reply;
  } catch (error) {
    interaction.end(String(error), false);
    throw error;
  }
}
```

`AnswerTicket` stands for any function in your `baml_src`. BAML returns a typed
object, so the example records it as JSON. Record a single field instead (for
example `reply.reply`) if that is the text your users see.

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

### What appears in Agnost AI

* **Conversations** grouped by `conversation_id`.
* **User-level analytics** grouped by `user_id`.
* **Events** for each BAML function call, with the user message as input, the
  parsed result as output, and the BAML function, client, provider, and token
  counts as event metadata.

## Manual setup: OpenTelemetry

BAML has no OpenTelemetry exporter, and its provider calls are invisible to OTel
instrumentors. If you already run an OpenTelemetry pipeline, record one span per
BAML call with GenAI semantic-convention attributes filled from the `Collector`.
Agnost AI accepts these spans as agent events.

### Install

```bash theme={null}
pip install baml-py opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
```

### Setup

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

from baml_py import Collector
from baml_client import b
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

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint="https://otel.agnost.ai/v1/traces",
    headers={"X-Agnost-Org-ID": os.environ["AGNOST_ORG_ID"]},
)))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("baml-agnost")


def text_message(role: str, text: str) -> str:
    return json.dumps([{"role": role, "parts": [{"type": "text", "content": text}]}])


def answer_ticket(message: str, user_id: str, conversation_id: str):
    collector = Collector(name="agnost")
    with tracer.start_as_current_span("AnswerTicket") as span:
        span.set_attribute("gen_ai.operation.name", "chat")
        span.set_attribute("gen_ai.agent.name", "baml-support")
        span.set_attribute("gen_ai.conversation.id", conversation_id)
        span.set_attribute("user.id", user_id)
        span.set_attribute("gen_ai.input.messages", text_message("user", message))

        reply = b.AnswerTicket(message, baml_options={"collector": collector})

        span.set_attribute("gen_ai.output.messages", text_message("assistant", reply.model_dump_json()))
        log = collector.last
        call = log.selected_call if log else None
        if call is not None:
            span.set_attribute("gen_ai.provider.name", call.provider)
            model = call.http_request.body.json().get("model")
            if model:
                span.set_attribute("gen_ai.request.model", model)
            if log.usage.input_tokens is not None:
                span.set_attribute("gen_ai.usage.input_tokens", log.usage.input_tokens)
            if log.usage.output_tokens is not None:
                span.set_attribute("gen_ai.usage.output_tokens", log.usage.output_tokens)
        return reply
```

`gen_ai.conversation.id` groups spans into one conversation and `user.id`
attributes them to a user. If `b.AnswerTicket` raises, the span ends with an
error status and Agnost AI marks the event as failed. The model name is read from
the request body BAML sent, which holds it for OpenAI- and Anthropic-style
providers. Call `provider.shutdown()` once when the process exits.

### Verify

Run one BAML function call, then open **Events** in Agnost AI. Confirm the event
shows the user message as input, the parsed result as output, and your user ID.
Then open **Conversations** and confirm two calls with the same conversation ID
land in one conversation.

### Troubleshooting

* Pass the collector on every call: `baml_options={"collector": collector}` in
  Python, `{ collector }` in TypeScript. Without it, `collector.last` is `None`.
* Create one `Collector` per request. A shared collector keeps every past call,
  and `collector.last` can belong to another request.
* Confirm `agnost.init("your-org-id")` runs before the first `begin()`.
* Short scripts must call `agnost.shutdown()` or `agnost.flush()` before exit.
* For the OpenTelemetry path, confirm `X-Agnost-Org-ID` is set on the exporter
  and that every span has `gen_ai.operation.name`. Spans without GenAI attributes
  are dropped.
* Setting `BOUNDARY_API_KEY` sends traces to Boundary Studio. It does not affect
  Agnost AI, and you can use both.

### References

* [BAML Collector reference](https://docs.boundaryml.com/ref/baml_client/collector)
* [Track tokens and raw requests with a Collector](https://docs.boundaryml.com/guide/baml-advanced/collector-track-tokens)
* [Boundary Studio tracing](https://docs.boundaryml.com/guide/boundary-cloud/observability/tracking-usage)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete BAML interaction.
* [Events](https://docs.agnost.ai/using-events.md): inspect each BAML function call and its metadata.
* [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.