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

# Ultravox

> Send finished Ultravox calls to Agnost AI from your call.ended webhook

## 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 Ultravox application.
Org ID: your-org-id
Record each finished call from the call.ended webhook handler and verify one fresh call.
```

Ultravox sends a `call.ended` webhook when a call finishes, but the payload holds only the call object. The transcript lives behind the [List Call Messages](https://docs.ultravox.ai/api-reference/calls/calls-messages-list) API, which needs your Ultravox API key. To keep that key on your own server, Agnost AI does not receive Ultravox webhooks directly. Instead, your webhook handler fetches the messages and records each exchange with the Agnost AI SDK.

Hosted Ultravox calls do not export OpenTelemetry traces, so this guide has no OpenTelemetry section. If you run the Ultravox model inside Pipecat or LiveKit Agents, use the OpenTelemetry route for those frameworks instead. See [Ultravox in Pipecat or LiveKit Agents](#ultravox-in-pipecat-or-livekit-agents).

## Manual setup: Agnost AI SDK

### Install

```bash theme={null}
pip install agnost fastapi httpx uvicorn
```

### Add the webhook handler

Save this as `ultravox_webhook.py`. It verifies the Ultravox signature, answers `204` right away, then fetches the call's messages and sends one Agnost AI event per caller and agent exchange.

```python theme={null}
import hashlib
import hmac
import json
import os
from datetime import datetime, timedelta, timezone

import agnost
import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response

agnost.init(os.environ["AGNOST_ORG_ID"])

ULTRAVOX_API_KEY = os.environ["ULTRAVOX_API_KEY"]
ULTRAVOX_WEBHOOK_SECRET = os.environ["ULTRAVOX_WEBHOOK_SECRET"]

app = FastAPI()


def verify_signature(request: Request, body: bytes) -> None:
    timestamp = request.headers.get("X-Ultravox-Webhook-Timestamp", "")
    try:
        sent_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
    except ValueError:
        raise HTTPException(status_code=401, detail="Missing or bad timestamp")
    if sent_at.tzinfo is None:
        sent_at = sent_at.replace(tzinfo=timezone.utc)
    if datetime.now(timezone.utc) - sent_at > timedelta(minutes=1):
        raise HTTPException(status_code=401, detail="Expired webhook")
    expected = hmac.new(
        ULTRAVOX_WEBHOOK_SECRET.encode(), body + timestamp.encode(), hashlib.sha256
    ).hexdigest()
    signatures = request.headers.get("X-Ultravox-Webhook-Signature", "").split(",")
    if not any(hmac.compare_digest(s.strip(), expected) for s in signatures):
        raise HTTPException(status_code=401, detail="Bad signature")


def fetch_messages(call_id: str) -> list:
    url = f"https://api.ultravox.ai/api/calls/{call_id}/messages"
    params = {"mode": "in_call", "pageSize": 100}
    messages = []
    while url:
        response = httpx.get(
            url, params=params, headers={"X-API-Key": ULTRAVOX_API_KEY}, timeout=30
        )
        response.raise_for_status()
        page = response.json()
        messages.extend(page["results"])
        url, params = page.get("next"), None
    return messages


def seconds(value) -> float:
    # Ultravox timespans are strings such as "12.480s".
    return float(value.rstrip("s")) if value else 0.0


def record_call(call: dict) -> None:
    if call.get("endReason") == "unjoined" or not call.get("joined"):
        return
    call_id = call["callId"]
    joined = datetime.fromisoformat(call["joined"].replace("Z", "+00:00"))
    agent_name = (call.get("agent") or {}).get("name") or "ultravox"
    user_id = (call.get("metadata") or {}).get("user_id") or call_id

    # One exchange is the caller's turn plus the agent's reply and any tool
    # calls the agent made while answering.
    exchanges = []
    current = None
    for message in fetch_messages(call_id):
        role = message.get("role")
        text = message.get("text") or ""
        span = message.get("wallClockTimespan") or {}
        if role == "MESSAGE_ROLE_USER" and (current is None or current["output"] or current["tools"]):
            current = None
        if current is None:
            current = {"input": [], "output": [], "tools": [], "start": seconds(span.get("start")), "end": 0.0}
            exchanges.append(current)
        current["end"] = max(current["end"], seconds(span.get("end")))
        if role == "MESSAGE_ROLE_USER":
            current["input"].append(text)
        elif role == "MESSAGE_ROLE_AGENT":
            current["output"].append(text)
        elif role == "MESSAGE_ROLE_TOOL_CALL":
            current["tools"].append(
                {"id": message.get("invocationId"), "name": message.get("toolName"), "arguments": text}
            )
        elif role == "MESSAGE_ROLE_TOOL_RESULT":
            for tool in current["tools"]:
                if tool["id"] == message.get("invocationId"):
                    tool["result"] = text

    if not any(exchange["input"] for exchange in exchanges):
        return  # The caller never spoke.
    for index, exchange in enumerate(exchanges):
        agnost.track(
            user_id=user_id,
            agent_name=agent_name,
            conversation_id=call_id,
            input=" ".join(exchange["input"]) or None,
            output=" ".join(exchange["output"]) or None,
            timestamp=joined + timedelta(seconds=exchange["start"]),
            latency=int(max(0.0, exchange["end"] - exchange["start"]) * 1000),
            properties={
                "ultravox_call_id": call_id,
                "exchange_index": index,
                "end_reason": call.get("endReason") or "",
                "tool_calls": exchange["tools"],
            },
        )
    agnost.flush()


