Overview
ThecreateTurnHandler function creates a handler for managing multi-turn conversations. It automatically handles message persistence, history retrieval, and integrates seamlessly with the Vercel AI SDK.
Creating a Turn Handler
Parameters
object
required
Configuration for the turn handler
Effect<TurnHandler, StoreError, ConversationStore>
An Effect that provides a turn handler instance with three methods:
getHistory, saveUserMessage, and onStepHandler Methods
getHistory
Retrieve conversation history from the store.object
Optional parameters
Effect<ConversationMessage[], StoreError>
An Effect that resolves to an array of conversation messages, ordered chronologically
saveUserMessage
Save a user message to the conversation.Ai.ModelMessage
required
The user message to save (from AI SDK). Should have
role: 'user'.Effect<void, StoreError>
An Effect that resolves when the message is saved
onStep
Save assistant and tool messages from an AI SDK step.Ai.StepResult<TOOLS>
required
A step result from the AI SDK’s multi-step generation (from
onStepFinish callback)Effect<void, StoreError>
An Effect that resolves when all new messages from the step are saved
- Tracks message indices to detect new messages
- Extracts only new messages added in this step
- Converts them to
ConversationMessageformat - Saves them to the store
Complete Example
Here’s a full example showing all turn handler methods in action:Multi-Turn with Tools
The turn handler works seamlessly with tool calls:Streaming Responses
For streaming responses, useonStepFinish to save messages as they complete:
Error Handling
Handle errors from the turn handler using Effect operators:Window Size Behavior
ThewindowSize parameter in getHistory controls conversation context:
- Larger windows = more context but higher token costs
- Smaller windows = less context but faster and cheaper
- Default of 10 works well for most conversations
- Set to 0 for one-shot queries without history
Best Practices
Always save user messages first
Always save user messages first
Save the user message before generating a response:
Use onStepFinish for automatic saving
Use onStepFinish for automatic saving
Let the turn handler automatically save assistant messages:
Adjust window size based on use case
Adjust window size based on use case
- Chat interfaces: 10-20 messages
- Q&A bots: 5-10 messages
- Single queries: 0 messages
- Complex tasks: 20-50 messages
Handle errors gracefully
Handle errors gracefully
Always provide fallback behavior for store errors:
Create one handler per conversation
Create one handler per conversation
Don’t reuse handlers across different conversations:
Next Steps
Conversation Store
Understand the underlying storage interface
Messages
Learn about message types and utilities
Drizzle Provider
Set up PostgreSQL storage
Examples
See complete implementations