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

# Deepgram Voice Agent API

> Capture Deepgram Voice Agent conversations with the Agnost AI SDK

## 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 Deepgram Voice Agent application.
Org ID: your-org-id
Record each user turn and the agent's reply from the Voice Agent WebSocket messages and verify one fresh conversation.
```

The Deepgram Voice Agent API runs the whole conversation over one WebSocket that your own code opens. Deepgram has no post-call webhook, so Agnost AI captures the conversation where your code already receives it: the WebSocket messages. Each user turn and the agent's reply become one Agnost AI interaction, grouped into one conversation per session.

## Manual setup: Agnost AI SDK

### Install

```bash theme={null}
pip install agnost deepgram-sdk
```

### Add the turn tracker

The tracker reads the messages Deepgram already sends to your client:

* `ConversationText` with `role` `user` starts an interaction with the user's words as input.
* `ConversationText` with `role` `assistant` is added to the reply. Think Live backchannels such as "mhmm" are skipped.
* `FunctionCallRequest`, `FunctionCallResponse`, and `FunctionCallCancelled` record the agent's function calls and their results.
* `UserStartedSpeaking` or the next user turn ends the previous interaction. `AgentAudioDone` sets its latency to the end of the agent's speech.
* `Error` ends the open interaction as failed.

```python theme={null}
import time

import agnost

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


class AgnostTurnTracker:
    """Records each user turn and the agent's reply as one Agnost AI interaction."""

    def __init__(self, user_id, conversation_id, agent_name="deepgram-voice-agent"):
        self.user_id = user_id
        self.conversation_id = conversation_id
        self.agent_name = agent_name
        self.request_id = ""
        self.interaction = None
        self.started_at = None
        self.audio_done_at = None
        self.replies = []
        self.tool_calls = {}

    def on_message(self, message):
        if isinstance(message, bytes):
            return  # agent audio
        kind = getattr(message, "type", None)
        if kind == "Welcome":
            self.request_id = message.request_id
        elif kind == "ConversationText" and message.role == "user":
            self.finish()
            self.interaction = agnost.begin(
                user_id=self.user_id,
                agent_name=self.agent_name,
                input=message.content,
                conversation_id=self.conversation_id,
                properties={"deepgram_request_id": self.request_id},
            )
            if self.interaction is None:
                raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
            self.started_at = time.monotonic()
        elif kind == "ConversationText" and self.interaction is not None:
            if message.conversational_behavior != "backchannel":
                self.replies.append(message.content)
        elif kind == "UserStartedSpeaking":
            self.finish()
        elif kind == "FunctionCallRequest":
            for call in message.functions:
                self.tool_calls[call.id] = {"name": call.name, "arguments": call.arguments}
        elif kind == "FunctionCallResponse":  # functions Deepgram runs for you
            self.record_function_result(message.id, message.content)
        elif kind == "FunctionCallCancelled":
            for call in message.functions:
                self.tool_calls.pop(call.id, None)
        elif kind == "AgentAudioDone":
            self.audio_done_at = time.monotonic()
        elif kind == "Error":
            self.finish(error=f"{message.code}: {message.description}")

    def record_function_result(self, call_id, content):
        if call_id in self.tool_calls:
            self.tool_calls[call_id]["result"] = content

    def finish(self, error=None):
        if self.interaction is None:
            return
        if self.tool_calls:
            self.interaction.set_property("tool_calls", list(self.tool_calls.values()))
            self.tool_calls = {}
        if error:
            self.interaction.set_property("deepgram_error", error)
        latency = None
        if self.audio_done_at is not None and self.audio_done_at > self.started_at:
            latency = int((self.audio_done_at - self.started_at) * 1000)
        self.interaction.end(
            output=" ".join(self.replies) or error or "",
            success=error is None,
            latency=latency,
        )
        self.interaction = None
        self.audio_done_at = None
        self.replies = []
```

### Connect it to the WebSocket

Register the tracker's `on_message` next to your own message handler. Use your own call or session ID as `conversation_id` and your user ID as `user_id`.

```python theme={null}
from deepgram import DeepgramClient
from deepgram.core.events import EventType