@app.post("/ultravox/webhook")
async def ultravox_webhook(request: Request, background_tasks: BackgroundTasks):
    body = await request.body()
    verify_signature(request, body)
    event = json.loads(body)
    if event.get("event") == "call.ended":
        background_tasks.add_task(record_call, event["call"])
    return Response(status_code=204)
```

Set three environment variables and run it:

```bash theme={null}
export AGNOST_ORG_ID="your-agnost-org-id"
export ULTRAVOX_API_KEY="your-ultravox-api-key"
export ULTRAVOX_WEBHOOK_SECRET="your-webhook-secret"
uvicorn ultravox_webhook:app --port 8000
```

Each call becomes one Agnost AI conversation keyed by the Ultravox `callId`. The agent name comes from the Ultravox agent's name. The user ID comes from a `user_id` key in the call's `metadata`, so set it when you create the call. Without it, the call ID is used. Tool calls the agent made while answering are attached to that exchange as the `tool_calls` property.

The call is over when the webhook arrives, so the handler uses `agnost.track()` with the exchange's input, output, and latency rather than `begin()` and `end()`.

### Subscribe to call.ended

Expose the handler at a public HTTPS URL, then create the webhook with the Ultravox API:

```bash theme={null}
curl -X POST "https://api.ultravox.ai/api/webhooks" \
  -H "X-API-Key: $ULTRAVOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-app.example.com/ultravox/webhook", "events": ["call.ended"], "secrets": ["'"$ULTRAVOX_WEBHOOK_SECRET"'"]}'
```

Without an `agentId`, the webhook covers every call in your account. Add `"agentId": "<agent-id>"` to cover one agent.

## Verify

1. Place a short call with the agent and say at least one sentence as the caller.
2. Check your server log for a `204` response to `POST /ultravox/webhook`.
3. In [app.agnost.ai](https://app.agnost.ai), open **Conversations** and find the Ultravox call ID. Each exchange shows the caller's words as input and the agent's reply as output, with an `exchange_index` property that gives its order in the call.

## Troubleshooting

* **The handler returns `401`:** check that `ULTRAVOX_WEBHOOK_SECRET` matches a secret on the Ultravox webhook, and that your server clock is correct. The handler rejects deliveries more than one minute old.
* **The handler returns `204` but no conversation appears:** the call was never joined, or the caller never spoke. Check the server log for an error from the messages request, such as a `401` from a wrong `ULTRAVOX_API_KEY`.
* **Exchanges show the time they were sent instead of their time in the call:** `agnost` 0.2.1 on PyPI does not forward the `timestamp` argument yet. Use `exchange_index` to read the order.
* **A call appears twice:** Ultravox can deliver the same webhook more than once and retries failed deliveries. Store the call IDs you have processed and skip repeats.
* **Users show as call IDs:** set a `user_id` key in the call's `metadata` when you create the call.

## Ultravox in Pipecat or LiveKit Agents

Pipecat and LiveKit Agents both ship an Ultravox integration. When Ultravox runs inside one of those frameworks, the framework's own telemetry covers the call, so follow the Agnost AI [Pipecat](https://docs.agnost.ai/pipecat.md) or [LiveKit](https://docs.agnost.ai/livekit.md) guide and skip the webhook handler above.

## References

* [Ultravox webhooks overview](https://docs.ultravox.ai/webhooks/overview)
* [Ultravox available webhooks](https://docs.ultravox.ai/webhooks/available-webhooks)
* [Securing Ultravox webhooks](https://docs.ultravox.ai/webhooks/securing-webhooks)
* [Ultravox webhook retries](https://docs.ultravox.ai/webhooks/errors-and-retries)
* [List Call Messages API](https://docs.ultravox.ai/api-reference/calls/calls-messages-list)
* [Ultravox with Pipecat](https://docs.ultravox.ai/integrations/pipecat) and [with LiveKit](https://docs.ultravox.ai/integrations/livekit)
* [Agnost AI Python SDK](https://docs.agnost.ai/python-conversation.md)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review complete Ultravox calls.
* [Events](https://docs.agnost.ai/using-events.md): inspect each caller and agent exchange.
* [Patterns](https://docs.agnost.ai/using-patterns.md): understand why callers contacted the agent.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.