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

# Rasa

> Capture Rasa Pro and Mantle conversations with an event broker

## 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 Rasa assistant.
Org ID: your-org-id
Add the Agnost AI event broker and verify one fresh conversation.
```

Rasa sends every conversation event to an event broker. A small custom broker turns each user turn into one Agnost AI event: the user message is the input and the assistant's replies are the output. It works for Rasa Pro projects configured with `endpoints.yml` and for Mantle agents configured with `integrations.yml`. Your flows, skills, and channels do not change.

## Manual setup: Agnost AI SDK

### Install

Install the SDK in the same Python environment as Rasa:

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

### 1. Add the turn collector

Create an `addons/` folder in the project root, next to `endpoints.yml` or `agent.yml`, with an empty `addons/__init__.py`. Then add `addons/agnost_turns.py`:

```python theme={null}
import json
from typing import Any, Dict, Optional

import agnost


class AgnostTurns:
    """Turns Rasa broker events into one Agnost AI event per user turn."""

    def __init__(self, org_id: str, agent_name: str = "rasa") -> None:
        if not agnost.init(org_id):
            raise RuntimeError("Agnost AI did not initialize. Check org_id.")
        self.agent_name = agent_name
        self.turns: Dict[str, Dict[str, Any]] = {}

    def user(
        self,
        conversation_id: str,
        user_id: Optional[str],
        text: Optional[str],
        timestamp: Optional[float],
    ) -> None:
        self.finish(conversation_id, timestamp)  # close a turn that never ended
        interaction = agnost.begin(
            user_id=user_id or conversation_id,
            agent_name=self.agent_name,
            input=text or "",
            conversation_id=conversation_id,
        )
        if interaction is None:
            return  # Agnost AI is not initialized; never break the conversation
        self.turns[conversation_id] = {
            "interaction": interaction,
            "started": timestamp,
            "replies": [],
            "tools": [],
        }

    def bot(self, conversation_id: str, text: Optional[str]) -> None:
        turn = self.turns.get(conversation_id)
        if turn is not None and text:
            turn["replies"].append(text)

    def tool(self, conversation_id: str, name: str, is_error: bool) -> None:
        turn = self.turns.get(conversation_id)
        if turn is not None:
            turn["tools"].append({"name": name, "is_error": is_error})

    def finish(self, conversation_id: str, timestamp: Optional[float]) -> None:
        turn = self.turns.pop(conversation_id, None)
        if turn is None:
            return
        interaction = turn["interaction"]
        latency = None
        if turn["started"] and timestamp:
            latency = max(0, int((timestamp - turn["started"]) * 1000))
        if turn["tools"]:
            interaction.set_property("tool_calls", json.dumps(turn["tools"]))
        interaction.end(output="\n".join(turn["replies"]), latency=latency)
```

Latency comes from Rasa's own event timestamps, from the user message to the end of the assistant's turn.

### 2. Add the broker for your project type

#### Rasa Pro (CALM)

Add `addons/agnost_broker.py`. Rasa Pro publishes flat events such as `{"event": "user", ...}`, and the turn ends when Rasa runs `action_listen`.

```python theme={null}
from typing import Any, Dict, Optional

from rasa.core.brokers.broker import EventBroker
from rasa.utils.endpoints import EndpointConfig

from addons.agnost_turns import AgnostTurns


class AgnostEventBroker(EventBroker):
    """Rasa Pro (CALM) event broker that sends each turn to Agnost AI."""

    def __init__(self, org_id: str, agent_name: str = "rasa") -> None:
        super().__init__()
        self.stream_pii = True
        self.turns = AgnostTurns(org_id, agent_name)

    @classmethod
    async def from_endpoint_config(
        cls, broker_config: EndpointConfig, event_loop: Optional[Any] = None
    ) -> "AgnostEventBroker":
        return cls(**broker_config.kwargs)

    def publish(self, event: Dict[str, Any]) -> None:
        conversation_id = event["sender_id"]
        kind = event.get("event")
        if kind == "user":
            self.turns.user(
                conversation_id,
                event.get("user_id"),
                event.get("text"),
                event.get("timestamp"),
            )
        elif kind == "bot":
            self.turns.bot(conversation_id, event.get("text"))
        elif kind == "action" and event.get("name") == "action_listen":
            self.turns.finish(conversation_id, event.get("timestamp"))
```

Register it in `endpoints.yml`:

```yaml endpoints.yml theme={null}
event_broker:
  type: addons.agnost_broker.AgnostEventBroker
  org_id: ${AGNOST_ORG_ID}
  agent_name: support-assistant