client = DeepgramClient(api_key=DEEPGRAM_API_KEY)
tracker = AgnostTurnTracker(user_id="u-42", conversation_id="call-123")

with client.agent.v1.connect() as connection:
    connection.on(EventType.MESSAGE, tracker.on_message)
    connection.on(EventType.MESSAGE, on_message)  # your existing handler
    connection.send_settings(settings)
    # ... start_listening(), stream audio, handle function calls ...

tracker.finish()
agnost.flush()
```

When your code runs a client-side function (`client_side: true`), pass its result to the tracker where you send the `FunctionCallResponse`:

```python theme={null}
connection.send_function_call_response(
    AgentV1SendFunctionCallResponse(id=call.id, name=call.name, content=result)
)
tracker.record_function_result(call.id, result)
```

`AgentV1SendFunctionCallResponse` comes from `deepgram.agent.v1.types`.

Call `agnost.flush()` after each session so short-lived workers send the last turn. Call `agnost.shutdown()` once when the process exits, not after each session.

### What appears in Agnost AI

* One conversation per `conversation_id`, under the user from `user_id`.
* One event per user turn, with the user's words as input and everything the agent said in reply as output.
* Function calls as a `tool_calls` property on the turn that made them, with each call's `name`, `arguments`, and `result`. Cancelled speculative calls are dropped.
* Deepgram's `request_id` from `Welcome` as `deepgram_request_id`, so you can match a turn to Deepgram's usage logs.
* Latency from the end of the user's turn to the end of the agent's speech.

The greeting the agent speaks before the user's first turn is not recorded, because no user turn is open yet.

### Verify

Run one session, then open [app.agnost.ai](https://app.agnost.ai). Confirm:

1. **Users** shows the value you passed as `user_id`.
2. The conversation has one event per user turn, with the user's words as input and the agent's reply as output.
3. A turn that called a function shows `tool_calls` in its event metadata.

### Troubleshooting

* **No events:** register `tracker.on_message` before `start_listening()`, and call `agnost.flush()` before the process exits.
* **The last turn is missing:** call `tracker.finish()` when the connection closes.
* **A turn has an empty output:** the user hung up or barged in before the agent replied.
* **A function call has no `result`:** call `tracker.record_function_result()` where you send `FunctionCallResponse` for client-side functions.
* **Each turn is a separate conversation:** pass the same `conversation_id` for the whole session.

### References

* [Deepgram: Voice Agent API overview](https://developers.deepgram.com/docs/voice-agent)
* [Deepgram: Build a Voice Agent with Python](https://developers.deepgram.com/docs/build-a-voice-agent-python)
* [Deepgram: Conversation Text](https://developers.deepgram.com/docs/voice-agent-conversation-text)
* [Deepgram: Function Call Request](https://developers.deepgram.com/docs/voice-agent-function-call-request)
* [Deepgram: Speculative replies and turn confirmation](https://developers.deepgram.com/docs/voice-agent-speculative-replies)
* [Deepgram: Session observability](https://developers.deepgram.com/docs/voice-agent-observability)

## Why there is no OpenTelemetry section

The Voice Agent API is a hosted service. It does not emit OpenTelemetry spans to your application, and it has no tracing setting to export them. The WebSocket messages are the only record of the conversation, which is why Deepgram's own [session observability guide](https://developers.deepgram.com/docs/voice-agent-observability) recommends logging them from your client.

If you build the agent with Pipecat or LiveKit Agents and use Deepgram only for speech-to-text and text-to-speech, use the [Pipecat](https://docs.agnost.ai/pipecat.md) or [LiveKit Agents](https://docs.agnost.ai/livekit.md) OpenTelemetry guides instead.

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review complete Deepgram voice sessions.
* [Events](https://docs.agnost.ai/using-events.md): inspect each user turn and agent reply.
* [Patterns](https://docs.agnost.ai/using-patterns.md): understand why users talked to the agent.


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