Vercel AI SDK Integration
Learn how to integrate TraceMem with the Vercel AI SDK to enable decision tracking, memory, and governance for your AI agents.
Overview
The @tracemem/vercel-ai package provides a seamless integration between the Vercel AI SDK and TraceMem, enabling your agents to:
- Create and track decisions autonomously during conversation turns
- Store and retrieve context to maintain long-term memory across sessions
- Evaluate actions against policies before execution
- Request human approval for sensitive operations
- Maintain a complete audit trail of agent reasoning and tool usage
This integration is essential for building production-grade agents that require accountability, safety, and persistent memory.
Prerequisites
Before installing the package, ensure you have:
- Vercel AI SDK - An existing project using the Vercel AI SDK
- A TraceMem account - Sign up at app.tracemem.com
- An Agent API key - Generate one from your TraceMem project settings
Installation
Step 1: Install the Package
Install the integration package along with its dependencies:
npm install @tracemem/vercel-ai @tracemem/ts-sdk zod
Step 2: Configure Environment
Set your TraceMem API key as an environment variable in your .env.local or .env file:
TRACEMEM_API_KEY=your_api_key_here
Important: Never commit your API key to version control.
Recommended Workflow
The integration allows agents to interact with TraceMem tools naturally. Here is the recommended pattern for your system prompt:
1. Initialize Tools
In your route handler (e.g., app/api/chat/route.ts), import and configure the tools:
import { createTraceMemTools } from '@tracemem/vercel-ai';
const tools = createTraceMemTools({
apiKey: process.env.TRACEMEM_API_KEY,
// Optional: Default settings
defaults: {
automationMode: 'propose'
}
});
2. Instruct the Agent
Update your system prompt to guide the agent on how to use the TraceMem tools:
"You are an intelligent agent. When starting a complex task, use 'tracememOpen' to create a decision context. Always capture the returned 'decisionId' and pass it to subsequent tools (tracememNote, tracememRead, etc.). Close the decision with 'tracememClose' when finished."
Auto-Intent Mapping
The tracememOpen tool accepts an action parameter which the SDK automatically maps to a standardized intent. This simplifies the agent's decision-making process.
| Action | Intent |
|---|---|
refactor | code.refactor.execute |
investigate | ops.incident.investigate |
plan | planning.execution.propose |
deploy | deploy.release.execute |
Example
The agent calls:
tracememOpen({ action: "refactor" })
This is automatically mapped to the code.refactor.execute intent.
Available Tools
The package exports a set of Zod-validated tools ready for the Vercel AI SDK.
Lifecycle Tools
-
tracememOpen(action, intent?)
Starts a new decision envelope. Returns{ decisionId }. -
tracememClose(decisionId, outcome, reason?)
Finalizes the decision with an outcome (commitorabort).
Context & Memory Tools
-
tracememNote(decisionId, message, kind?, data?)
Adds a thought, observation, or reasoning note to the decision history. -
tracememRead(decisionId, product, purpose, query?)
Reads data from a product integration (e.g., fetching a file, querying a database) within the decision context. -
tracememTrace(decisionId)
Retrieves the current trace/history of the decision.
Governance Tools
-
tracememEvaluate(decisionId, policy, inputs)
Evaluates a set of inputs against a specific policy to check for compliance. -
tracememRequestApproval(decisionId, message)
Pauses execution to request human approval for the decision. -
tracememWrite(decisionId, product, purpose, mutation)
Proposes or executes a mutation (write operation) on a product.
Discovery Tools
tracememProductsList(purpose?)- List available products.tracememProductGet(name)- Get details for a specific product.tracememCapabilities()- Check server capabilities.
Context Injection
You can inject application-specific context (like User ID, Session ID, or Route) into every TraceMem tool call using the context provider. This ensures every decision is properly attributed.
const tools = createTraceMemTools({
apiKey: process.env.TRACEMEM_API_KEY,
context: async ({ tool, args }) => ({
userId: 'user_123',
sessionUrl: '/chats/session_abc',
metadata: {
source: 'vercel-ai-agent'
}
})
});
The injected context is merged into the decision metadata automatically.
Security
Secret Redaction
The integration includes automatic secret redaction to prevent sensitive data from leaking into your decision history.
- Redacted keys: Keys matching patterns like
token,secret,password,keyare automatically redacted from tool inputs. - Sanitization: Applied to
metadata,notes, andfunction argumentsbefore they are sent to the TraceMem API.
You can disable this behavior by setting sanitize: false in the configuration, though it is not recommended.
Example Workflow
Here represents a typical conversation flow handled by the tools:
- User: "Please refactor the login component to use hooks."
- Agent: Calls
tracememOpen({ action: 'refactor' })-> getsdecisionId: "dec_123". - Agent: Calls
tracememNote({ decisionId: "dec_123", message: "Analyzing current component structure." }). - Agent: Calls
tracememRead({ decisionId: "dec_123", product: "repo", purpose: "read_file", query: { path: "Login.tsx" } }). - Agent: Calls
tracememEvaluate({ decisionId: "dec_123", policy: "code_style", inputs: { ... } }). - Agent: Calls
tracememClose({ decisionId: "dec_123", outcome: "commit" }).
Troubleshooting
Tool Call Failures
If the agent fails to call tools correctly:
- Check System Prompt: Ensure you explicitly instruct the agent to pass the
decisionIdreturned bytracememOpento all other tools. The Vercel AI SDK integration is stateless and requires this ID for continuity. - Verify API Key: Ensure
TRACEMEM_API_KEYis set and valid. - Check Console Logs: The integration logs warnings if the context provider fails, but otherwise bubbles up errors from the TraceMem SDK.
"Decision ID not found"
If you receive errors about invalid decision IDs:
- The agent may be hallucinating an ID.
- The decision may have been closed.
- Ensure the agent waits for the result of
tracememOpenbefore calling other tools.