Conversations
Code Examples
Practical examples for working with conversations
Complete API Client
JavaScript/Node.js
const axios = require('axios')
class ConversationsAPI {
constructor(keyId, keySecret) {
this.credentials = { keyId, keySecret }
this.baseURL = 'https://api.performchat.com/rest/v1'
}
async list(page = 1, limit = 20) {
const response = await axios.get(`${this.baseURL}/conversations`, {
params: { page, limit },
data: this.credentials
})
return response.data
}
async get(conversationId) {
const response = await axios.get(
`${this.baseURL}/conversations/${conversationId}`,
{ data: this.credentials }
)
return response.data
}
async getMessages(conversationId, page = 1, limit = 50) {
const response = await axios.get(
`${this.baseURL}/conversations/${conversationId}/messages`,
{
params: { page, limit },
data: this.credentials
}
)
return response.data
}
async exportConversation(conversationId) {
const allMessages = []
let page = 1
let hasMore = true
let conversation = null
while (hasMore) {
const result = await this.getMessages(conversationId, page)
allMessages.push(...result.data)
conversation = result.conversation
hasMore = page < result.pagination.total_pages
page++
}
return { conversation, messages: allMessages }
}
async exportAll() {
const allConversations = []
let page = 1
let hasMore = true
while (hasMore) {
const result = await this.list(page, 100)
allConversations.push(...result.data)
hasMore = page < result.pagination.total_pages
page++
}
return allConversations
}
}
// Usage
const api = new ConversationsAPI(
process.env.API_KEY_ID,
process.env.API_KEY_SECRET
)
const conversations = await api.list(1, 10)
const fullConv = await api.exportConversation('conv_123')Python
import os
import requests
from typing import Dict, List
class ConversationsAPI:
def __init__(self, key_id: str, key_secret: str):
self.credentials = {
"keyId": key_id,
"keySecret": key_secret
}
self.base_url = "https://api.performchat.com/rest/v1"
def list(self, page: int = 1, limit: int = 20) -> Dict:
response = requests.get(
f"{self.base_url}/conversations",
params={"page": page, "limit": limit},
json=self.credentials
)
response.raise_for_status()
return response.json()
def get(self, conversation_id: str) -> Dict:
response = requests.get(
f"{self.base_url}/conversations/{conversation_id}",
json=self.credentials
)
response.raise_for_status()
return response.json()
def get_messages(
self,
conversation_id: str,
page: int = 1,
limit: int = 50
) -> Dict:
response = requests.get(
f"{self.base_url}/conversations/{conversation_id}/messages",
params={"page": page, "limit": limit},
json=self.credentials
)
response.raise_for_status()
return response.json()
def export_conversation(self, conversation_id: str) -> Dict:
all_messages = []
page = 1
conversation = None
while True:
result = self.get_messages(conversation_id, page)
all_messages.extend(result['data'])
conversation = result['conversation']
if page >= result['pagination']['total_pages']:
break
page += 1
return {
"conversation": conversation,
"messages": all_messages
}
def export_all(self) -> List[Dict]:
all_conversations = []
page = 1
while True:
result = self.list(page, 100)
all_conversations.extend(result['data'])
if page >= result['pagination']['total_pages']:
break
page += 1
return all_conversations
# Usage
api = ConversationsAPI(
os.getenv("API_KEY_ID"),
os.getenv("API_KEY_SECRET")
)
conversations = api.list(page=1, limit=10)
full_conv = api.export_conversation("conv_123")Common Use Cases
Export to JSON
const fs = require('fs')
async function exportConversationsToJSON() {
const conversations = await api.exportAll()
// Get full data for each conversation
for (const conv of conversations) {
const full = await api.exportConversation(conv.id)
conv.messages = full.messages
}
fs.writeFileSync(
'conversations.json',
JSON.stringify(conversations, null, 2)
)
console.log(`Exported ${conversations.length} conversations`)
}Export to CSV
async function exportToCSV() {
const conversations = await api.exportAll()
const csv = [
['ID', 'Title', 'User ID', 'Messages', 'Created', 'Updated'].join(','),
...conversations.map(c =>
[
c.id,
`"${c.title}"`,
c.customer_user_id,
c.message_count,
c.created_at,
c.updated_at
].join(',')
)
].join('\n')
fs.writeFileSync('conversations.csv', csv)
}Analytics Dashboard
async function getConversationStats() {
const conversations = await api.exportAll()
const now = new Date()
const oneDayAgo = new Date(now - 24 * 60 * 60 * 1000)
const oneWeekAgo = new Date(now - 7 * 24 * 60 * 60 * 1000)
return {
total: conversations.length,
totalMessages: conversations.reduce((sum, c) => sum + c.message_count, 0),
last24h: conversations.filter(c =>
new Date(c.created_at) > oneDayAgo
).length,
lastWeek: conversations.filter(c =>
new Date(c.created_at) > oneWeekAgo
).length,
avgMessagesPerConv: conversations.reduce((sum, c) => sum + c.message_count, 0) / conversations.length
}
}Search Across All Conversations
async function searchAllConversations(searchTerm) {
const conversations = await api.exportAll()
const results = []
for (const conv of conversations) {
const { messages } = await api.exportConversation(conv.id)
const matchingMessages = messages.filter(msg =>
msg.content.toLowerCase().includes(searchTerm.toLowerCase())
)
if (matchingMessages.length > 0) {
results.push({
conversation: conv,
matches: matchingMessages
})
}
}
return results
}User Conversation History
async function getUserConversationHistory(customerUserId) {
const allConversations = await api.exportAll()
const userConversations = allConversations
.filter(c => c.customer_user_id === customerUserId)
.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
// Get full data for each
for (const conv of userConversations) {
const full = await api.exportConversation(conv.id)
conv.messages = full.messages
}
return userConversations
}Generate Conversation Report
async function generateConversationReport(conversationId) {
const { conversation, messages } = await api.exportConversation(conversationId)
const userMessages = messages.filter(m => m.role === 'user')
const assistantMessages = messages.filter(m => m.role === 'assistant')
const duration = new Date(messages[messages.length - 1].created_at) -
new Date(messages[0].created_at)
return {
id: conversation.id,
title: conversation.title,
stats: {
totalMessages: messages.length,
userMessages: userMessages.length,
assistantMessages: assistantMessages.length,
avgMessageLength: messages.reduce((sum, m) => sum + m.content.length, 0) / messages.length,
durationMs: duration,
durationMinutes: Math.floor(duration / 60000)
},
transcript: messages.map(m => ({
role: m.role,
content: m.content,
time: new Date(m.created_at).toLocaleString()
}))
}
}Backup System
async function backupConversations() {
const timestamp = new Date().toISOString().split('T')[0]
const conversations = await api.exportAll()
console.log(`Backing up ${conversations.length} conversations...`)
// Export with full messages
for (let i = 0; i < conversations.length; i++) {
const conv = conversations[i]
console.log(`Exporting ${i + 1}/${conversations.length}: ${conv.id}`)
const full = await api.exportConversation(conv.id)
conv.messages = full.messages
}
const filename = `backup-${timestamp}.json`
fs.writeFileSync(filename, JSON.stringify(conversations, null, 2))
console.log(`Backup saved to ${filename}`)
return {
filename,
conversationCount: conversations.length,
totalMessages: conversations.reduce((sum, c) => sum + c.messages.length, 0)
}
}Error Handling
async function safeGetConversation(conversationId) {
try {
return await api.get(conversationId)
} catch (error) {
if (error.response?.status === 404) {
console.error(`Conversation ${conversationId} not found`)
return null
} else if (error.response?.status === 401) {
throw new Error('Invalid API credentials')
} else {
console.error('Unexpected error:', error.message)
throw error
}
}
}Related Pages
- List Conversations - API reference for listing conversations
- Get Conversation - API reference for getting a conversation
- Get Messages - API reference for getting messages