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:

multi-turn-basic.ts
1import { MozaikAgent, MozaikRequest } from '@mozaik-ai/core'
2
3const 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}
11
12const agent = new MozaikAgent(request)
13
14// The agent remembers the previous context
15const response = await agent.act('Can you show me an example?')
16
17console.log(response)

Building Chat History

Here's a pattern for maintaining an ongoing conversation:

chat-history.ts
1import { MozaikAgent, MozaikRequest, Message } from '@mozaik-ai/core'
2
3// Initialize conversation history
4const history: Message[] = [
5 { role: 'system', content: 'You are a helpful assistant.' }
6]
7
8async function chat(userMessage: string): Promise<string> {
9 // Add user message to history
10 history.push({ role: 'user', content: userMessage })
11
12 // Create agent with current history
13 const request: MozaikRequest = {
14 model: 'gpt-5',
15 messages: history
16 }
17
18 const agent = new MozaikAgent(request)
19 const response = await agent.act()
20
21 // Add assistant response to history
22 history.push({ role: 'assistant', content: response })
23
24 return response
25}
26
27// Usage
28await chat('What is TypeScript?')
29await chat('How does it compare to JavaScript?') // Remembers context
30await 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

AI models have token limits. For long conversations, you may need to truncate or summarize older messages to stay within limits.
context-management.ts
1// Simple approach: keep only recent messages
2function trimHistory(history: Message[], maxMessages: number = 20): Message[] {
3 // Always keep the system message
4 const systemMessage = history.find(m => m.role === 'system')
5 const otherMessages = history.filter(m => m.role !== 'system')
6
7 // Keep only the most recent messages
8 const recentMessages = otherMessages.slice(-maxMessages)
9
10 return systemMessage
11 ? [systemMessage, ...recentMessages]
12 : recentMessages
13}

Next Steps