--- title: "Memory for the Vercel AI SDK" description: "The @pastdotdev/ai-sdk package adds memory to the Vercel AI SDK: recall and ingest tools, a middleware that recalls before each model call, and a small client." canonical: https://past.dev/integrations/vercel-ai-sdk last-updated: 2026-10-28 --- # Add memory to the Vercel AI SDK Source: https://past.dev/integrations/vercel-ai-sdk The Vercel AI SDK runs the agent loop and leaves memory to the application. The `@pastdotdev/ai-sdk` package adds it in three ways. `pastTools({ identity })` gives the model `recall` and `ingest` tools. `pastRecallMiddleware({ identity })` adds recalled memory to the prompt of every model call. `createPastClient()` calls ingest, recall and `deleteDataPoint` from your own code. Your code passes the signed-in user's id as `identity`, and no tool schema has an identity field. ## Vercel AI SDK memory scope The [AI SDK](https://ai-sdk.dev/docs/agents) treats an agent as a model calling tools in a loop, with `ToolLoopAgent` managing the loop, the message array and the stopping conditions for one run. Persistence sits with the application: the [message persistence guide](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence) has you implement chat saving and loading against your own database. For memory beyond the transcript, the [memory guide](https://ai-sdk.dev/docs/agents/memory) states that the SDK provides no native memory persistence and documents three approaches: provider-defined tools, external memory providers and custom tools. The package below is a memory provider with tools. - `useChat` manages client-side message state; storing and reloading chats is application code in your route handlers. - `runtimeContext` carries shared state through one agent loop, for `prepareStep` and lifecycle callbacks. It is run-scoped state rather than durable memory. - A saved transcript is raw text: nothing in it dates a fact or marks which value is current. ## Install the package ```bash npm install @pastdotdev/ai-sdk ai zod export PAST_API_KEY=past_sk_... ``` It works with AI SDK 7, any model provider, Node 20 or later, and edge runtimes that have `fetch`. Create the project key in the [past.dev console](https://app.past.dev) under **Build › API keys**. The package is [@pastdotdev/ai-sdk on npm](https://www.npmjs.com/package/@pastdotdev/ai-sdk), and its source and README are in the [pastdotdev/ai-sdk repository](https://github.com/pastdotdev/ai-sdk). ## Give the model recall and ingest tools ```typescript import { generateText, isStepCount } from 'ai'; import { pastTools } from '@pastdotdev/ai-sdk'; const { text } = await generateText({ model: 'openai/gpt-5-mini', tools: pastTools({ identity: user.id }), stopWhen: isStepCount(5), prompt: 'Remember that my favourite editor is Neovim.', }); ``` `user` is the signed-in user from your own session. A `ToolLoopAgent` takes the same `tools` option. Make the tools for each request, with that request's user. | Tool | API call | What the model fills | | --- | --- | --- | | `recall` | `POST /api/v1/recall` | `query` | | `ingest` | `POST /api/v1/ingest` | `content`, and optionally `timestamp` (ISO 8601) and `label` | `recall` gives the model one numbered line per memory with its date, a mark when a later statement replaced it, and up to two quotes from its sources. Set `modelOutput: 'json'` to give the model the API's JSON instead. `ingest` gives each call a new source id and uses it as the idempotency key, so a retry never saves a second data point. Options set the `audience` of each ingest, `metadata` the model never sees, and the recall `limit`, `level` or `maxTokens`. ## Recall before every model call The middleware recalls with the last user message as the query before each model call, and adds the memories as one system message after your own. It needs no tool call from the model. ```typescript import { gateway, streamText, wrapLanguageModel } from 'ai'; import { pastRecallMiddleware } from '@pastdotdev/ai-sdk'; const model = wrapLanguageModel({ model: gateway('openai/gpt-5-mini'), middleware: pastRecallMiddleware({ identity: user.id }), }); const result = streamText({ model, prompt: 'What did we decide about the launch date?' }); ``` By default it adds at most 5 memories from a 1,000-token evidence budget, leaves out memories a later statement replaced, and marks the block as notes for the model rather than instructions. When nothing matches or the recall fails, it adds nothing and the model call goes on. It only reads: write with the `ingest` tool or the client. ## Call the API from your own code ```typescript import { createPastClient } from '@pastdotdev/ai-sdk'; const past = createPastClient(); // PAST_API_KEY, PAST_API_HOST await past.listAudiences(); // free: a good connection test await past.ingest({ content: 'Order 1042 shipped.', identity: user.id, id: 'order-1042' }); await past.recall({ query: 'order 1042', identity: user.id }); await past.deleteDataPoint('order-1042'); // the data point and the memory derived from it await past.listIdentities({ limit: 100 }); // paged with hasMore and endCursor ``` An API error is a `PastApiError` with `code`, `status`, `debugMessage` and `requestId`. Inside a tool, the AI SDK hands the error to the model as a tool error and the loop goes on. A `429` is retried at most twice, after its `Retry-After` time, and no other error is retried. > **Identity** > > The application sets the identity. The model never chooses it. Recall returns what the identity in the request may read, so take the identity from the signed-in user in code, and keep it out of every value that the model fills. ## Or connect the MCP server `createMCPClient` from `@ai-sdk/mcp` connects with the `http` transport, and `tools()` returns the server's tools for `generateText` or `streamText` ([MCP tools](https://ai-sdk.dev/docs/ai-sdk-core/mcp-tools)). Close the client when the response is complete. The project's end-user MCP server then gives the agent `recall`, `answer` and `who_am_i`, plus `remember` while the project's write toggle is on, with no tool code to write. 1. Turn on the project's end-user MCP server on **Build › MCP server** in the console. 2. Mint an access link there, or with the account server's `create_mcp_access_link` tool. The link has the form `https://api.past.dev/mcp//link/`. It is one URL that is one identity, and the server answers it with no sign-in step. 3. Keep the link in a secret store, such as the `PAST_MCP_URL` environment variable that the code below reads. The secret in its path is the credential. ```typescript import { createMCPClient } from "@ai-sdk/mcp"; import { generateText } from "ai"; const past = await createMCPClient({ transport: { type: "http", url: process.env.PAST_MCP_URL! }, }); try { const { text } = await generateText({ model, // any AI SDK model tools: await past.tools(), prompt: "What did we decide about the Q4 budget?", }); console.log(text); } finally { await past.close(); } ``` Every call through the link runs as its identity, with that identity's audiences. Mint one link per install, so that a revoked link stops one agent only. When the agent serves several people, mint one link per end user, and connect each request with the link of the user who makes it. Never share one link between users. `remember` writes to the identity's own private audience, and only that identity recalls it. Send data that the whole project must recall through the ingest call. The [end-user server documentation](/docs/mcp/serving-your-own-users) describes the tools, the links and revocation. ## When to use which layer | Requirement | Chat persistence you build | @pastdotdev/ai-sdk | | --- | --- | --- | | Resume a conversation in useChat | Yes | No | | Facts shared across chats, users and apps | Only by rereading transcripts | One recall call | | Current value after a change | The model rereads the transcript | Replaced statements are marked | | Backfilled history on original dates | No | Timestamped ingestion | | Recall result | Provider-specific | Ranked memories with dates and source excerpts | Recall returns ranked documents with dates and source excerpts. The application decides whether those documents support an answer, contain a disagreement, or are insufficient; HTTP failures are handled separately. The [quickstart](/docs/memory-api/quickstart) shows how to ingest, wait until ingestion completes, and recall. The [benchmarks](/benchmarks) document how recall is measured, and [choosing a memory system](/guides/choose-memory-system) compares the wider field of options. ## Frequently asked questions ### Does the Vercel AI SDK have built-in memory? No. The AI SDK documents memory as something the application adds through provider-defined tools, an external memory provider, or custom tools. Chat history persistence is also implemented by the application. ### Should I use the tools or the middleware? Use the middleware when every model call should see relevant memory without the model asking for it. Use the tools when the model decides when to look something up and what to save. You can use both. ### Does this work with useChat and streamText? Yes. The tools and the middleware run in your route handler wherever generateText or streamText runs, and useChat on the client doesn't change. ## Related - [Memory for the OpenAI Agents SDK](https://past.dev/integrations/openai-agents-sdk) - [Memory for LangChain](https://past.dev/integrations/langchain) - [Memory for Mastra](https://past.dev/integrations/mastra) - [Memory for Zapier](https://past.dev/integrations/zapier) - [Cross-session memory](https://past.dev/glossary/cross-session-memory) - [Quickstart](https://past.dev/docs/memory-api/quickstart)