Agent API

Overview

The Flutch External API allows you to integrate AI agents into your applications programmatically. Use this API to send messages to agents and receive responses either synchronously or via streaming.

Base URL

https://api.flutch.ai/api/v1

Authentication

All API requests require an API key passed in the X-API-Key header.

Getting Your API Key

  1. Log in to your Flutch admin panel
  2. Navigate to /tokens (hidden page, accessible by direct URL)
  3. Click "Generate API Key"
  4. Important: Copy and save the key immediately - it will only be shown once!

API Key Format

flutch_<64 hexadecimal characters>

Example:

flutch_f6f1a55e248f04eb6896c2d77e5060ba4d192951db74aa21045e23b7ac39622e

Security Best Practices

  • Never commit API keys to version control
  • Store keys securely using environment variables or secrets management
  • Rotate keys periodically
  • Revoke compromised keys immediately via the admin panel

Endpoints

1. Invoke Agent (Synchronous)

Send a message to an agent and receive the complete response.

Endpoint:

POST /agents/{agentId}/invoke

Headers:

Content-Type: application/json
X-API-Key: flutch_your_api_key_here

Request Body:

json
{
  "userId": "user-123",
  "content": {
    "text": "Hello, what can you help me with?"
  },
  "threadId": "thread-456"  // Optional - for continuing a conversation
}

Parameters:

FieldTypeRequiredDescription
userIdstringYesID of the user making the request. Must belong to your company.
content.textstringYesThe message text to send to the agent
threadIdstringNoThread ID to continue an existing conversation. Omit to create a new thread.

Response (201 Created):

json
{
  "id": "694d21839750ec2392a293c2",
  "threadId": "694d21829750ec2392a293b7",
  "userId": "67b3447044b9e7a1c9b71756",
  "agentId": "67b88f7ec6092d7bc711a934",
  "role": "assistant",
  "platform": "api",
  "reason": "agent_reply",
  "content": {
    "text": "I can help you with various tasks...",
    "contentChains": [],
    "attachments": [],
    "reasoningChains": []
  },
  "status": "delivered",
  "createdAt": "2025-12-25T11:35:31.498Z",
  "updatedAt": "2025-12-25T11:35:31.498Z"
}

cURL Example:

bash
curl -X POST https://your-domain.com/api/v1/agents/67b88f7ec6092d7bc711a934/invoke \
  -H "Content-Type: application/json" \
  -H "X-API-Key: flutch_f6f1a55e248f04eb6896c2d77e5060ba..." \
  -d '{
    "userId": "user-123",
    "content": {
      "text": "Hello, what can you help me with?"
    }
  }'

2. Stream Agent Response (Server-Sent Events)

Send a message to an agent and receive the response in real-time via Server-Sent Events (SSE).

Endpoint:

POST /agents/{agentId}/stream

Headers:

Content-Type: application/json
X-API-Key: flutch_your_api_key_here

Request Body: Same as invoke endpoint.

Response Format (SSE):

The response is streamed as Server-Sent Events with the following event types:

Event: thread_created

Sent when a new thread is created or existing thread is loaded.

event: thread_created
data: {"threadId":"thread-123"}

Event: partial

Sent for each chunk of the agent's response as it's being generated.

event: partial
data: Hello

event: partial
data:  world

event: partial
data: !

Event: thread_renamed

Sent if the thread title is updated based on the conversation.

event: thread_renamed
data: {"title":"Conversation about AI"}

Event: final

Sent when the agent's response is complete. Contains the full message object.

event: final
data: {"id":"msg-123","content":{"text":"Hello world!"},...}

Event: error

Sent if an error occurs during processing.

event: error
data: {"error":"Error message","code":"ERROR_CODE"}

JavaScript Example:

javascript
const eventSource = new EventSource(
  'https://your-domain.com/api/v1/agents/67b88f7ec6092d7bc711a934/stream',
  {
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'flutch_your_api_key_here'
    }
  }
);

eventSource.addEventListener('thread_created', (e) => {
  const data = JSON.parse(e.data);
  console.log('Thread ID:', data.threadId);
});

eventSource.addEventListener('partial', (e) => {
  console.log('Partial response:', e.data);
  // Update UI with streaming text
});

eventSource.addEventListener('final', (e) => {
  const message = JSON.parse(e.data);
  console.log('Complete message:', message);
  eventSource.close();
});

eventSource.addEventListener('error', (e) => {
  const error = JSON.parse(e.data);
  console.error('Error:', error);
  eventSource.close();
});

cURL Example:

bash
curl -N -X POST https://your-domain.com/api/v1/agents/67b88f7ec6092d7bc711a934/stream \
  -H "Content-Type: application/json" \
  -H "X-API-Key: flutch_f6f1a55e248f04eb6896c2d77e5060ba..." \
  -d '{
    "userId": "user-123",
    "content": {
      "text": "Tell me a story"
    }
  }'

Error Responses

401 Unauthorized

Missing or invalid API key.

json
{
  "statusCode": 401,
  "message": "Invalid API key"
}

