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

All REST API requests require an authorization header with your agent's API token:

Authorization: Bearer <token>

Getting Your Credentials

💡 Note: Follow these steps to obtain your authentication credentials:

To get your API token:

  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}

Session Management

Creating and Managing Sessions

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
DELETE {agentRoute}/session/{sessionId}Close the session
POST {agentRoute}/session/{sessionId}/run_v2Send a message (optionally with file attachments)

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 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,
"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
}

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

Closing Sessions

When closing a session, you can specify a completion status:

Available Session Status Values:

  • completed - Session completed successfully
  • busy - User or agent busy
  • noanswer - No answer received
  • canceled - Session canceled by user
  • failed - Session failed due to error
  • resolved_by_operator - Resolved by human operator
  • declined - Session declined
  • transferred - Transferred to another agent/operator

Agent Capabilities

Check what features your agent supports before implementing voice or other advanced features.

Capabilities Endpoint

Method & PathPurpose
GET {agentRoute}/capabilitiesReturns agent capabilities (e.g., 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)

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

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

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 user
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 user reaction (like / dislike)

Listing User Conversations

Query Parameters:

  • ext_id (required): External user ID
  • ext_type (optional): User 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 users 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 user ID
  • ext_type (optional): User type, defaults to web

WebSocket Connections

WebSocket connections enable real-time communication and streaming responses.

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

2. Conversation Events WebSocket

Monitor conversation events across all user sessions.

Connection URL:

wss://portal.flametree.ai/ws/{user_id}

Event Types:

EventMeaning
CONVERSATION_CREATEDNew conversation started
CONVERSATION_CLOSEDConversation closed
CONVERSATION_NEW_MESSAGENew message received
CONVERSATION_BOT_STATUS_MODIFIEDAgent status updated

💡 Note: These events keep the conversation list up-to-date and highlight unread dialogs.

Data Types and Enums

User Types (ext_type)

TypeDescription
webWeb widget users (default)
telegramTelegram bot users
whatsappWhatsApp users
emailEmail users
sipVoice/phone users
facebookFacebook Messenger users

Message Roles

RoleDescription
HUMANMessage from the user
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

Common Issues & Solutions

Authentication fails with 401 error

Possible causes:

  • Invalid or expired API token
  • Missing Authorization header
  • Incorrect token format

Solutions:

  1. Verify token: Double-check your API token from the agent's Advanced section
  2. Check header format: Ensure you're using Authorization: Bearer <token>
  3. Regenerate token: If token is expired, generate a new one from the Flametree portal
Session creation fails

Possible causes:

  • Invalid agent_id in the URL
  • Missing required fields in request body
  • Agent is not active or configured properly

Solutions:

  1. Verify agent_id: Check the agent_id from your Flametree portal
  2. Validate request body: Ensure all required fields are present
  3. Check agent status: Verify your agent is active and properly configured
Voice features not working

Possible causes:

  • Agent doesn't support STT/TTS capabilities
  • Incorrect audio format
  • Missing Content-Type headers

Solutions:

  1. Check capabilities: Use the /capabilities endpoint to verify STT/TTS support
  2. Verify audio format: Ensure you're using supported audio formats
  3. Set headers: Include proper Content-Type headers for audio requests
WebSocket connection fails

Possible causes:

  • Invalid session_id or user_id
  • Network connectivity issues
  • Firewall blocking WebSocket connections

Solutions:

  1. Verify IDs: Check that session_id and user_id are valid
  2. Test connectivity: Ensure your network allows WebSocket connections
  3. Check firewall: Verify WebSocket traffic isn't blocked

Error Handling

HTTP Status Codes

CodeDescription
200Success
401Unauthorized - Invalid or missing API token
404Not Found - Session or resource doesn't exist
422Validation Error - Invalid request parameters
503Service Unavailable - Agent temporarily unavailable

FAQ

How do I handle streaming responses?

Use WebSocket connections to receive real-time message chunks. Connect to the agent communication WebSocket and listen for type: "message" events for streaming responses.

Can I use the same session for multiple conversations?

No, each session represents a single conversation. Create a new session for each new conversation to maintain proper context and isolation.

What's the maximum file size for attachments?

File size limits depend on your Flametree plan and agent configuration. Check with your Flametree administrator for specific limits.

How long do sessions remain active?

Session timeout is configurable per agent (default: 259200 seconds = 72 hours). Inactive sessions are automatically closed after the timeout period.

Can I integrate with multiple agents?

Yes, you can integrate with multiple agents by using different agent_ids in your API calls. Each agent requires its own authentication token.