Skip to main content

Overview

The createTurnHandler 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 onStep

Handler 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
Example:

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
Example:

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
How it works:
  • Tracks message indices to detect new messages
  • Extracts only new messages added in this step
  • Converts them to ConversationMessage format
  • Saves them to the store
Example:

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, use onStepFinish to save messages as they complete:

Error Handling

Handle errors from the turn handler using Effect operators:

Window Size Behavior

The windowSize parameter in getHistory controls conversation context:
Window size considerations:
  • 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

Save the user message before generating a response:
Let the turn handler automatically save assistant messages:
  • Chat interfaces: 10-20 messages
  • Q&A bots: 5-10 messages
  • Single queries: 0 messages
  • Complex tasks: 20-50 messages
Always provide fallback behavior for store errors:
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