Pattern
INT·Jun 26
PrepareStep: Trim Message History
Demonstrate ToolLoopAgent prepareStep for trimming long message history. Pre-seeded 24-message conversation shows context compression on the first run with per-step trim telemetry.
View Full Pattern on Desktop

Problems Solved
- Prevent unbounded message history growth in agent loops
- Trim conversation context before each agent step
- Keep recent tool results while dropping stale turns
- Observe prepareStep compression with per-step telemetry
Use Cases
- Long-running agent loops with many tool calls
- Context window budget management
- Production agents that must cap history size
- Debugging what the model sees each step
AI SDK APIs
ToolLoopAgentprepareStepstepCountIstoolgateway
Tags
aiagentsprepare-stepcontext-windowmessage-trimmingtool-loop-agentai-sdkagent-api
Requirements
- Node.js
- 24+
- Memory
- 512MB
- Other
- OpenAI API key
Environment Variables
OPENAI_API_KEYGet key →
External Services
openai
Ready to use?
View the full interactive pattern with live preview and copy the source code.
View Pattern on DesktopRelated Patterns


Loop Control: stopWhen
Demonstrate ToolLoopAgent loop control with stopWhen. Covers stepCountIs, hasToolCall, combined conditions, and a custom StopCondition with step timeline visualization.
aiagents+7
View →


Tool Context: experimental_context
Inject request-scoped context (user identity, database handles, session) into ToolLoopAgent tools via experimental_context, so the model never supplies sensitive identity in tool inputs.
aiagents+7
View →
End of Pattern



