Appearance
Use Cases & Patterns
DialogueDB is designed for a wide range of conversational applications. This guide covers common use cases and implementation patterns to help you build robust AI-powered experiences.
AI Chatbots
Build intelligent chatbots with persistent conversation history.
Basic Chatbot Pattern
typescript
import { DialogueDB } from 'dialogue-db';
import { generateAIResponse } from './your-llm-service';
const client = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY });
async function handleUserMessage(dialogueId: string | null, userInput: string) {
// Create new dialogue or use existing
let dialogue;
if (!dialogueId) {
dialogue = await client.dialogues.create({
message: {
role: 'system',
content: 'You are a helpful customer support assistant.'
}
});
dialogueId = dialogue.id;
}
// Store user message
await client.messages.create(dialogueId, {
role: 'user',
content: userInput
});
// Get conversation history for context
const { messages } = await client.dialogues.get(dialogueId);
// Generate AI response
const aiResponse = await generateAIResponse(messages);
// Store AI response
await client.messages.create(dialogueId, {
role: 'assistant',
content: aiResponse,
metadata: {
model: 'gpt-4',
timestamp: new Date().toISOString()
}
});
return { dialogueId, response: aiResponse };
}Stateful Chatbot
Track conversation state for complex interactions:
typescript
async function handleStatefulChat(dialogueId: string, userInput: string) {
// Get current dialogue with state
const dialogue = await client.dialogues.get(dialogueId);
const currentState = dialogue.state || {};
// Process intent
const intent = detectIntent(userInput);
// Update state based on conversation flow
let newState = { ...currentState };
if (intent === 'book_appointment') {
newState = {
...currentState,
flow: 'booking',
step: 'date_selection',
collectedData: {}
};
} else if (intent === 'provide_date' && currentState.flow === 'booking') {
newState = {
...currentState,
step: 'time_selection',
collectedData: {
...currentState.collectedData,
date: extractDate(userInput)
}
};
}
// Update dialogue state
await client.dialogues.update(dialogueId, {
state: newState
});
// Continue conversation based on state
const response = generateResponseForState(newState);
await client.messages.create(dialogueId, {
role: 'assistant',
content: response
});
return response;
}Customer Support
Provide contextual customer support with full conversation history.
Support Ticket Integration
typescript
async function createSupportTicket(userId: string, issue: string) {
// Create dialogue with metadata
const dialogue = await client.dialogues.create({
metadata: {
userId,
ticketId: generateTicketId(),
status: 'open',
priority: 'normal',
department: 'general'
},
tags: ['support', 'customer-inquiry'],
message: {
role: 'user',
content: issue
}
});
// Auto-respond with acknowledgment
await client.messages.create(dialogue.id, {
role: 'assistant',
content: 'Thank you for contacting support. A team member will assist you shortly.',
metadata: {
automated: true
}
});
return dialogue.id;
}
// Agent handoff
async function agentTakeover(dialogueId: string, agentId: string) {
// Update state to indicate human agent
await client.dialogues.update(dialogueId, {
state: {
handedOff: true,
agentId,
handoffTime: new Date().toISOString()
}
});
await client.messages.create(dialogueId, {
role: 'system',
content: `Agent ${agentId} has joined the conversation.`
});
}Multi-Channel Support
Track conversations across different channels:
typescript
async function handleMultiChannelMessage(
userId: string,
message: string,
channel: 'email' | 'chat' | 'phone' | 'social'
) {
// Find or create dialogue for user
const dialogues = await client.dialogues.list({
query: 'by-status',
status: 'active'
});
const userDialogue = dialogues.items.find(
d => d.metadata?.userId === userId
);
const dialogueId = userDialogue?.id || (
await client.dialogues.create({
metadata: { userId, channels: [channel] }
})
).id;
// Add message with channel info
await client.messages.create(dialogueId, {
role: 'user',
content: message,
metadata: {
channel,
timestamp: new Date().toISOString()
}
});
// Update channels list
const currentChannels = userDialogue?.metadata?.channels || [];
if (!currentChannels.includes(channel)) {
await client.dialogues.update(dialogueId, {
metadata: {
...userDialogue?.metadata,
channels: [...currentChannels, channel]
}
});
}
}Conversational Analytics
Track and analyze conversation patterns.
Conversation Metrics
typescript
async function analyzeDialogues(projectId: string) {
// Get all dialogues
const { items: dialogues } = await client.dialogues.list({
limit: 1000
});
// Calculate metrics
const metrics = {
totalDialogues: dialogues.length,
averageMessages: dialogues.reduce((sum, d) => sum + d.totalMessages, 0) / dialogues.length,
activeDialogues: dialogues.filter(d => d.status === 'active').length,
completedDialogues: dialogues.filter(d => d.status === 'ended').length,
averageThreads: dialogues.reduce((sum, d) => sum + (d.threadCount || 0), 0) / dialogues.length
};
return metrics;
}
// Sentiment analysis
async function analyzeSentiment(dialogueId: string) {
const { messages } = await client.dialogues.get(dialogueId);
const userMessages = messages.filter(m => m.role === 'user');
const sentiments = userMessages.map(msg => ({
messageId: msg.id,
sentiment: analyzeSentimentScore(msg.content),
timestamp: msg.created
}));
return {
dialogueId,
overallSentiment: calculateAverage(sentiments),
sentimentTrend: sentiments
};
}Multi-Turn Agent Workflows
Build complex agent interactions with conversation branching.
Agent Orchestration
typescript
async function multiAgentWorkflow(userQuery: string) {
// Create main dialogue
const mainDialogue = await client.dialogues.create({
message: {
role: 'user',
content: userQuery
},
metadata: {
workflow: 'multi-agent',
stage: 'orchestration'
}
});
// Route to specialized agents
const intent = classifyIntent(userQuery);
// Create thread for specific agent
const agentThread = await client.dialogues.create({
threadOf: mainDialogue.id,
metadata: {
agent: intent.agent,
specialization: intent.domain
},
message: {
role: 'system',
content: `You are a ${intent.agent} specialized in ${intent.domain}.`
}
});
// Agent processes request
const agentResponse = await processWithAgent(agentThread.id, userQuery);
// Store result in main dialogue
await client.messages.create(mainDialogue.id, {
role: 'assistant',
content: agentResponse,
metadata: {
generatedBy: intent.agent,
threadId: agentThread.id
}
});
return mainDialogue.id;
}Conversation Branching
Explore multiple conversation paths:
typescript
async function exploreAlternatives(originalDialogueId: string) {
// Get original conversation
const original = await client.dialogues.get(originalDialogueId);
const lastMessage = original.messages[original.messages.length - 1];
// Create alternative response threads
const alternatives = await Promise.all([
createAlternative(originalDialogueId, 'creative', lastMessage),
createAlternative(originalDialogueId, 'conservative', lastMessage),
createAlternative(originalDialogueId, 'detailed', lastMessage)
]);
return alternatives;
}
async function createAlternative(
parentId: string,
style: string,
lastMessage: any
) {
const thread = await client.dialogues.create({
threadOf: parentId,
metadata: {
responseStyle: style,
experimentId: generateExperimentId()
}
});
// Generate alternative response
const alternativeResponse = await generateWithStyle(lastMessage, style);
await client.messages.create(thread.id, {
role: 'assistant',
content: alternativeResponse,
metadata: { style }
});
return thread;
}Long-Running Conversations
Manage extended conversations efficiently.
Conversation Compacting
typescript
async function manageLongConversation(dialogueId: string) {
const dialogue = await client.dialogues.get(dialogueId);
// Check if conversation is getting long
if (dialogue.totalMessages > 50) {
// Compact conversation
const summary = await client.dialogues.action(dialogueId, 'compact');
// Create continuation with summary
const continuation = await client.dialogues.create({
threadOf: dialogueId,
state: {
previousSummary: summary,
continuationOf: dialogueId
},
message: {
role: 'system',
content: `Previous conversation summary: ${summary}`
}
});
// End original dialogue
await client.dialogues.action(dialogueId, 'end');
return continuation.id;
}
return dialogueId;
}Context Window Management
Keep conversations within LLM context limits:
typescript
async function getRecentContext(dialogueId: string, maxMessages: number = 20) {
const { messages } = await client.dialogues.get(dialogueId);
// Get most recent messages
const recentMessages = messages.slice(-maxMessages);
// If conversation is longer, include summary
if (messages.length > maxMessages) {
const summary = await client.dialogues.action(dialogueId, 'compact');
return {
summary,
recentMessages,
totalMessages: messages.length
};
}
return {
recentMessages,
totalMessages: messages.length
};
}Session Management
Handle user sessions and conversation resumption.
Session Persistence
typescript
async function getOrCreateSession(userId: string) {
// Find active dialogue for user
const { items } = await client.dialogues.list({
query: 'by-status',
status: 'active'
});
const userDialogue = items.find(d =>
d.metadata?.userId === userId &&
d.metadata?.sessionActive === true
);
if (userDialogue) {
// Resume existing session
return userDialogue.id;
}
// Create new session
const dialogue = await client.dialogues.create({
metadata: {
userId,
sessionActive: true,
sessionStart: new Date().toISOString()
}
});
return dialogue.id;
}
async function endSession(dialogueId: string) {
await client.dialogues.update(dialogueId, {
metadata: {
sessionActive: false,
sessionEnd: new Date().toISOString()
}
});
await client.dialogues.action(dialogueId, 'end');
}Next Steps
- Best Practices - Optimization and error handling
- Complete Examples - Full end-to-end implementations
- API Reference - Detailed endpoint documentation