403 Forbidden

User doesn't belong to the company associated with the API key, or doesn't have access to the agent.

json
{
  "statusCode": 403,
  "message": "Access denied"
}

400 Bad Request

Invalid request parameters.

json
{
  "statusCode": 400,
  "message": "userId is required in request body"
}

404 Not Found

Agent or thread not found.

json
{
  "statusCode": 404,
  "message": "Agent not found"
}

500 Internal Server Error

Server error during processing.

json
{
  "statusCode": 500,
  "message": "Internal server error"
}

Best Practices

Thread Management

Creating Conversations:

  • Omit threadId in the first request to create a new conversation thread
  • Save the threadId from the response
  • Include the same threadId in subsequent requests to continue the conversation

Example Flow:

javascript
// First message - creates new thread
const response1 = await invoke(agentId, {
  userId: "user-123",
  content: { text: "What is AI?" }
});
const threadId = response1.threadId; // Save this!

// Follow-up message - continues conversation
const response2 = await invoke(agentId, {
  userId: "user-123",
  content: { text: "Tell me more" },
  threadId: threadId  // Use saved threadId
});

Rate Limiting

  • Current implementation has no hard rate limits
  • Recommended: Implement client-side throttling to avoid overwhelming the API
  • Suggested limit: 10 requests per second per API key

Error Handling

Always implement proper error handling:

javascript
async function invokeAgent(agentId, userId, text, threadId = null) {
  try {
    const response = await fetch(
      `https://your-domain.com/api/v1/agents/${agentId}/invoke`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': process.env.FLUTCH_API_KEY
        },
        body: JSON.stringify({
          userId,
          content: { text },
          ...(threadId && { threadId })
        })
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error: ${error.message}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Failed to invoke agent:', error);
    throw error;
  }
}

Integration Examples

Node.js

javascript
const axios = require('axios');

const FLUTCH_API_KEY = process.env.FLUTCH_API_KEY;
const BASE_URL = 'https://your-domain.com/api/v1';

async function sendMessage(agentId, userId, text, threadId = null) {
  const response = await axios.post(
    `${BASE_URL}/agents/${agentId}/invoke`,
    {
      userId,
      content: { text },
      ...(threadId && { threadId })
    },
    {
      headers: {
        'X-API-Key': FLUTCH_API_KEY
      }
    }
  );

  return response.data;
}

// Usage
(async () => {
  const message = await sendMessage(
    '67b88f7ec6092d7bc711a934',
    'user-123',
    'Hello, AI!'
  );

  console.log('Agent response:', message.content.text);
  console.log('Thread ID:', message.threadId);
})();

Python

python
import requests
import os

FLUTCH_API_KEY = os.getenv('FLUTCH_API_KEY')
BASE_URL = 'https://your-domain.com/api/v1'

def send_message(agent_id, user_id, text, thread_id=None):
    url = f'{BASE_URL}/agents/{agent_id}/invoke'
    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': FLUTCH_API_KEY
    }

    payload = {
        'userId': user_id,
        'content': {'text': text}
    }

    if thread_id:
        payload['threadId'] = thread_id

    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status()

    return response.json()

# Usage
message = send_message(
    '67b88f7ec6092d7bc711a934',
    'user-123',
    'Hello, AI!'
)

print(f"Agent response: {message['content']['text']}")
print(f"Thread ID: {message['threadId']}")

cURL

bash
#!/bin/bash

AGENT_ID="67b88f7ec6092d7bc711a934"
USER_ID="user-123"
API_KEY="flutch_your_api_key_here"
BASE_URL="https://your-domain.com/api/v1"

# Send message
curl -X POST "${BASE_URL}/agents/${AGENT_ID}/invoke" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: ${API_KEY}" \
  -d "{
    \"userId\": \"${USER_ID}\",
    \"content\": {
      \"text\": \"Hello, AI!\"
    }
  }"

FAQ

Q: Can I use one API key for multiple users? A: Yes, the API key authenticates your company. You specify the userId in each request to identify which user is making the request.

Q: How do I get my agent ID? A: Agent IDs are visible in the admin panel URL when viewing an agent (e.g., /agents/67b88f7ec6092d7bc711a934).

Q: What happens if I lose my API key? A: You cannot retrieve a lost API key. Generate a new one and update your applications. Revoke the old key if necessary.

Q: Can I have multiple API keys? A: Currently, only one API key per company is supported. Generating a new key doesn't automatically revoke the old one.

Q: Is there a webhook for receiving responses? A: Not currently. Use the streaming endpoint (/stream) for real-time responses.

Q: What's the maximum message length? A: There is no hard limit, but very long messages may be truncated by the underlying AI model (typically 4000-8000 tokens depending on the model).

Support

For technical support or questions:

  • Check the admin panel documentation
  • Contact your Flutch account manager
  • Email: [email protected]

Changelog

Version 1.0 (2025-01-15)

  • Initial API release
  • /invoke endpoint for synchronous responses
  • /stream endpoint for real-time streaming
  • API key authentication