Skip to main content

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

TermDefinition
SessionAn object that represents metadata about the active chat with the agent (no message history)
ConversationAn object that wraps an active session plus the entire chat history. Conversations are returned in the array from the /conversations endpoint
Agent RouteBase URL for agent-specific APIs: https://portal.flametree.ai/chatbot/{agent_id}
Public RouteBase 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

  1. Go to your Flametree portal and open your agent configuration
  2. Navigate to Advanced section
  3. Find the token field (hidden with asterisks)
  4. 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

ContextBase URLReference
Agent-specific APIshttps://portal.flametree.ai/chatbot/{agent_id}→ referred to as {agentRoute}
Public (conversation) APIshttps://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 & PathPurpose
POST {agentRoute}/sessionStart 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_v2Send a message (optionally with file attachments)
tip

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_id in 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 content
  • attachments (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.mode field indicates the session type:

  • REGULAR - Normal request/reply session
  • COPILOT - Session transferred to copilot mode
  • OPERATOR - Session transferred to operator

If the request fails, verify that:

  • the message field 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 successfully
  • busy - Customer or agent busy
  • noanswer - No answer received
  • canceled - Session canceled by customer
  • failed - Session failed due to error
  • resolved_by_operator - Resolved by human operator
  • escalated_by_operator - Operator marked the session for escalation review
  • not_found - Context or resources for the session were lost or not found
  • network_error - Closed due to client-side connectivity issues
  • unknown - Fallback status for undefined closure reasons
  • user_timeout - Closed automatically because the customer stopped responding
  • timeout - Closed automatically due to maximum session duration limit.
  • declined - Session declined
  • transferred - Transferred to another agent/operator
  • daily_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 & PathPurpose
GET {agentRoute}/capabilitiesReturns 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 & PathPurpose
POST {agentRoute}/transcribeSpeech-to-text transcription

Supported Audio Formats:

  • audio/wav - WAV format
  • audio/mp4 - MP4/M4A format
  • audio/webm - WebM format (sent as audio/mp4)

If transcription fails, verify that:

  • the audio format is supported
  • the Content-Type header 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 & PathPurpose
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 speech
  • format (optional): Audio format - wav or mp4 (default: wav)
  • voice_name (optional): Specific voice to use

If synthesis fails, verify that:

  • the agent supports TTS (has_tts: true)
  • the Accept header 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 & PathPurpose
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 ID
  • ext_type (optional): Customer type, defaults to web

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 download
  • ext_id (required): External customer ID
  • ext_type (optional): Customer type, defaults to web

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:

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

EventMeaning
CONVERSATION_CREATEDNew conversation started
CONVERSATION_CLOSEDConversation closed
CONVERSATION_NEW_MESSAGENew message received
CONVERSATION_BOT_STATUS_MODIFIEDAgent 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)

TypeDescription
webWeb widget customers (default)
mobileMobile app customers
telegramTelegram bot customers
whatsappWhatsApp customers
emailEmail customers
sipVoice/phone customers
facebookFacebook customers

Message Roles

RoleDescription
HUMANMessage from the customer
AIMessage from the AI agent
OPERATORMessage from human operator
COPILOTMessage from AI copilot assistant
NOTESInternal notes

Session Modes

ModeDescription
REGULARStandard AI agent session
OPERATORHuman operator handling
COPILOTAI assistant mode

Feedback Types

TypeDescription
GOODPositive feedback (like)
BADNegative feedback (dislike)
NONENo feedback / reset feedback

Error Handling

CodeDescription
200Success
401Unauthorized: invalid or missing API token
404Not Found: session or resource does not exist
422Validation Error: invalid request parameters
503Service 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.


Was this article helpful?