Skip to main content

Chat & Respond API

AvonAI provides two API endpoints for interacting with your AI agents programmatically. This guide explains when to use each one and how to integrate them into your application.

Two Endpoints, Two Use Cases

/chat/respond
Best forProduction conversationsOne-off questions, testing
Conversation memoryAutomatic -- the agent remembers previous messagesManual -- you must send the full history yourself
Message persistenceYes -- all messages are savedNo -- nothing is stored
Quality monitoringYes -- conversations are analyzed in AvonAINo
Multi-turn supportBuilt-in (reuse the same conversationId)Manual (pass chat_history each time)

Recommendation: Use /chat for any user-facing or production integration. Use /respond only for quick tests or stateless, single-question scenarios.


Authentication

Every request must include one of the following headers:

API Key (recommended for integrations):

X-API-Key: avk_your_api_key_here

Bearer Token (for SSO/JWT-based auth):

Authorization: Bearer <your_jwt_token>
info

You can generate API keys from the AvonAI platform under Settings > API Keys.


Use this endpoint for multi-turn conversations. The platform automatically stores messages, fetches conversation history, and feeds it to the agent on every turn.

Endpoint

POST {BASE_URL}/api/ai-agents/chat

Request Format

{
"conversationId": "string (required)",
"agentId": "string (required)",
"message": {
"role": "customer",
"sender_id": "string (required)",
"content": "string (required)"
},
"user_data": {}
}

Field Reference

FieldTypeRequiredDescription
conversationIdstringYesUnique ID for this conversation. Reuse the same ID for all messages in a conversation. Max 200 characters.
agentIdstringYesThe ID of your AI agent (found in the AI Admin Panel). Max 200 characters.
message.rolestringYesAlways "customer" for user messages.
message.sender_idstringYesUnique identifier for the end-user sending the message. Max 200 characters.
message.contentstringYesThe user's message text. Max 50,000 characters.
user_dataobjectNoKey-value pairs for personalization (e.g., user name, account type, region).

Response Format

{
"message_id": "auto-generated-uuid",
"conversation_id": "your-conversation-id",
"role": "agent",
"sender_id": "agent-id",
"content": "The agent's response text",
"timestamp": "2025-01-15T12:00:00Z",
"metadata": {
"sources": [
{
"id": "doc-id",
"content": "relevant excerpt from knowledge base",
"kb_id": "knowledge-base-id",
"score": 0.95
}
]
}
}
FieldDescription
contentThe agent's answer to the user's question.
metadata.sourcesKnowledge base articles the agent used to generate its answer (RAG agents only).
conversation_idEchoes back the conversation ID you sent.

Multi-Turn Conversations

The key to multi-turn conversations is the conversationId. When you send multiple messages with the same conversationId, the agent automatically retrieves the full conversation history and uses it to understand context.

How It Works

Turn 1: { "conversationId": "conv-abc", "content": "What is your return policy?" }
→ Agent responds about the return policy

Turn 2: { "conversationId": "conv-abc", "content": "What if I lost the receipt?" }
→ Agent knows you're still asking about returns (same conversationId)

Turn 3: { "conversationId": "conv-abc", "content": "Can I return after 30 days?" }
→ Agent uses full context of the conversation

Behind the scenes, the agent rewrites vague follow-ups (e.g., "tell me more about that") into specific queries (e.g., "tell me more about the return policy") for better knowledge base retrieval.

Important

If you generate a new conversationId for every message, each message will be treated as an independent conversation and the agent will have no memory of previous messages.

When to Generate a New conversationId

  • The user starts a new conversation or topic
  • The user opens a new session (e.g., logs in again)
  • You want to reset context intentionally

When to Reuse the Same conversationId

  • The user sends a follow-up message in the same conversation
  • The user asks for clarification or more details
  • The user continues the same topic

Example: Multi-Turn Conversation

cURL

# Turn 1 -- Start a new conversation
curl -X POST https://your-instance.avon-ai.com/api/ai-agents/chat \
-H "X-API-Key: avk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"conversationId": "conv-abc-123",
"agentId": "your-agent-id",
"message": {
"role": "customer",
"sender_id": "user-42",
"content": "What is your return policy?"
}
}'

# Turn 2 -- Follow-up (same conversationId)
curl -X POST https://your-instance.avon-ai.com/api/ai-agents/chat \
-H "X-API-Key: avk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"conversationId": "conv-abc-123",
"agentId": "your-agent-id",
"message": {
"role": "customer",
"sender_id": "user-42",
"content": "What if I lost the receipt?"
}
}'

# New conversation -- different topic, new conversationId
curl -X POST https://your-instance.avon-ai.com/api/ai-agents/chat \
-H "X-API-Key: avk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"conversationId": "conv-xyz-456",
"agentId": "your-agent-id",
"message": {
"role": "customer",
"sender_id": "user-42",
"content": "How do I track my order?"
}
}'

