Skip to main content

Conversations

Conversations are the container for ongoing dialogue between users and agents. Understanding how conversations work helps you build better experiences.

What is a Conversation?

A conversation is a sequence of messages between a user and an agent. It:

  • Maintains context across multiple messages
  • Has a unique identifier
  • Can be resumed later
  • Stores history and metadata
Conversation: conv-abc123
├── Message 1: User: "Hi, I need help with my VPN"
├── Message 2: Agent: "I'd be happy to help with your VPN..."
├── Message 3: User: "It says connection failed"
├── Message 4: Agent: "That error usually means..."
└── [continues...]

Starting a Conversation

New Conversation

// Automatically creates a new conversation
const response = await client.agents.chat({
agentId: 'agent-123',
message: 'Hello!'
});

console.log(response.conversationId); // conv-xyz789

With User Context

// Associate conversation with a user
const response = await client.agents.chat({
agentId: 'agent-123',
userId: 'user-456',
message: 'Hello!'
});

Continuing a Conversation

Resume with Conversation ID

// First message
const response1 = await client.agents.chat({
agentId: 'agent-123',
message: 'My name is Sarah'
});

// Continue the conversation
const response2 = await client.agents.chat({
agentId: 'agent-123',
conversationId: response1.conversationId,
message: 'What is my name?'
});

// Agent remembers: "Your name is Sarah"

Get Conversation History

const conversation = await client.conversations.get('conv-123');

console.log(conversation.messages);
// [
// { role: 'user', content: 'My name is Sarah' },
// { role: 'assistant', content: 'Nice to meet you, Sarah!' },
// { role: 'user', content: 'What is my name?' },
// { role: 'assistant', content: 'Your name is Sarah.' }
// ]

Conversation Lifecycle

┌─────────┐    ┌─────────┐    ┌─────────┐    ┌──────────┐
│ Created │───▶│ Active │───▶│ Idle │───▶│ Archived │
└─────────┘ └─────────┘ └─────────┘ └──────────┘
│ │
│ │
└──────────────┘
(new message)

States

StateDescriptionDuration
createdJust startedUntil first response
activeCurrently in useDuring conversation
idleNo recent activityAfter 30 min
archivedHistorical recordAfter 90 days

Automatic Transitions

  • Active → Idle: 30 minutes of no messages
  • Idle → Active: New message received
  • Idle → Archived: 90 days in idle state

Managing Conversations

List Conversations

// List user's conversations
const conversations = await client.conversations.list({
agentId: 'agent-123',
userId: 'user-456',
state: 'active',
limit: 20
});

End a Conversation

// Explicitly end a conversation
await client.conversations.end('conv-123');

// End with a summary
await client.conversations.end('conv-123', {
reason: 'Issue resolved',
summary: 'User had VPN connection issues. Resolved by reinstalling certificates.'
});

Delete a Conversation

// Permanently delete (cannot be undone)
await client.conversations.delete('conv-123');

Conversation Context

How Context is Built

Each message includes conversation history:

Message 5 sends to model:
┌─────────────────────────────────────────┐
│ System Prompt │
├─────────────────────────────────────────┤
│ Message 1: User: "Hi" │
│ Message 2: Agent: "Hello!" │
│ Message 3: User: "My VPN isn't working" │
│ Message 4: Agent: "Let me help..." │
│ Message 5: User: "It shows error 443" │
└─────────────────────────────────────────┘

Context Limits

Long conversations are automatically managed:

ScenarioAction
Under limitFull history sent
Near limitOlder messages summarized
At limitSummary + recent messages
// Check context usage
const conversation = await client.conversations.get('conv-123');
console.log(conversation.contextUsage);
// { tokens: 12500, maxTokens: 128000, percentage: 9.8 }

Manual Context Control

// Start fresh (no history)
const response = await client.agents.chat({
agentId: 'agent-123',
conversationId: null, // Forces new conversation
message: 'New topic'
});

