Getting Started
REST API Integration
Chat API reference: request and response fields, file uploads, conversation history, streaming, and errors.
Overview
Use the Chat API to send messages and read conversation history. Each API channel key selects an agent and grants access to that channel's conversations.
For the public API, see API overview. Conversation export uses a platform API key and covers customer conversations across channels. Health is public and needs no key. The channel-key instructions below apply to the Chat API endpoints in this guide.
https://api.mu.chat/v2Quick Start
In the dashboard, select your agent, open Deploy → API → Setup (or Manage), and create or copy its API key.

Keep the key on your server. Organization API keys and the widget's websiteToken do not authenticate these endpoints.
export MUCHAT_API_KEY='YOUR_API_CHANNEL_KEY'curl --request POST 'https://api.mu.chat/v2/chat' \
--header "Authorization: Bearer $MUCHAT_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"query": "Hello! How can you help me?",
"external_message_id": "message-001",
"stream": false
}'{
"data": {
"message": {
"id": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"role": "assistant",
"parts": [
{
"id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
"type": "text",
"text": "Hello! How can I help you today?"
}
]
},
"metadata": {
"conversation_id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"user_message_id": "d4e5f6a7-b8c9-4d0e-8f1a-2b3c4d5e6f7a",
"external_message_id": "message-001",
"contact_id": "e5f6a7b8-c9d0-4e1f-8a2b-3c4d5e6f7a8b",
"finish_reason": "completed",
"conversation_status": "open",
"bot_active": true,
"handoff_status": "not_requested",
"usage": { "credits": 1 }
}
}
}For the next message, include the returned data.metadata.conversation_id and a new external_message_id. Wait for the previous request to finish; history is stored automatically.
| Header | Value |
|---|---|
Authorization | Required: Bearer YOUR_API_CHANNEL_KEY. |
Content-Type | application/json for chat; let your client set multipart headers for uploads. |
Last-Event-ID | Optional: last received SSE id, when resuming the same request. |
Key API Endpoints
| Method | Path | Purpose |
|---|---|---|
POST | /v2/chat | Send a message; receive JSON or SSE. |
POST | /v2/chat/uploads | Upload a file. |
GET | /v2/chat/conversations | List conversations. |
GET | /v2/chat/conversations/{conversation_id} | Read a conversation's current state. |
GET | /v2/chat/conversations/{conversation_id}/messages | Read public messages. |
Send a Message: Request Fields
Send a JSON body to POST /v2/chat. Fields are optional unless marked required. Extra fields are rejected.
| Field | Data type | Default | Purpose |
|---|---|---|---|
query | Text | "" | The user's message. Without a file, text is required and cannot contain only spaces. |
attachments | List of file objects | [] | Uploaded files in display order. Send up to 5 files with different IDs. |
attachments[].blob_id | Positive integer | None; required | The ID you received when uploading the file. |
conversation_id | Text (UUID) | null | Send the ID from the previous response to continue that conversation. Leave it out to start a new one. |
external_message_id | Text | null | Your system's message ID. It must be unique within the channel, nonblank, and at most 255 characters. The server creates one if you leave it out. |
contact | JSON object | null | User details, such as name and email. Leave it out to keep the current conversation's contact. |
system_prompt | Text | null | Instructions for this message. If omitted or blank, the channel's instructions apply, falling back to the agent's instructions. |
knowledge_base_ids | List of IDs | null | Knowledge bases to search for this reply. Select up to 100 active bases assigned to the agent. Leave it out to use all, or send [] to disable search. |
stream | true or false | false | With true, receive the reply as it is generated. With false, receive the complete reply at once. |
For fields with a null default, sending null has the same effect as leaving the field out.
system_prompt and knowledge_base_ids apply only to this request; saved agent settings stay unchanged.
Contact Fields
All contact fields are optional. Leave a field out to keep its current value. Send null to clear a text field, except identifier. Leading and trailing spaces are removed, and blank text is treated as null. Verified information or operator edits may be protected from API changes.
| Field | Data type | Limit | Purpose |
|---|---|---|---|
contact.identifier | Text | Up to 255 characters | The signed-in user's stable ID in your system, such as "customer-42". It cannot change during a conversation. |
contact.name | Text | Up to 255 characters | The name displayed for the user. |
contact.first_name | Text | Up to 255 characters | Given name. |
contact.last_name | Text | Up to 255 characters | Family name. |
contact.email | Text | Valid email | The user's email address. Stored in lowercase. |
contact.phone_number | Text | Up to 64 characters | A valid phone number, stored in E.164 format. Numbers without a country code are treated as Iranian. |
contact.locale | Text | Up to 32 characters | Profile language, such as "fa". This does not set the reply language. |
contact.custom_attributes | JSON object | — | Extra data, such as {"plan":"premium"}. Only supplied keys change. Send null for a key to clear its value. Defaults to {}. |
contact.identifier identifies the same user. To continue the same conversation, send conversation_id.
Send a Message: Response Fields
JSON success returns 200 with data.message and data.metadata. The paths below are inside data.
| Field | Data type | Meaning |
|---|---|---|
message | JSON object or null | Reply, or null when no AI reply was generated. |
message.id | Text (UUID) | MuChat's reply message ID. |
message.role | Text | assistant for the AI; history also includes user and operator. |
message.parts | List of objects | Text and files in display order. |
metadata.conversation_id | Text (UUID) | Conversation ID for subsequent messages. |
metadata.user_message_id | Text (UUID) | MuChat's ID for the incoming message. |
metadata.external_message_id | Text | Your supplied message ID, or the generated one. |
metadata.contact_id | Text (UUID) | MuChat's contact ID; distinct from your contact.identifier. |
metadata.finish_reason | Text | completed: finished; suppressed: no AI reply; failed: failed; cancelled: interrupted. |
metadata.conversation_status | Text | open: active; pending: awaiting handling; snoozed: postponed; resolved: closed. |
metadata.bot_active | true or false | Whether the bot is enabled for this conversation. |
metadata.handoff_status | Text | not_requested: no handoff; pending: awaiting an operator; operator_owned: assigned. |
metadata.usage.credits | Integer | Credits used by this reply. Reports 0 if no reply is generated or generation fails. |
If generation fails or is cancelled, the JSON response returns 503 with the result in data. A retry returns information from when the original request ended. Fetch conversation details for the current state.
Message Parts
Each text part has:
| Field | Data type | Meaning |
|---|---|---|
id | Text (UUID) | Content-part ID. |
type | Text | "text". |
text | Text | Text to display. |
| Field | Data type | Meaning |
|---|---|---|
id | Text (UUID) | Media-part ID. |
client_id | Text | An ID for finding this part in your app. Currently the same as id. |
position | Integer | This part's order within the message. |
type | Text | attachment or voice. |
updated_at | Date and time | Last update, in ISO 8601 format. |
content_attributes | JSON object | File details below. |
content_attributes.schema_version | Integer | Format version; currently 1. |
content_attributes.kind | Text | image, file, or voice. |
content_attributes.filename | Text | Display filename. |
content_attributes.status | Text | pending, processing, ready, failed, or rejected: processing state. |
content_attributes.content_type | Text or null | MIME type, e.g. image/png. |
content_attributes.byte_size | Integer or null | File size in bytes. |
content_attributes.width | Integer or null | Image width in pixels. |
content_attributes.height | Integer or null | Image height in pixels. |
content_attributes.duration_seconds | Number or null | Media duration in seconds. |
content_attributes.error_code | Text or null | Media-processing error code. |
content_attributes.transcription | JSON object or null | Voice-to-text result, if available. |
content_attributes.transcription.status | Text | pending, completed, empty, failed, or skipped: transcription outcome. |
content_attributes.transcription.text | Text or null | Completed transcript. |
content_attributes.delivery_status | Text or null | Media-delivery state, if available. |
content_attributes.download_url | Text or null | Temporary download link. |
content_attributes.expires_in | Integer or null | How long the link stays valid, in seconds. Currently 300. Fetch message history again for a fresh link. |
Upload Files
Send the file in the file field using multipart/form-data. A successful 201 response returns the file ID in blob_id.
curl 'https://api.mu.chat/v2/chat/uploads' \
--header "Authorization: Bearer $MUCHAT_API_KEY" \
--form 'file=@./screenshot.png;type=image/png'If the response is {"blob_id":187}, send it in a chat request:
{
"query": "What is shown in this image?",
"external_message_id": "message-002",
"attachments": [{ "blob_id": 187 }]
}- Attach the upload within 24 hours, in the same channel, to one new message. Retries of that message can reuse it.
- Maximum 5 files per message. Upload limit: 30 per 15 minutes; size depends on the plan and server cap (default 100 MiB).
- Supported vision models read static images. PDFs and other files are stored without reading their contents; audio uploads are not transcribed.
Chat API Streaming
Send stream: true to receive the reply as it is generated, using text/event-stream. The event name is in event, and its JSON is in data. The data.type matches the event name. Save received id values to resume after a disconnect. Ignore heartbeat comments.
| Event | Fields and purpose |
|---|---|
CUSTOM | Confirms the message was received. name is "muchat.api.message.accepted.v1", and value contains the message's IDs. |
RUN_STARTED | Generation has started. threadId identifies the thread, and runId identifies this generation. |
TEXT_MESSAGE_START | Reply text is starting. messageId identifies the message, and role is assistant. When present, partId identifies the text part, and position gives its order. |
TEXT_MESSAGE_CONTENT | New text is in delta. Add it to messageId's text, using partId to choose the part when present. |
TEXT_MESSAGE_END | Text for this messageId has ended, or for its partId when present. |
RUN_ERROR | code identifies the error; message explains it. |
RUN_FINISHED | The reply has ended. threadId and runId identify the thread and generation. Use the final response in result for display. |
The value contains conversation_id, user_message_id, external_message_id, contact_id, and run_id. All are UUIDs except your external_message_id. The run_id can be null. In that case, the final event's runId is user_message_id. Use conversation_id for the next message.
After a disconnect, retry the same request with the last SSE id in the Last-Event-ID header. Text chunks may not be sent again, so use the final result. Without that result, the response is incomplete. A stream failure may return result.status as "failed" and the message's IDs in result.metadata, without result.data.
Run streamer.mjs with Node.js 18+, or streamer.py with Python and requests installed. Both use MUCHAT_API_KEY.
import { randomUUID } from 'node:crypto';
async function readAgentReply() {
const body = {
query: 'Hello! How can you help me?',
external_message_id: randomUUID(),
stream: true,
};
const response = await fetch('https://api.mu.chat/v2/chat', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MUCHAT_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if (!response.ok) {
const problem = await response.json();
throw new Error(`${problem.code}: ${problem.detail}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let result;
let streamError;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.startsWith('data:')) continue;
const event = JSON.parse(line.slice(5).trim());
if (event.type === 'TEXT_MESSAGE_CONTENT') {
process.stdout.write(event.delta);
} else if (event.type === 'RUN_ERROR') {
streamError = event.message;
} else if (event.type === 'RUN_FINISHED') {
result = event.result;
}
}
}
if (!result?.data) {
throw new Error(streamError || 'Stream ended before the final result');
}
console.log('\nFinal result:', JSON.stringify(result, null, 2));
if (['failed', 'cancelled'].includes(result.data.metadata.finish_reason)) {
throw new Error(streamError || 'The response could not be completed');
}
}
readAgentReply().catch(error => {
console.error('Error:', error.message);
process.exitCode = 1;
});import json
import os
import sys
from uuid import uuid4
import requests
def read_agent_reply():
body = {
'query': 'Hello! How can you help me?',
'external_message_id': str(uuid4()),
'stream': True,
}
headers = {
'Authorization': f"Bearer {os.environ['MUCHAT_API_KEY']}",
'Content-Type': 'application/json',
}
with requests.post(
'https://api.mu.chat/v2/chat',
json=body, headers=headers, stream=True, timeout=(10, 210),
) as response:
if not response.ok:
problem = response.json()
raise RuntimeError(f"{problem['code']}: {problem['detail']}")
response.encoding = 'utf-8'
result = None
stream_error = None
for line in response.iter_lines(decode_unicode=True):
if not line or not line.startswith('data:'):
continue
event = json.loads(line[5:].strip())
if event['type'] == 'TEXT_MESSAGE_CONTENT':
print(event['delta'], end='', flush=True)
elif event['type'] == 'RUN_ERROR':
stream_error = event['message']
elif event['type'] == 'RUN_FINISHED':
result = event['result']
if not result or 'data' not in result:
raise RuntimeError(stream_error or 'Stream ended before the final result')
print('\nFinal result:', json.dumps(result, ensure_ascii=False, indent=2))
if result['data']['metadata']['finish_reason'] in ('failed', 'cancelled'):
raise RuntimeError(stream_error or 'The response could not be completed')
try:
read_agent_reply()
except (requests.RequestException, ValueError, RuntimeError) as error:
print('Error:', error, file=sys.stderr)
sys.exit(1)Conversation History
GET /v2/chat/conversations returns data[], newest activity first. GET /v2/chat/conversations/{conversation_id} returns one data object with the same fields. conversation_id is a required UUID in the path.
| Conversation field | Data type | Meaning |
|---|---|---|
id | Text (UUID) | Conversation ID. |
contact_id | Text (UUID) | MuChat's contact ID. |
contact_identifier | Text or null | Your user's identifier. |
created_at | Date and time | Creation time, in ISO 8601 format. |
last_activity_at | Date and time | Most recent activity. |
conversation_status | Text | Current status, as defined in the chat response. |
bot_active | true or false | Whether the bot is currently enabled. |
handoff_status | Text | Current operator handoff state. |
GET /v2/chat/conversations/{conversation_id}/messages returns public messages in data[], oldest to newest within each page. Messages use id, role, and parts from the response reference, plus ISO 8601 created_at. Private notes and unfinished replies are excluded.
| Query parameter | Applies to | Purpose |
|---|---|---|
contact_identifier | Conversations | Send the user's contact.identifier to get their conversations. |
cursor | Conversations | Send pagination.next_cursor from the previous response to get the next page. |
before | Messages | Send before_cursor to get older messages. |
after | Messages | Send after_cursor to get newer messages. Do not combine with before. |
limit | Both | Number of results per page, from 1–100. Defaults to 50. |
These parameters are optional. Without before or after, you get the latest messages. Use pagination values only with the same channel, conversation, and filters. Your server must give each user access only to their own history.
pagination field | Data type | Meaning |
|---|---|---|
has_more | true or false | If true, more results are available in the selected direction. |
next_cursor | Text or null | Value for the next page. Send it in the same cursor, before, or after parameter. The default direction for messages is before. |
before_cursor | Text or null | Send in before to get messages older than this page. Only included in message lists. |
after_cursor | Text or null | Send in after to get messages newer than this page. Only included in message lists. Keep your previous value when a page is empty. |
Error Handling
HTTP errors use application/problem+json:
{
"type": "about:blank",
"title": "Invalid API Key",
"status": 401,
"detail": "The provided API key is invalid or expired.",
"instance": "/v2/chat",
"code": "INVALID_API_KEY",
"trace_id": "f6a7b8c9-d0e1-4f2a-8b3c-4d5e6f7a8b9c"
}| Field | Data type | Meaning |
|---|---|---|
type | Text | Problem type; currently about:blank. |
title | Text | Short error title. |
status | Integer | HTTP status code. |
detail | Text | Error explanation. |
instance | Text | Request path. |
code | Text | Error identifier for program logic. |
trace_id | Text | Support tracing ID; also in X-Request-ID. |
data | JSON object (optional) | Saved message and metadata for generation failures. |
errors | List of objects (optional) | Field errors for VALIDATION_ERROR. |
errors[].loc | List | Invalid field's location, e.g. ["body","contact","email"]. |
errors[].msg | Text | What is wrong with the field. |
errors[].type | Text | The kind of problem with the field. |
| HTTP / code | Action |
|---|---|
401 INVALID_API_KEY | Check the API channel key. |
403 API_CHANNEL_INACTIVE / API_ACCESS_NOT_AVAILABLE | Check channel activation and plan access. |
403 API_CONTACT_UNAVAILABLE | Check whether the contact is blocked. |
403 CHAT_FILE_ACCESS_DENIED | Use an unused upload from this channel. |
404 CONVERSATION_NOT_FOUND | Check the conversation ID and channel. |
409 API_MESSAGE_CONFLICT | Retry the original body, or use a new message ID. |
409 API_CONVERSATION_BUSY / API_CONVERSATION_CLOSED | Wait for the reply, or start a new conversation. |
409 API_CONTACT_MISMATCH | Keep the conversation's original identity. |
409 CHAT_UPLOAD_NOT_READY / 410 CHAT_UPLOAD_EXPIRED | Complete or repeat the upload. |
413 CHAT_FILE_TOO_LARGE | Reduce file size. |
422 VALIDATION_ERROR / API_CURSOR_INVALID | Check fields, UUIDs, and cursors. |
422 API_KNOWLEDGE_UNAVAILABLE | Use active knowledge assigned to this agent. |
422 CHAT_FILE_INVALID / CHAT_MEDIA_PROCESSING_FAILED | Check the file; retry processing if needed. |
422 CHAT_ATTACHMENT_LIMIT_EXCEEDED | Send at most 5 files. |
429 MESSAGE_RATE_LIMIT_EXCEEDED | Wait for Retry-After when present; otherwise retry with a delay. |
503 API_GENERATION_FAILED | Read data.metadata.finish_reason; partial text may exist. |
For SSE, check RUN_ERROR and the final result: failed, cancelled, or missing result.data means failure even after HTTP 200.