```

Start Rasa from the project root so `addons` can be imported:

```bash theme={null}
export AGNOST_ORG_ID=<your-org-id>
rasa run --endpoints endpoints.yml
```

Rasa accepts one `event_broker`. If you already stream events to Kafka, keep that broker and run the collector in a Kafka consumer instead: create `AgnostEventBroker(org_id="<your-org-id>")` once and pass each decoded message to its `publish` method. Rasa writes the same event JSON to the topic.

#### Mantle

Add `addons/agnost_mantle_broker.py`. Mantle publishes nested events such as `{"user": {...}}`, records tool calls as `tool_executed`, and ends each turn with `bot_turn_ended`.

```python theme={null}
from typing import Any, Dict

from rasa.api.brokers.v1 import EventBroker, EventBrokerSettings

from addons.agnost_turns import AgnostTurns


class AgnostMantleEventBroker(EventBroker):
    """Mantle event broker that sends each turn to Agnost AI."""

    def __init__(self) -> None:
        super().__init__()
        self.turns: AgnostTurns

    async def connect(self, settings: EventBrokerSettings) -> None:
        self.turns = AgnostTurns(
            settings.params["org_id"], settings.params.get("agent_name", "rasa")
        )

    def publish(self, event: Dict[str, Any]) -> None:
        conversation_id = event["conversation_id"]
        if "user" in event:
            self.turns.user(
                conversation_id,
                event.get("user_id"),
                event["user"].get("text"),
                event.get("timestamp"),
            )
        elif "bot" in event:
            self.turns.bot(conversation_id, event["bot"].get("text"))
        elif "tool_executed" in event:
            tool = event["tool_executed"]
            self.turns.tool(
                conversation_id, tool.get("tool_name", ""), bool(tool.get("is_error"))
            )
        elif "bot_turn_ended" in event:
            self.turns.finish(conversation_id, event.get("timestamp"))
```

Register it in `integrations.yml`:

```yaml integrations.yml theme={null}
event_broker:
  type: addons.agnost_mantle_broker.AgnostMantleEventBroker
  org_id: ${AGNOST_ORG_ID}
  agent_name: support-agent
```

Mantle requires a custom broker to subclass `rasa.api.brokers.v1.EventBroker` directly, so the Rasa Pro class above does not load in a Mantle agent.

### Data mapping

* The Rasa conversation ID (`sender_id`, or `conversation_id` on Mantle events) becomes the Agnost AI conversation ID.
* The event's `user_id` becomes the user ID. When the channel does not set one, the conversation ID is used.
* The user message is the event input. All assistant messages until the end of the turn are joined with newlines as the output.
* `agent_name` from the broker config becomes the agent name. It defaults to `rasa`.
* On Mantle, tools called during the turn are listed in the event's `tool_calls` metadata with their name and error flag.

## Why there is no OpenTelemetry section

Rasa can export traces over OTLP (`tracing: type: otlp`), but its spans describe Rasa internals with attributes such as `sender_id`, `class_name`, and `voice.*`. They carry no GenAI or OpenInference attributes and no message text, so the Agnost AI collector ignores them. Use the event broker above for conversations, and keep Rasa's OTLP tracing for your own trace backend if you use one.

### Verify

1. Start Rasa with the broker configured, then send two messages in one conversation through any channel, such as the Inspector or the REST channel.
2. Open **Conversations** in [app.agnost.ai](https://app.agnost.ai). The conversation ID matches the Rasa conversation ID, and each user message is one event.
3. Open an event and confirm the input is the user's message and the output is the assistant's full reply.

### Troubleshooting

* **Rasa logs `The EventBroker type ... could not be found`:** start Rasa from the project root and confirm `addons/__init__.py` exists.
* **Rasa fails at startup with `Agnost AI did not initialize`:** set `AGNOST_ORG_ID` to your organization ID before starting Rasa.
* **Mantle says the broker must subclass the published contract:** use `AgnostMantleEventBroker` in `integrations.yml`, not the Rasa Pro class.
* **Events appear but outputs are empty:** the assistant replied with buttons or custom payloads only. The broker records bot `text` only.
* **Every conversation shows the same user:** your channel does not set a user ID, so the conversation ID is used. Set the user ID in your channel to group conversations per person.

### References

* [Rasa event brokers and custom brokers](https://rasa.com/docs/reference/integrations/event-brokers)
* [Mantle custom event broker](https://rasa.com/docs/mantle/reference/custom-event-broker)
* [Mantle conversation events](https://rasa.com/docs/mantle/reference/events)
* [Rasa tracing](https://rasa.com/docs/pro/improve/tracing)
* [Agnost AI Python SDK](https://docs.agnost.ai/python-conversation.md)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review complete Rasa conversations.
* [Events](https://docs.agnost.ai/using-events.md): inspect each user turn and the assistant's reply.
* [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.