Skip to main content

Agent Interaction (Enhanced) - POST /external/agent/v2

The enhanced agent endpoint provides the most robust way to interact with your Optimly AI agent. This endpoint supports advanced features like automatic tool detection, seamless handoffs, and enhanced context management.

Endpoint

POST /external/agent/v2

Authentication

This endpoint requires an agent access token provided via the Authorization header or query parameter.

Authorization: Bearer YOUR_AGENT_ACCESS_TOKEN

Query Parameter

POST /external/agent/v2?access_token_query=YOUR_AGENT_ACCESS_TOKEN

Request Body

{
"chat_id": "string",
"content": "string",
"metadata": {
"client_id": "string",
"session_id": "string",
"source": "string"
}
}

Parameters

ParameterTypeRequiredDescription
chat_idstringYesUnique identifier for the chat session
contentstringYesThe user's message content
metadataobjectNoAdditional context and tracking information
metadata.client_idstringNoUnique identifier for the client/user
metadata.session_idstringNoSession identifier for tracking
metadata.sourcestringNoSource of the message (e.g., "website", "mobile")

Response

Success Response

{
"agent_id": "agent_123",
"chat_id": "chat_456",
"response": "Hello! I'd be happy to help you today. What can I assist you with?",
"message_id": "msg_789",
"timestamp": "2025-06-16T10:30:00Z",
"tools_executed": [
{
"tool": "lead_capture",
"status": "executed",
"data": {
"form_submitted": true
}
}
],
"handoff_data": null,
"metadata": {
"processing_time": 1.2,
"tokens_used": 150,
"knowledge_chunks_used": 3
}
}

Response Fields

FieldTypeDescription
agent_idstringID of the agent that processed the message
chat_idstringChat session identifier
responsestringThe agent's response text
message_idstringUnique ID for this message exchange
timestampstringISO timestamp of the response
tools_executedarrayList of tools that were automatically executed
handoff_dataobjectInformation about any handoffs initiated
metadataobjectProcessing metadata and usage information

Example Usage

Basic Message Exchange

const response = await fetch('https://api.optimly.io/external/agent/v2', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: 'chat_12345',
content: 'I need help with my account settings',
metadata: {
client_id: 'user_789',
source: 'website'
}
})
});

const data = await response.json();
console.log('Agent response:', data["response"]);

Python Example

import requests

url = 'https://api.optimly.io/external/agent/v2'
headers = {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
}
payload = {
'chat_id': 'chat_12345',
'content': 'Can you help me schedule a demo?',
'metadata': {
'client_id': 'user_789',
'source': 'mobile_app'
}
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Agent response: {data['response']}")

cURL Example

curl -X POST https://api.optimly.io/external/agent/v2 \
-H "Authorization: Bearer your_access_token" \
-H "Content-Type: application/json" \
-d '{
"chat_id": "chat_12345",
"content": "What are your business hours?",
"metadata": {
"client_id": "user_789",
"source": "website"
}
}'

Automatic Tool Execution

The v2 endpoint automatically detects when tools should be executed based on the conversation context:

Lead Capture

When a user provides contact information, the agent automatically captures it:

{
"content": "My email is john@example.com and I'm interested in your services"
}

Response includes:

{
"tools_executed": [
{
"tool": "lead_capture",
"status": "executed",
"data": {
"email": "john@example.com",
"lead_id": "lead_456"
}
}
]
}

Appointment Scheduling

When users request appointments, the system can automatically schedule them:

{
"content": "I'd like to book a meeting for next Tuesday at 2 PM"
}

Email Handoff

For complex queries, the agent can automatically initiate email handoffs:

{
"handoff_data": {
"type": "email",
"status": "initiated",
"ticket_id": "ticket_789"
}
}

Error Handling

Common Error Responses

Invalid Access Token

{
"error": "Invalid access token",
"detail": "The provided access token is not valid or has expired",
"status_code": 401
}

Chat Not Found

{
"error": "Chat not found",
"detail": "The specified chat_id does not exist or is not accessible",
"status_code": 404
}

Rate Limit Exceeded

{
"error": "Rate limit exceeded",
"detail": "Too many requests. Please wait before making another request",
"status_code": 429
}

Invalid Request

{
"error": "Validation error",
"detail": "content field is required",
"status_code": 400
}

Best Practices

1. Error Handling

Always implement proper error handling for API calls:

try {
const response = await fetch('/external/agent/v2', options);

if (!response.ok) {
const error = await response.json();
throw new Error(error["detail"] || 'API request failed');
}

const data = await response.json();
// Handle successful response
} catch (error) {
console.error('Agent API error:', error["message"]);
// Show user-friendly error message
}

2. Timeout Handling

Set appropriate timeouts for API calls:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout

try {
const response = await fetch('/external/agent/v2', {
...options,
signal: controller.signal
});
clearTimeout(timeoutId);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request timed out');
}
}

3. Metadata Usage

Include relevant metadata to improve tracking and analytics:

{
"metadata": {
"client_id": "user_12345",
"session_id": "session_abcde",
"source": "mobile_app",
"user_agent": navigator.userAgent,
"page_url": window.location.href
}
}

Integration Examples

React Chat Component

import React, { useState } from 'react';

function ChatComponent({ accessToken, chatId }) {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [loading, setLoading] = useState(false);

const sendMessage = async () => {
if (!message.trim()) return;

setLoading(true);
const userMessage = { role: 'user', content: message };
setMessages(prev => [...prev, userMessage]);

try {
const response = await fetch('/external/agent/v2', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: chatId,
content: message,
metadata: {
source: 'react_component'
}
})
});

const data = await response.json();

const agentMessage = { role: 'assistant', content: data.response };
setMessages(prev => [...prev, agentMessage]);

} catch (error) {
console.error('Error sending message:', error);
} finally {
setLoading(false);
setMessage('');
}
};

return (
<div className="chat-component">
<div className="messages">
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
</div>

<div className="input-area">
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
disabled={loading}
placeholder="Type your message..."
/>
<button onClick={sendMessage} disabled={loading}>
{loading ? 'Sending...' : 'Send'}
</button>
</div>
</div>
);
}

Node.js Backend Integration

const express = require('express');
const axios = require('axios');

const app = express();
app.use(express.json());

app.post('/api/chat', async (req, res) => {
try {
const { message, chatId, userId } = req.body;

const response = await axios.post('https://api.optimly.io/external/agent/v2', {
chat_id: chatId,
content: message,
metadata: {
client_id: userId,
source: 'backend_api'
}
}, {
headers: {
'Authorization': `Bearer ${process.env.OPTIMLY_ACCESS_TOKEN}`,
'Content-Type': 'application/json'
},
timeout: 30000
});

res.json(response.data);
} catch (error) {
console.error('Optimly API error:', error.response?.data || error.message);
res.status(500).json({
error: 'Failed to process message',
detail: error.response?.data?.detail || 'Internal server error'
});
}
});

Differences from v1

The v2 endpoint provides several enhancements over the legacy v1 endpoint:

Featurev1v2
Tool Auto-executionManualAutomatic
Knowledge IntegrationBasicEnhanced with vector search
Context ManagementLimitedFull conversation context
Error HandlingBasicComprehensive with details
Handoff SupportNoneAutomatic email handoffs
Response MetadataMinimalDetailed processing info

Rate Limits

  • 100 requests per minute per access token
  • 1000 requests per hour per access token
  • Burst allowance of 20 requests in 10 seconds

When rate limits are exceeded, you'll receive a 429 status code with retry information in the headers.

Next Steps