Python

import requests
import uuid

BASE_URL = "https://your-instance.avon-ai.com"
API_KEY = "avk_your_api_key"
AGENT_ID = "your-agent-id"

headers = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}

def send_message(conversation_id: str, sender_id: str, content: str) -> dict:
response = requests.post(
f"{BASE_URL}/api/ai-agents/chat",
headers=headers,
json={
"conversationId": conversation_id,
"agentId": AGENT_ID,
"message": {
"role": "customer",
"sender_id": sender_id,
"content": content
}
}
)
response.raise_for_status()
return response.json()


# Start a conversation
conv_id = str(uuid.uuid4())

# Turn 1
reply = send_message(conv_id, "user-42", "What is your return policy?")
print(f"Agent: {reply['content']}")

# Turn 2 -- agent remembers the context automatically
reply = send_message(conv_id, "user-42", "What if I lost the receipt?")
print(f"Agent: {reply['content']}")

# Turn 3
reply = send_message(conv_id, "user-42", "Can I return after 30 days?")
print(f"Agent: {reply['content']}")

Node.js

const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const BASE_URL = 'https://your-instance.avon-ai.com';
const API_KEY = 'avk_your_api_key';
const AGENT_ID = 'your-agent-id';

async function sendMessage(conversationId, senderId, content) {
const response = await axios.post(
`${BASE_URL}/api/ai-agents/chat`,
{
conversationId,
agentId: AGENT_ID,
message: {
role: 'customer',
sender_id: senderId,
content
}
},
{
headers: {
'X-API-Key': API_KEY,
'Content-Type': 'application/json'
}
}
);
return response.data;
}

async function main() {
const convId = uuidv4();

// Turn 1
let reply = await sendMessage(convId, 'user-42', 'What is your return policy?');
console.log('Agent:', reply.content);

// Turn 2 -- agent remembers context
reply = await sendMessage(convId, 'user-42', 'What if I lost the receipt?');
console.log('Agent:', reply.content);
}

main();

Personalization with user_data

If your agent is configured for personalization (via the Personal Data Engine), you can pass user-specific data to tailor responses:

{
"conversationId": "conv-abc-123",
"agentId": "your-agent-id",
"message": {
"role": "customer",
"sender_id": "user-42",
"content": "What's my account balance?"
},
"user_data": {
"userId": "user-42",
"name": "John Smith",
"account_type": "premium",
"region": "US-East"
}
}

The agent uses this data to personalize responses and filter knowledge base results relevant to the user.


The /respond Endpoint (Stateless)

Use this endpoint for single-turn, stateless interactions. The platform does not store messages or fetch history -- you manage the conversation state yourself.

Endpoint

POST {BASE_URL}/api/ai-agents/respond

Request Format

{
"agent_id": "string (required)",
"msg": {
"role": "customer",
"sender_id": "string (required)",
"content": "string (required)",
"conversation_id": "string (required)"
},
"chat_history": [],
"user_data": {}
}

Field Reference

FieldTypeRequiredDescription
agent_idstringYesThe ID of your AI agent.
msg.rolestringYesAlways "customer" for user messages.
msg.sender_idstringYesUnique identifier for the end-user.
msg.contentstringYesThe user's message text.
msg.conversation_idstringYesAn identifier for the conversation (used internally, not persisted).
chat_historyarrayNoPrevious messages in the conversation. You must manage and send this yourself.
user_dataobjectNoKey-value pairs for personalization.

Example

curl -X POST https://your-instance.avon-ai.com/api/ai-agents/respond \
-H "X-API-Key: avk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "your-agent-id",
"msg": {
"role": "customer",
"sender_id": "user-42",
"content": "What is your return policy?",
"conversation_id": "temp-session-1"
},
"chat_history": []
}'
tip

If you need multi-turn support with /respond, you must collect the agent's response after each turn and include it in chat_history for the next request. The /chat endpoint handles this automatically.


Error Handling

HTTP StatusMeaningSuggested Action
200SuccessParse the response normally.
401UnauthorizedCheck your API key or JWT token.
404Agent not foundVerify your agentId / agent_id.
422Validation errorCheck that all required fields are present and correctly formatted.
500Server errorRetry with exponential backoff.

Best Practices

  1. Use /chat for production -- it handles history, persistence, and monitoring automatically.
  2. One conversationId per conversation -- don't reuse IDs across unrelated conversations, and don't generate new IDs for follow-up messages.
  3. Keep sender_id consistent per user -- this helps identify users across conversations.
  4. Generate conversationId on your side -- use UUIDs, session tokens, or any unique string (max 200 characters).
  5. Check metadata.sources in the response to see which knowledge base articles were used.
  6. Start fresh conversations for new topics -- this keeps context clean and improves answer quality.