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
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:
- 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} |
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 & Path | Purpose |
---|---|
POST {agentRoute}/session | Start a new session |
GET {agentRoute}/session/{sessionId} | Get session metadata |
DELETE {agentRoute}/session/{sessionId} | Close the session |
POST {agentRoute}/session/{sessionId}/run_v2 | Send 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 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.mode
field indicates the session type:
REGULAR
- Normal request/reply sessionCOPILOT
- Session transferred to copilot modeOPERATOR
- Session transferred to operator
Closing Sessions
When closing a session, you can specify a completion status:
Available Session Status Values:
completed
- Session completed successfullybusy
- User or agent busynoanswer
- No answer receivedcanceled
- Session canceled by userfailed
- Session failed due to errorresolved_by_operator
- Resolved by human operatordeclined
- Session declinedtransferred
- Transferred to another agent/operator
Agent Capabilities
Check what features your agent supports before implementing voice or other advanced features.
Capabilities Endpoint
Method & Path | Purpose |
---|---|
GET {agentRoute}/capabilities | Returns 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 & 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
)
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 -wav
ormp4
(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 & Path | Purpose |
---|---|
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 IDext_type
(optional): User 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 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 downloadext_id
(required): External user IDext_type
(optional): User type, defaults toweb
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:
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 |
2. Conversation Events WebSocket
Monitor conversation events across all user sessions.
Connection URL:
wss://portal.flametree.ai/ws/{user_id}
Event Types:
Event | Meaning |
---|---|
CONVERSATION_CREATED | New conversation started |
CONVERSATION_CLOSED | Conversation closed |
CONVERSATION_NEW_MESSAGE | New message received |
CONVERSATION_BOT_STATUS_MODIFIED | Agent status updated |
💡 Note: These events keep the conversation list up-to-date and highlight unread dialogs.
Data Types and Enums
User Types (ext_type
)
Type | Description |
---|---|
web | Web widget users (default) |
telegram | Telegram bot users |
whatsapp | WhatsApp users |
email | Email users |
sip | Voice/phone users |
facebook | Facebook Messenger users |
Message Roles
Role | Description |
---|---|
HUMAN | Message from the user |
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 |
Common Issues & Solutions
Authentication fails with 401 error
Possible causes:
- Invalid or expired API token
- Missing Authorization header
- Incorrect token format
Solutions:
- Verify token: Double-check your API token from the agent's Advanced section
- Check header format: Ensure you're using
Authorization: Bearer <token>
- 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:
- Verify agent_id: Check the agent_id from your Flametree portal
- Validate request body: Ensure all required fields are present
- 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:
- Check capabilities: Use the
/capabilities
endpoint to verify STT/TTS support - Verify audio format: Ensure you're using supported audio formats
- 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:
- Verify IDs: Check that session_id and user_id are valid
- Test connectivity: Ensure your network allows WebSocket connections
- Check firewall: Verify WebSocket traffic isn't blocked
Error Handling
HTTP Status Codes
Code | Description |
---|---|
200 | Success |
401 | Unauthorized - Invalid or missing API token |
404 | Not Found - Session or resource doesn't exist |
422 | Validation Error - Invalid request parameters |
503 | Service 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.