Chat API

Integrate AlonChat conversations into your applications via the REST API

Chat API#

Send messages and receive AI responses programmatically through the AlonChat Chat API.


Overview#

The Chat API lets you:

  • Send a customer message to your AI agent
  • Receive a complete reply or a streaming response
  • Continue multi-turn conversations with a conversation ID
  • Track credits used for each request

API, MCP, and CLI access are available on every paid plan. Active trials may access gated features during the trial, subject to trial limits.

The same endpoint is documented on your agent's Deploy → API page.


Quick Start#

1. Get Your API Key#

  1. Go to Project Settings → API Keys and create a key (optionally restrict it to one agent).
  2. Open your agent's Deploy → API page for the endpoint and Agent ID.
  3. Send the key as a Bearer token from your server only.

Keys look like sk-… and are shown once at creation.

2. Make Your First Request#

bash
curl -X POST https://alonchat.com/api/v1/chat/{agentId} \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Hello, what are your business hours?"
  }'

3. Handle the Response#

json
{
  "response": "We're open Monday–Saturday, 9AM to 6PM. Closed on Sundays and holidays!",
  "conversation_id": "550e8400-e29b-41d4-a716-446655440000",
  "credits_used": 5,
  "credits_remaining": 995
}

Save conversation_id and send it on later requests to keep the same thread.


Authentication#

Code
Authorization: Bearer YOUR_API_KEY

API keys are managed in Project Settings → API Keys. You can optionally restrict a key to one agent. See the Authentication guide.

Security: Use API keys only on your server. Never put them in frontend code, mobile apps, or public repositories.


Endpoint#

POST /api/v1/chat/{agentId}

Request Body#

FieldTypeRequiredDescription
messagestringYesUser message (1–10,000 characters)
conversation_iduuidNoContinue an existing conversation. Omit to start a new one.
streambooleanNoSet true for Server-Sent Events (SSE). Default false.
idempotency_keystringNoSafe retries. Replaying an in-flight key returns 409. Can also be sent as Idempotency-Key or X-Idempotency-Key header.

Example (non-streaming)#

javascript
const response = await fetch(`https://alonchat.com/api/v1/chat/${agentId}`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    message: 'What products do you offer?',
    conversation_id: '550e8400-e29b-41d4-a716-446655440000',
    idempotency_key: crypto.randomUUID(),
  }),
})

const data = await response.json()
console.log(data.response)
console.log(data.conversation_id)
console.log(data.credits_used)

Success Response#

FieldTypeDescription
responsestringAgent reply text
conversation_iduuidConversation to continue on the next turn
credits_usednumberCredits consumed by this request
credits_remainingnumberCredits left after this request

Additional diagnostic fields may appear for debugging; treat response, conversation_id, and the credit fields as the stable public contract.


Streaming Responses#

Set "stream": true to receive Server-Sent Events. Each line is prefixed with data: followed by JSON.

javascript
const response = await fetch(`https://alonchat.com/api/v1/chat/${agentId}`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    message: 'Tell me about your services',
    stream: true,
  }),
})

const reader = response.body.getReader()
const decoder = new TextDecoder()

while (true) {
  const { done, value } = await reader.read()
  if (done) break

  const chunk = decoder.decode(value, { stream: true })
  for (const line of chunk.split('\n')) {
    if (!line.startsWith('data: ')) continue
    const event = JSON.parse(line.slice(6))

    if (event.type === 'token') {
      process.stdout.write(event.token)
    } else if (event.type === 'done') {
      console.log('\nConversation:', event.conversation_id)
      console.log('Credits used:', event.credits_used)
    } else if (event.type === 'error') {
      console.error(event.error)
    }
  }
}

Common stream event types:

TypeMeaning
tokenPartial reply text
doneStream finished; includes final reply fields
errorRequest failed mid-stream

Other event types may appear when the agent runs tools mid-turn. Handle unknown types safely.


Rate Limits#

The Chat API is rate-limited to 60 requests per minute per API key.

Responses include rate-limit headers so you can track usage. When you exceed the limit, the API returns 429 with retry_after_seconds (and related limit fields). Back off before retrying.


Error Handling#

StatusMeaning
200Success
400Invalid request body
401Invalid or missing API key
402Insufficient credits
403Insufficient permissions or plan locked
404Agent not found
409Duplicate in-flight idempotency key
429Rate limited
500Server error
503Service temporarily unavailable

Error bodies are typically a flat JSON object, for example:

json
{
  "error": "Too many requests",
  "retry_after_seconds": 30
}

Insufficient credits may include remaining credit fields and a stable code such as INSUFFICIENT_CREDITS. Duplicate idempotency requests may include DUPLICATE_REQUEST.


Best Practices#

  1. Store conversation_id so multi-turn chats keep context.
  2. Send an idempotency_key on payment-sensitive or retried requests.
  3. Use streaming when you want progressive UI updates.
  4. Keep keys server-side and rotate them if they leak.
  5. Watch credits via credits_used / credits_remaining and your Usage page.