// Provide custom context
const response = await client.agents.chat({
agentId: 'agent-123',
context: {
summary: 'User is having email sync issues on Outlook',
facts: ['Using Windows 11', 'Outlook 365', 'Started yesterday']
},
message: 'Any updates on my issue?'
});

Multi-Agent Conversations

Escalation

When an agent escalates, the conversation continues:

// Tier 1 agent escalates to Tier 2
// Conversation history is preserved

// User's view:
// User: "I need advanced help"
// Tier1: "Let me connect you with a specialist..."
// Tier2: "Hi, I'm a senior agent. I see you've been having..."

Handoff

// Transfer conversation to different agent
await client.conversations.handoff({
conversationId: 'conv-123',
toAgentId: 'specialist-agent',
summary: 'User needs help with advanced configuration',
preserveHistory: true
});

Conversation Metadata

Add Metadata

await client.conversations.update({
conversationId: 'conv-123',
metadata: {
ticketId: 'TICKET-001',
priority: 'high',
department: 'IT',
tags: ['vpn', 'connectivity']
}
});

Query by Metadata

const conversations = await client.conversations.list({
agentId: 'agent-123',
metadata: {
priority: 'high',
department: 'IT'
}
});

Conversation Events

Webhooks

Subscribe to conversation events:

await client.webhooks.create({
url: 'https://your-app.com/webhooks',
events: [
'conversation.started',
'conversation.message',
'conversation.ended',
'conversation.escalated'
]
});

Event Payload

{
"event": "conversation.message",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"conversationId": "conv-123",
"agentId": "agent-456",
"userId": "user-789",
"message": {
"role": "assistant",
"content": "I can help with that..."
},
"metadata": {
"tokensUsed": 150,
"toolsUsed": ["memory"]
}
}
}

Streaming Conversations

Real-time Responses

const stream = await client.agents.chat({
agentId: 'agent-123',
conversationId: 'conv-123',
message: 'Tell me about your services',
stream: true
});

for await (const chunk of stream) {
process.stdout.write(chunk.content);
}

Stream Events

stream.on('start', () => console.log('Response starting'));
stream.on('token', (token) => process.stdout.write(token));
stream.on('tool_call', (tool) => console.log('Using tool:', tool.name));
stream.on('end', () => console.log('Response complete'));

Analytics

Conversation Metrics

const analytics = await client.conversations.getAnalytics({
agentId: 'agent-123',
startDate: '2024-01-01',
endDate: '2024-01-31'
});

console.log({
totalConversations: analytics.total,
averageLength: analytics.avgMessages,
averageDuration: analytics.avgDurationMinutes,
resolutionRate: analytics.resolvedPercentage,
escalationRate: analytics.escalatedPercentage
});

Export Conversations

// Export for analysis
const export = await client.conversations.export({
agentId: 'agent-123',
startDate: '2024-01-01',
endDate: '2024-01-31',
format: 'json', // or 'csv'
includeMetadata: true
});

Best Practices

1. Use User IDs

Always associate conversations with users for:

  • Persistent memory across sessions
  • Analytics and tracking
  • Compliance and audit
// ✅ Good
await client.agents.chat({
agentId: 'agent-123',
userId: 'user-456', // Track the user
message: '...'
});

// ❌ Bad
await client.agents.chat({
agentId: 'agent-123',
// No user ID - can't track or personalize
message: '...'
});

2. Handle Long Conversations

// Check if conversation is getting long
if (conversation.contextUsage.percentage > 50) {
// Consider summarizing or starting fresh
await client.conversations.summarize('conv-123');
}

3. End Conversations Properly

// When issue is resolved
await client.conversations.end('conv-123', {
reason: 'resolved',
summary: 'User issue resolved',
satisfaction: 'positive'
});

// This helps with:
// - Analytics
// - Training data
// - Memory management

4. Use Metadata

// Tag conversations for easier management
await client.conversations.update({
conversationId: 'conv-123',
metadata: {
source: 'website-chat',
page: '/pricing',
campaign: 'q1-launch'
}
});

Next: Learn about Memory to understand persistent context across conversations.