# Chat API (/docs/chat-api)

> Put your agent in your own chat window, on any website or app, with the Chat Sessions API. Test it first with scripted tools, from your code or from an AI tool over MCP.

The Chat API lets your agent answer text messages anywhere you can show text:
your own chat window on a website, a mobile app, a support portal, or a
backend that relays messages from another system. You build the chat window;
OmniDimension runs the agent.

Each conversation is a **chat session**. Your server opens a session, sends
each customer message, shows the agent's reply, and ends the session when the
conversation is over. The agent uses everything you set up for it: its prompt,
knowledge base, tools and post-call actions.

## Pick the right option [#pick-the-right-option]

| You want | Use |
|---|---|
| A chat bubble on your website with no code | [Web chat widget](/docs/dashboard-guides/web-chat-widget) |
| The agent in **your own** chat window or app | The Chat API in `live` mode (this page) |
| To check an agent before customers see it, with tools you control | The Chat API in `test` mode ([Test your agent](#test-your-agent-before-you-go-live)) |
| An AI tool such as Claude or Cursor to test and fix the agent for you | The same API over [MCP](#test-from-an-ai-tool-over-mcp) |
| Voice in your own app | [Web call sessions](/docs/api-reference/sessions/createSession) |

## How it works [#how-it-works]

<svg viewBox="0 45 820 250" role="img" aria-label="The customer types in your chat window. Your chat window sends the message to your server. Your server, which holds the API key, calls the OmniDimension Chat API, which runs the agent and its tools and returns the reply. Your server passes the reply back to the chat window. When the chat ends, OmniDimension runs post-call analysis and sends the results to your webhook, email or connected apps." style={{ width: '100%', height: 'auto', maxWidth: '760px', display: 'block', margin: '0 auto' }}>
  <defs>
    <marker id="ca-arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
      <path d="M0,0 L10,5 L0,10 z" fill="currentColor" />
    </marker>
  </defs>

  <rect x="20" y="60" width="190" height="90" rx="10" fill="currentColor" fillOpacity="0.04" stroke="currentColor" strokeOpacity="0.35" strokeWidth="1.5" />
  <rect x="315" y="60" width="190" height="90" rx="10" fill="currentColor" fillOpacity="0.04" stroke="currentColor" strokeOpacity="0.35" strokeWidth="1.5" />
  <rect x="610" y="60" width="190" height="90" rx="10" fill="currentColor" fillOpacity="0.04" stroke="currentColor" strokeOpacity="0.35" strokeWidth="1.5" />
  <rect x="610" y="210" width="190" height="72" rx="10" fill="currentColor" fillOpacity="0.04" stroke="currentColor" strokeOpacity="0.35" strokeWidth="1.5" strokeDasharray="4 4" />

  <text x="115" y="98" textAnchor="middle" fill="currentColor" fontSize="15" fontWeight="600">Your chat window</text>
  <text x="115" y="120" textAnchor="middle" fill="currentColor" fillOpacity="0.7" fontSize="12">website or app</text>

  <text x="410" y="98" textAnchor="middle" fill="currentColor" fontSize="15" fontWeight="600">Your server</text>
  <text x="410" y="120" textAnchor="middle" fill="currentColor" fillOpacity="0.7" fontSize="12">holds the API key</text>

  <text x="705" y="98" textAnchor="middle" fill="currentColor" fontSize="15" fontWeight="600">Chat API</text>
  <text x="705" y="120" textAnchor="middle" fill="currentColor" fillOpacity="0.7" fontSize="12">runs the agent and its tools</text>

  <text x="705" y="242" textAnchor="middle" fill="currentColor" fontSize="14" fontWeight="600">Post-call actions</text>
  <text x="705" y="262" textAnchor="middle" fill="currentColor" fillOpacity="0.7" fontSize="11">webhook · email · CRM · Sheets</text>

  <line x1="210" y1="92" x2="313" y2="92" stroke="currentColor" strokeWidth="1.5" markerEnd="url(#ca-arrow)" />
  <text x="262" y="82" textAnchor="middle" fill="currentColor" fillOpacity="0.8" fontSize="11">message</text>
  <line x1="313" y1="124" x2="212" y2="124" stroke="currentColor" strokeWidth="1.5" markerEnd="url(#ca-arrow)" />
  <text x="262" y="142" textAnchor="middle" fill="currentColor" fillOpacity="0.8" fontSize="11">reply</text>

  <line x1="505" y1="92" x2="608" y2="92" stroke="currentColor" strokeWidth="1.5" markerEnd="url(#ca-arrow)" />
  <text x="557" y="82" textAnchor="middle" fill="currentColor" fillOpacity="0.8" fontSize="11">API key + message</text>
  <line x1="608" y1="124" x2="507" y2="124" stroke="currentColor" strokeWidth="1.5" markerEnd="url(#ca-arrow)" />
  <text x="557" y="142" textAnchor="middle" fill="currentColor" fillOpacity="0.8" fontSize="11">reply + tool calls</text>

  <line x1="705" y1="150" x2="705" y2="208" stroke="currentColor" strokeWidth="1.5" markerEnd="url(#ca-arrow)" />
  <text x="713" y="184" textAnchor="start" fill="currentColor" fillOpacity="0.8" fontSize="11">after the chat ends</text>
</svg>

Call the Chat API from your server, never from the browser or the app. Your
API key controls your whole account; anyone who sees it can use it. Your chat
window talks to your own server, and only your server talks to OmniDimension.

## Before you start [#before-you-start]

- An agent you have **published**. A live chat answers with the published
  version, the same one your phone calls use. See
  [Agent versioning and publishing](/docs/dashboard-guides/agent-versioning-and-publishing).
- Your API key, kept on your server. See [Authentication](/docs/get-started/authentication).
- Balance in your account. Each agent reply is charged; see [Cost](#cost).

All requests go to `https://omnidim.io/api/v1` with the header
`Authorization: Bearer YOUR_API_KEY`.

## Build a live chat [#build-a-live-chat]

### Open a session when the customer starts chatting [#open-a-session-when-the-customer-starts-chatting]

Call [Create chat session](/docs/api-reference/chat-sessions/createChatSession)
with your agent's id and `"mode": "live"`. The reply is the agent's greeting:
show it as the first message in your chat window. Keep the `session_id` for
this customer's conversation.

```bash
curl -X POST https://omnidim.io/api/v1/chat/sessions/create \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": 158910,
    "mode": "live",
    "custom_variables": { "name": "Ada", "plan": "Gold" }
  }'
```

```json
{
  "session_id": 4521,
  "reply": "Hi Ada, this is Sam from Demo Dental. How can I help?",
  "tool_calls": [],
  "should_end": false
}
```

`custom_variables` fills the agent's
[dynamic variables](/docs/dashboard-guides/dynamic-variables), as on a call:
pass what you already know about the customer so the agent does not have to ask.

### Send each customer message [#send-each-customer-message]

Call [Send chat message](/docs/api-reference/chat-sessions/sendChatMessage)
with the customer's text. The response holds the agent's reply, which you
show in the chat window.

```bash
curl -X POST https://omnidim.io/api/v1/chat/sessions/4521/message \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "message": "Can I book a cleaning for tomorrow at 10?" }'
```

```json
{
  "session_id": 4521,
  "reply": "Done, you are booked for a cleaning tomorrow at 10 am.",
  "tool_calls": [
    {
      "function_name": "book_appointment",
      "args": "{\"date\": \"2026-12-01\", \"time\": \"10:00\"}",
      "result": "{\"status\": \"ok\", \"data\": {\"booking_id\": \"B-1042\"}}",
      "success": true
    }
  ],
  "should_end": false
}
```

- **One message at a time.** Wait for the reply before you send the next
  message in the same session. A reply usually takes a second or two, longer
  when the agent calls a tool; show a typing indicator meanwhile.
- **`tool_calls`** lists the tools the agent ran on this turn, with their
  arguments and results. Your chat window can ignore it, or use it, for example
  to show a booking card.
- **`status`** turns `ended` when the agent closes the chat itself (see below).
  Show the reply, then close your chat window. You do not need to call End
  chat session.

#### When the agent ends or transfers the chat [#when-the-agent-ends-or-transfers-the-chat]

The agent closes a chat the way it ends a call, following its own
[call settings](/docs/dashboard-guides/call-settings):

- **End call:** when the conversation is done, the agent says goodbye and runs
  `end_call`.
- **Transfer:** when the customer must go to a person, the agent runs
  `transfer_call` and tells the customer the number they are being transferred
  to. Nothing is dialed: the response gives you the number in
  `transferred_to`, so you can show it, open a phone link, or hand the chat to
  your team.

That turn's response says the chat is over and carries the whole conversation,
so you can act on it right away:

```json
{
  "session_id": 4521,
  "reply": "Sure, I am transferring you to +15551234567 now.",
  "tool_calls": [{ "function_name": "transfer_call", "args": "{\"transfer_option_index\": 0}", "success": true }],
  "should_end": true,
  "status": "ended",
  "ended_by": "transfer",
  "transferred_to": "+15551234567",
  "transcript": [
    { "role": "agent", "text": "Hi, this is Sam from Demo Dental. How can I help?" },
    { "role": "customer", "text": "I need to talk to a person." },
    { "role": "agent", "text": "Sure, I am transferring you to +15551234567 now." }
  ]
}
```

`ended_by` is `agent` (end call), `transfer`, `client` (you called End chat
session) or `idle` (30 minutes with no message).

### End the session [#end-the-session]

Call [End chat session](/docs/api-reference/chat-sessions/endChatSession)
when the customer closes the chat or your own timeout passes. This saves the
chat, runs post-call analysis and the agent's post-call actions, and returns
the transcript. When the agent ended the chat itself, it is already saved;
calling End chat session then only reports how it ended.

```bash
curl -X POST https://omnidim.io/api/v1/chat/sessions/4521/end \
  -H "Authorization: Bearer YOUR_API_KEY"
```

If you never call it, for example because the customer closed the tab, the
session ends on its own after **30 minutes** with no message. After a session
ends, a new message returns `409 session_ended`: open a new session.

### Get the results [#get-the-results]

Once the chat ends, the agent's post-call actions run as they do after a call:
your [webhook](/docs/api-reference/webhook-payload), email report, CRM,
Google Sheets or workflow receives the transcript, summary and extracted
variables. The chat is also in **Call Logs** on the `API-Chat` channel.

To read the record from your code instead, call
[Get chat session](/docs/api-reference/chat-sessions/getChatSession) until
`analysis_status` is `done` (usually a few seconds after the end). `call_log`
holds the record in the same shape as [Get call log](/docs/api-reference/calls/getCallLog).

## A complete server [#a-complete-server]

This server gives your chat window three routes of its own and keeps the API
key out of the browser. It is a starting point: add your own login, rate
limits and storage.

```js tab="Node.js (Express)"
import express from 'express';

const API = 'https://omnidim.io/api/v1';
const KEY = process.env.OMNIDIM_API_KEY; // never sent to the browser
const AGENT_ID = 158910;

async function omni(path, body) {
  const res = await fetch(`${API}${path}`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify(body ?? {}),
  });
  const data = await res.json();
  if (!res.ok) throw Object.assign(new Error(data.error_description), { status: res.status, code: data.error });
  return data;
}

const app = express();
app.use(express.json());

// The chat window opens: start a session and return the greeting.
app.post('/chat/start', async (req, res) => {
  const turn = await omni('/chat/sessions/create', {
    agent_id: AGENT_ID,
    mode: 'live',
    custom_variables: { name: req.body.name },
  });
  res.json(turn); // { session_id, reply, tool_calls, should_end }
});

// The customer sends a message.
app.post('/chat/:id/message', async (req, res) => {
  try {
    const turn = await omni(`/chat/sessions/${req.params.id}/message`, { message: req.body.message });
    res.json(turn); // turn.status === 'ended': the agent closed the chat (see transferred_to)
  } catch (e) {
    res.status(e.status ?? 500).json({ error: e.code });
  }
});

// The customer closes the chat.
app.post('/chat/:id/end', async (req, res) => {
  await omni(`/chat/sessions/${req.params.id}/end`);
  res.json({ ok: true });
});

app.listen(3000);
```

```python tab="Python (FastAPI)"
import os

import httpx
from fastapi import FastAPI, HTTPException

API = "https://omnidim.io/api/v1"
KEY = os.environ["OMNIDIM_API_KEY"]  # never sent to the browser
AGENT_ID = 158910

app = FastAPI()
client = httpx.AsyncClient(timeout=90, headers={"Authorization": f"Bearer {KEY}"})

async def omni(path: str, body: dict | None = None) -> dict:
    res = await client.post(f"{API}{path}", json=body or {})
    data = res.json()
    if res.is_error:
        raise HTTPException(res.status_code, data.get("error"))
    return data

@app.post("/chat/start")
async def start(body: dict):
    # The chat window opens: start a session and return the greeting.
    return await omni("/chat/sessions/create", {
        "agent_id": AGENT_ID, "mode": "live",
        "custom_variables": {"name": body.get("name")},
    })

@app.post("/chat/{session_id}/message")
async def message(session_id: int, body: dict):
    # turn["status"] == "ended": the agent closed the chat (see transferred_to)
    return await omni(f"/chat/sessions/{session_id}/message", {"message": body["message"]})

@app.post("/chat/{session_id}/end")
async def end(session_id: int):
    await omni(f"/chat/sessions/{session_id}/end")
    return {"ok": True}
```

Your chat window then calls only your server:

```js title="In the browser"
const { session_id, reply } = await post('/chat/start', { name: 'Ada' });
showAgentMessage(reply);

async function onCustomerMessage(text) {
  showCustomerMessage(text);
  const turn = await post(`/chat/${session_id}/message`, { message: text });
  showAgentMessage(turn.reply);
  if (turn.status === 'ended') closeChat(turn.transferred_to); // e.g. show "Call us at ..."
}

window.addEventListener('pagehide', () => navigator.sendBeacon(`/chat/${session_id}/end`));

async function post(url, body) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body ?? {}),
  });
  return res.json();
}
```

## Test your agent before you go live [#test-your-agent-before-you-go-live]

A `test` session runs the same agent with three differences, so you can check
it without touching real systems:

- It talks to your **latest edits**, before you publish them.
- The agent's **tools never run**. Each tool returns what you set in
  `tool_results`, so you can play out a tool that succeeds, fails or times out.
  A tool you leave out returns `{"status": "ok", "data": {}}`. The end call
  and transfer tools still run, so you see when the agent would hang up or
  transfer, and to which number.
- Post-call analysis extracts the variables, but **nothing is delivered**: no
  webhook, email or CRM update. The chat is listed on the `MCP-Test` channel.

```bash
curl -X POST https://omnidim.io/api/v1/chat/sessions/create \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": 158910,
    "mode": "test",
    "tool_results": {
      "book_appointment": { "status": "error", "error": "calendar_unavailable" }
    }
  }'
```

The response to a test session's creation also has a `briefing`, so you script
the right tools and fill the right variables:

```json
"briefing": {
  "agent_version": "draft",
  "tools": [
    { "name": "book_appointment", "description": "Book a visit…", "parameters": { "type": "object", "properties": { "date": { "type": "string" } } }, "runs_in_test": false },
    { "name": "end_call", "description": "End this chat. Use it when: …", "parameters": {}, "runs_in_test": true }
  ],
  "dynamic_variables": ["name", "plan"],
  "missing_variables": ["plan"]
}
```

Key `tool_results` by the tool names listed there. Pass every name in
`missing_variables` in `custom_variables`, or the agent talks with blanks.

Then send messages as in a live chat. To change what a tool returns for one
message only, add `tool_results` to that message:

```bash
curl -X POST https://omnidim.io/api/v1/chat/sessions/4522/message \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Try 11 instead, please.",
    "tool_results": { "book_appointment": { "status": "ok", "data": { "booking_id": "B-1" } } }
  }'
```

End the session, then read the record with
[Get chat session](/docs/api-reference/chat-sessions/getChatSession): check the
transcript, the tools the agent called with their arguments (`tool_calls` on
each turn), and whether `extracted_variables` hold what you expect.

In a test chat, each entry in `tool_calls` has a `source`: `scripted` (your
`tool_results`), `default` (you scripted nothing, so it got an empty success)
or `real` (the end call and transfer tools). If the agent states details after a
`default` result, such as an order status it was never given, it is making them
up.

A chat test checks what the agent says and does. It cannot show how it sounds
on a call: speech recognition mistakes, interruptions, silence, latency and
pronunciation only show on a real call. Voice prompts may also write numbers as
words, which reads oddly in chat and is right on a call.

Good test chats play **one customer goal each**: a normal booking, a tool that
fails, a customer who goes off topic, a question the agent must refuse. Judge
the agent on what it did (the tools it called and the final record), not only
on how it sounded.

## Test from an AI tool over MCP [#test-from-an-ai-tool-over-mcp]

The four chat session endpoints are also tools in the
[OmniDimension MCP server](/docs/mcp): `createChatSession`, `sendChatMessage`,
`endChatSession` and `getChatSession`. Connect Claude, ChatGPT, Cursor or
another MCP client, then ask it to test your agent in plain words:

```text
Test my agent "Demo Dental Receptionist" in test mode. Play four customers:
a normal cleaning booking, one where book_appointment fails with
calendar_unavailable, one who asks for a diagnosis, and one who goes off topic.
Read each chat's record and tell me where the agent went wrong.
```

The `omnidim-test-agent` playbook (in
[OmniDimension skills](https://github.com/Omnidim/skills), and served by the MCP
server) tells the AI tool how to do this well. It writes the scenarios from the
agent's own tools, plays the customer, scripts the tool results and reads back
each record. When the agent ends or transfers a chat,
the reply says so (`status: ended`, `ended_by`, `transferred_to`) with the
whole transcript, so the AI tool knows the conversation is over and can judge
whether the agent ended at the right moment. It changes the agent only after you
approve each fix, saves a version first, and never publishes: you publish when
you are satisfied. It can then suggest prompt changes, apply
them with `updateAgent` once you agree, and run the same chats again. Save a
version first ([Agent versioning](/docs/dashboard-guides/agent-versioning-and-publishing))
so you can go back.

## Cost [#cost]

Each agent reply is charged as a chat message, **$0.006 by default**, the
greeting included. Customer messages are free. A chat of ten agent replies
costs $0.06. Each reply is paid from your balance just before the agent
answers, and refunded if the agent fails to answer, so your balance always shows
what your chats have used. It is listed on your usage statement under **Chat
messages**. Live and test chats cost the same.

If your balance cannot pay for one more reply, Create chat session and Send
chat message return `402 insufficient_balance`. Show the customer a fallback,
such as a contact form, and top up.

## Errors [#errors]

| Status | `error` | What to do |
|---|---|---|
| 400 | `unsupported_mode` | Use `live` or `test`. |
| 400 | `invalid_request` | Check the body: an integer `agent_id`, a non-empty `message`, and `tool_results` only in a test chat. |
| 401 | | Check the API key. |
| 402 | `insufficient_balance` | Top up your balance. |
| 404 | `agent_not_found` / `session_not_found` | The agent or session is not in your account. |
| 409 | `session_ended` | Open a new session. `ended_by` says why it ended. |
| 502 | `agent_unavailable` | The agent did not answer in time. Send the same message again. |

## Good to know [#good-to-know]

- **Text only.** For voice in your own app, use
  [web call sessions](/docs/api-reference/sessions/createSession).
- **Every reply waits for the agent.** The response comes when the reply is
  ready; allow up to 60 seconds before your server gives up.
- **One session per conversation.** Open a new one for each customer or
  each new conversation; a session cannot be reopened. A session ends after
  100 agent replies (`ended_by: turn_limit`).
- **Real tools in live chats.** A live chat books, updates and sends exactly
  as a call would. Use a test chat while you are building.
- **A transfer connects nobody.** It ends the chat and gives you the number;
  routing the customer is up to your chat window.

## API reference [#api-reference]

  - [Create chat session](/docs/api-reference/chat-sessions/createChatSession): Open a live or test session and get the greeting.
  - [Send chat message](/docs/api-reference/chat-sessions/sendChatMessage): Send the customer's text and get the agent's reply and tool calls.
  - [End chat session](/docs/api-reference/chat-sessions/endChatSession): Save the chat and run post-call analysis and actions.
  - [Get chat session](/docs/api-reference/chat-sessions/getChatSession): Read the session's state and its full record.