Chat API: REST API and WebSocket integration for third-party applications
The Flametree Chat API enables third-party applications to integrate with Flametree AI agents using REST API calls and WebSocket connections. This comprehensive API allows you to create chat sessions, send messages, handle voice features, and manage conversation history.
Prerequisites
Before using the Chat API, ensure you have:
- Active Flametree account with configured AI agent
- Agent API token (found in agent's Advanced section)
- Agent ID (found in agent's Advanced section)
- Basic understanding of REST APIs and WebSocket connections
- Development environment capable of making HTTP requests
Key Concepts
| Term | Definition |
|---|---|
| Session | An object that represents metadata about the active chat with the agent (no message history) |
| Conversation | An object that wraps an active session plus the entire chat history. Conversations are returned in the array from the /conversations endpoint |
| Agent Route | Base URL for agent-specific APIs: https://portal.flametree.ai/chatbot/{agent_id} |
| Public Route | Base URL for public APIs: https://portal.flametree.ai |
Authentication and Getting Credentials
All REST API requests require an authorization header with your agent's API token:
Authorization: Bearer <token>
Getting Your Credentials
Follow these steps to obtain your authentication credentials
- Go to your Flametree portal and open your agent configuration
- Navigate to Advanced section
- Find the token field (hidden with asterisks)
- Click the Copy button to copy the token
To get your agent_id, in the same Advanced section, you'll find the agent_id field above the token field.
API Base URLs
| Context | Base URL | Reference |
|---|---|---|
| Agent-specific APIs | https://portal.flametree.ai/chatbot/{agent_id} | → referred to as {agentRoute} |
| Public (conversation) APIs | https://portal.flametree.ai | → referred to as {publicRoute} |
https://portal.example.com/chatbot/{'{agent_id}'}
Session Management
Sessions represent active chats with your AI agent without message history. Use these endpoints to manage session lifecycle:
Session Endpoints
| Method & Path | Purpose |
|---|---|
POST {agentRoute}/session | Start a new session |
GET {agentRoute}/session/{sessionId} | Get session metadata |
PUT {agentRoute}/session/{sessionId} | Update session metadata |
DELETE {agentRoute}/session/{sessionId} | Close the session |
POST {agentRoute}/session/{sessionId}/run_v2 | Send a message (optionally with file attachments) |
Sessions are closed automatically after the configured timeout.
Creating a New Session
Request Body:
{
"user_id": "d7915d1e-8aea-41d2-a331-87d7cc4875da",
"name": "John Smith",
"email": "john.smith@example.com",
"phone": "+1555123456",
"type": "web",
"args": [],
"kwargs": {
"user_profile_info":"Very important client"
},
"user_info": {
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"language": "en-US",
"screenWidth": 1920,
"screenHeight": 1080,
"platform": "Win32",
"isMobile": false
}
}
Response:
{
"session_id": "0685d2ec-14b8-7f0d-8000-b43afe3a64d1",
"session_type": "custom_stateful",
"mode": "REGULAR",
"conversation_id": null,
"ext_type": "web",
"user_id": "d7915d1e-8aea-41d2-a331-87d7cc4875da",
"name": "John Smith",
"email": "john.smith@example.com",
"phone": "+1555123456",
"channel_id": null,
"timeout": 259200,
"greeting_text": "I am Flame - your AI Support Assistant. \nI can help you with building AI agents, setting up outbound campaigns, configuring platform features, and navigating the dev tools.",
"inbound_phrase": null,
"start_phrase": null,
"language": "en",
"llm_backend": null,
"show_thoughts": false,
"conversation_result": null,
"operator_id": "user_12345",
"operator_name": "John Doe",
"env_info": {
"current_date": "2025-06-26 Thu",
"tenant_id": "00000000-0000-0000-0000-000000000000"
},
"kwargs": {
"tenant_id": "00000000-0000-0000-0000-000000000000"
},
"close_time": 1751196481.8386822,
"voice_name": null
}
Make sure:
- the
agent_idin the URL is correct - all required fields are provided in the request body
- the agent is active and properly configured
Sending Messages
Messages are sent using multipart/form-data format to support file attachments.
Request Format:
message(required): Text message contentattachments(optional): File attachments (multiple files allowed)
Example with JavaScript:
const formData = new FormData();
formData.append('message', 'Hello, I need help with my account');
// Optional: Add file attachments
if (attachments) {
attachments.forEach((file) => {
formData.append('attachments', file);
});
}
Response:
{
"response": "I'd be happy to help you with your account. What specific issue are you experiencing?",
"metadata": {
"mode": "REGULAR"
}
}
💡 Note: The
metadata.modefield indicates the session type:
REGULAR- Normal request/reply sessionCOPILOT- Session transferred to copilot modeOPERATOR- Session transferred to operator
If the request fails, verify that:
- the
messagefield is included - files are sent using
multipart/form-data
Closing Sessions
When closing a session, you can specify a completion status:
Available Session Status Values:
completed- Session completed successfullybusy- Customer or agent busynoanswer- No answer receivedcanceled- Session canceled by customerfailed- Session failed due to errorresolved_by_operator- Resolved by human operatorescalated_by_operator- Operator marked the session for escalation reviewnot_found- Context or resources for the session were lost or not foundnetwork_error- Closed due to client-side connectivity issuesunknown- Fallback status for undefined closure reasonsuser_timeout- Closed automatically because the customer stopped respondingtimeout- Closed automatically due to maximum session duration limit.declined- Session declinedtransferred- Transferred to another agent/operatordaily_limit_exceeded– A session start was blocked because the daily session limit was exceeded. Contact and Session records are created for analytics, but the session is not activated and does not affect billing or usage
Agent Capabilities
Check what features your agent supports before implementing voice or other advanced features.
| Method & Path | Purpose |
|---|---|
GET {agentRoute}/capabilities | Returns agent capabilities (for example, voice messages, TTS) |
Response:
{
"has_stt": true,
"has_tts": false
}
Voice Features
The Chat API supports both speech-to-text (STT) and text-to-speech (TTS) capabilities.
Speech-to-Text (STT)
| Method & Path | Purpose |
|---|---|
POST {agentRoute}/transcribe | Speech-to-text transcription |
Supported Audio Formats:
audio/wav- WAV formataudio/mp4- MP4/M4A formataudio/webm- WebM format (sent asaudio/mp4)
If transcription fails, verify that:
- the audio format is supported
- the
Content-Typeheader matches the file format - the agent supports STT (
has_stt: true)
Request Headers:
Content-Type: audio/wav
# OR
Content-Type: audio/mp4
Example Usage (JavaScript):
const mimeType = getAudioMimeType();
const contentType =
mimeType === 'audio/webm' || mimeType === 'audio/mp4'
? 'audio/mp4'
: 'audio/wav';
const response = await fetch(`${agentRoute}/transcribe`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': contentType,
},
body: audioBytes
});
const transcribedText = await response.text();
Response: Returns the transcribed text as a plain string:
"Hello, I need help with my account"
Text-to-Speech (TTS)
| Method & Path | Purpose |
|---|---|
GET {agentRoute}/synthesize?text={text}&format={format} | Text-to-speech synthesis; returns audio |
GET {agentRoute}/session/{sessionId}/synthesize?text={text}&format={format} | Session-specific TTS synthesis |
Query Parameters:
text(required): Text to convert to speechformat(optional): Audio format -wavormp4(default:wav)voice_name(optional): Specific voice to use
If synthesis fails, verify that:
- the agent supports TTS (
has_tts: true) - the
Acceptheader matches the requested format
Synthesize Request Headers:
Accept: audio/mp4
# OR
Accept: audio/wav
Example Usage (JavaScript):
const synthesizeTextToSpeech = async (
botRoute: string,
text: string,
format: 'mp4' | 'wav' = 'mp4',
): Promise<Blob> => {
const response = await fetch(`${botRoute}/synthesize?text=${encodeURIComponent(text)}&format=${format}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': `audio/${format}`,
},
});
return await response.blob();
};
// Usage example
const audioBlob = await synthesizeTextToSpeech(
botRoute,
'Hello, how can I help you today?',
'mp4',
);
// Create audio URL and play
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
await audio.play();
Response: Binary audio data (Blob) with appropriate Content-Type header (audio/mp4 or audio/wav).
Conversation Management
Each session represents a single conversation. Create a new session for each new interaction.
Conversations include both session metadata and complete chat history.
Conversation Endpoints
| Method & Path | Purpose |
|---|---|
GET {publicRoute}/api/v1/public/conversations?ext_id={userId} | List conversations of the customer |
GET {publicRoute}/api/v1/public/conversations/attachments/{attachment_id}?ext_id={userId} | Download an attachment |
PATCH {publicRoute}/api/v1/public/sessions/{session_id}/logs/{log_id} | Set a customer reaction (like / dislike) |
Listing Customer Conversations
Query Parameters:
ext_id(required): External customer IDext_type(optional): Customer type, defaults toweb
Response:
{
"user_id": "user123",
"user_name": "John Doe",
"conversations": [
{
"session_id": "session_abc123",
"bot_url": "https://portal.flametree.ai/chatbot/agent_123",
"bot_name": "Customer Support Agent",
"bot_api_key": "sk-...",
"start_time": "2025-06-26T10:30:00Z",
"logs": [
{
"id": 1,
"timestamp": "2025-06-26T10:31:00Z",
"role": "HUMAN",
"text": "Hello, I need help",
"attachments": []
},
{
"id": 2,
"timestamp": "2025-06-26T10:31:30Z",
"role": "AI",
"text": "I'd be happy to help you!",
"attachments": []
}
]
}
]
}
Setting Message Reactions
Allow customers to provide feedback on AI responses with like/dislike reactions.
Content-Type: application/json
Set Reaction Request Body:
{
"feedback": "GOOD",
"ext_id": "user123",
"tenant_id": "00000000-0000-0000-0000-000000000000"
}
Example Usage (JavaScript):
const setMessageReactionRequest = async ({
session_id,
log_id,
url,
data,
}: {
session_id: string;
log_id: string;
url: string;
data: {
feedback: 'GOOD' | 'BAD' | 'NONE';
ext_id: string;
tenant_id?: string;
};
}) => {
const response = await fetch(
`${url}/api/v1/public/sessions/${session_id}/logs/${log_id}`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}
);
return response.json();
};
Downloading Attachments
Query Parameters:
attachment_id(path): ID of the attachment to downloadext_id(required): External customer IDext_type(optional): Customer type, defaults toweb
WebSocket Connections
WebSocket connections enable real-time communication and streaming responses.
Agent Communication WebSocket
Chat sessions can operate in streaming mode where the agent's reply is delivered in real-time chunks.
Connection URL:
wss://portal.flametree.ai/chatbot/{agent_id}/ws/{session_id}
Message Types:
| Payload | Description |
|---|---|
type: "message" | Final bot message |
type: "thought" | Intermediate thoughts |
type: "timeout" | Session timeout notifications |
type: "close" | Session end notifications |
role: "OPERATOR" | Messages from a live operator |
Conversation Events WebSocket
Monitor conversation events across all customer sessions.
Connection URL:
wss://portal.flametree.ai/ws/{user_id}
Event Types:
These events keep the conversation list up-to-date and highlight unread dialogs.
| Event | Meaning |
|---|---|
CONVERSATION_CREATED | New conversation started |
CONVERSATION_CLOSED | Conversation closed |
CONVERSATION_NEW_MESSAGE | New message received |
CONVERSATION_BOT_STATUS_MODIFIED | Agent status updated |
If the WebSocket connection fails, verify that the session_id in the agent WebSocket URL or the user_id in the conversation events WebSocket URL is valid.
Data Types and Enums
Customer Types (ext_type)
| Type | Description |
|---|---|
web | Web widget customers (default) |
mobile | Mobile app customers |
telegram | Telegram bot customers |
whatsapp | WhatsApp customers |
email | Email customers |
sip | Voice/phone customers |
facebook | Facebook customers |
Message Roles
| Role | Description |
|---|---|
HUMAN | Message from the customer |
AI | Message from the AI agent |
OPERATOR | Message from human operator |
COPILOT | Message from AI copilot assistant |
NOTES | Internal notes |
Session Modes
| Mode | Description |
|---|---|
REGULAR | Standard AI agent session |
OPERATOR | Human operator handling |
COPILOT | AI assistant mode |
Feedback Types
| Type | Description |
|---|---|
GOOD | Positive feedback (like) |
BAD | Negative feedback (dislike) |
NONE | No feedback / reset feedback |
Error Handling
| Code | Description |
|---|---|
200 | Success |
401 | Unauthorized: invalid or missing API token |
404 | Not Found: session or resource does not exist |
422 | Validation Error: invalid request parameters |
503 | Service Unavailable: agent temporarily unavailable |
For 401 Unauthorized, verify that the token is copied correctly from the agent's Advanced section and that the request includes the Authorization: Bearer <token> header.