Multi-turn Conversation
Maintain context across conversations so AI agents generate more relevant and continuous responses.
Overview
Multi-turn conversations allow your agent to remember previous exchanges, enabling more natural, context-aware interactions. This is essential for building chatbots, assistants, and any application requiring back-and-forth dialogue.
Basic Example
Pass conversation history via the messages array:
1import { MozaikAgent, MozaikRequest } from '@mozaik-ai/core'23const request: MozaikRequest = {4 messages: [5 { role: 'system', content: 'You are a coding assistant' },6 { role: 'user', content: 'How do I sort an array in TypeScript?' },7 { role: 'assistant', content: 'You can use the .sort() method...' }8 ],9 model: 'claude-haiku-4.5'10}1112const agent = new MozaikAgent(request)1314// The agent remembers the previous context15const response = await agent.act('Can you show me an example?')1617console.log(response)
Building Chat History
Here's a pattern for maintaining an ongoing conversation:
1import { MozaikAgent, MozaikRequest, Message } from '@mozaik-ai/core'23// Initialize conversation history4const history: Message[] = [5 { role: 'system', content: 'You are a helpful assistant.' }6]78async function chat(userMessage: string): Promise<string> {9 // Add user message to history10 history.push({ role: 'user', content: userMessage })1112 // Create agent with current history13 const request: MozaikRequest = {14 model: 'gpt-5',15 messages: history16 }1718 const agent = new MozaikAgent(request)19 const response = await agent.act()2021 // Add assistant response to history22 history.push({ role: 'assistant', content: response })2324 return response25}2627// Usage28await chat('What is TypeScript?')29await chat('How does it compare to JavaScript?') // Remembers context30await chat('Show me an example') // Continues the conversation
Message Roles
Mozaik supports three message roles:
system
Sets the behavior and personality of the assistant. Usually the first message in the conversation.
user
Represents messages from the user or the application requesting a response.
assistant
Represents previous responses from the AI. Include these to maintain context.
Managing Context Length
Warning
1// Simple approach: keep only recent messages2function trimHistory(history: Message[], maxMessages: number = 20): Message[] {3 // Always keep the system message4 const systemMessage = history.find(m => m.role === 'system')5 const otherMessages = history.filter(m => m.role !== 'system')67 // Keep only the most recent messages8 const recentMessages = otherMessages.slice(-maxMessages)910 return systemMessage11 ? [systemMessage, ...recentMessages]12 : recentMessages13}