Artifact metadata

Stored reference for a generated output.

CreatedApr 15, 11:55 PM
RunReport Indexer index run
Reference/artifacts/artifact_gemsearch_90b39d59dad1fe78
Storageaddyco-artifacts/gemsearch/reports/2026-04-15_23-55-06_give-me-code-examples-of-memory-in-openai-agents-js.md
Hash90b39d59dad1fe781c5002d691b3690122b45889486f87690ed4345c61dfbaac
Modelgemini-3.1-pro-preview

Preview

Stored report content from Supabase Storage.

# Search: give me code examples of memory in openai-agents-js > Wednesday, April 15, 2026 · `gemini-3.1-pro-preview` ## Findings **Memory in `openai-agents-js`** (`@openai/agents`) operates on the philosophy of being minimal and lightweight. Unlike some framework abstractions that try to natively map and orchestrate your database schemas, OpenAI's JS/TS Agents SDK leaves long-term memory to the developer, while providing robust primitives for handling short-term conversation context, chaining history across agent handoffs, and utilizing server-managed states. Here is a comprehensive breakdown of how memory works in the SDK and how to implement it. --- ### What It Is & Key Features As of **version 0.8.3 (April 2026)**, memory in the `@openai/agents` SDK is primarily managed through these core features: 1. **Short-Term Context (`result.history`)**: Every time you call the `run()` function, it returns a `history` array. This array contains the full log of exchanges (user inputs, agent outputs, and executed tool calls). 2. **Context Chaining**: By passing the `history` array from one agent's output as the input to a different agent, you immediately share the full context of the conversation. 3. **Server-Managed State**: You can opt to use the OpenAI Responses API's built-in `conversationId` or `previousResponseId` to reuse server-side state. This minimizes payload sizes and latency, so you don't have to send the entire token history on every API request. 4. **Tool-Augmented Long-Term Memory**: The SDK encourages developers to implement long-term memory (e.g., saving user preferences) by providing "Tools" to the agent that write to persistent storage. --- ### Code Examples #### 1. Short-Term Memory (Multi-Turn Conversations) To maintain an ongoing conversation, you extract the `history` property from the first execution and append your next prompt using the SDK's `user()` helper function. ```typescript import { Agent, run, user } from '@openai/agents'; const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful and conversational assistant.', }); async function main() { // Turn 1: Initial conversation const result1 = await run(agent, 'Hi, I am Alice and I love drinking espresso.'); console.log('Agent:', result1.finalOutput); // Turn 2: Re-inject history to persist short-term memory // We spread the previous history array and append the new user message. const nextInput = [ ...result1.history, user('Do you remember my name and what coffee I like?') ]; const result2 = await run(agent, nextInput); console.log('Agent:', result2.finalOutput); } main(); ``` #### 2. Chaining Agents (Handoff Memory) You can easily pass the memory context from one specialized agent to another. This is highly useful for workflows where Agent A gathers information and Agent B executes a task. ```typescript import { Agent, run, user } from '@openai/agents'; const supportAgent = new Agent({ name: 'SupportTriage', instructions: 'Gather the user\'s support issue.', }); const billingAgent = new Agent({ name: 'BillingSpecialist', instructions: 'Resolve billing issues using the provided context.', }); async function workflow() { // 1. First agent gathers context const triageResult = await run(supportAgent, 'I was double-charged for my pro subscription this month.'); // 2. We pass the triage history to the Billing Agent + an explicit instruction const billingInput = [ ...triageResult.history, user('Please review the above support context and issue a refund.') ]; const billingResult = await run(billingAgent, billingInput); console.log('Billing Agent:', billingResult.finalOutput); } ``` #### 3. Long-Term Persistent Memory (Via Tools) The SDK does not have a native vector-database abstraction. To implement long-term memory (e.g., for users returning days later), you create a `Tool` that interacts with your own database (like PostgreSQL, MongoDB, or Cloudflare Durable Objects). ```typescript import { Agent, Tool, run } from '@openai/agents'; import { z } from 'zod'; // Tool that allows the agent to actively save facts to your DB const saveMemoryTool = new Tool({ name: 'save_user_preference', description: 'Use this tool to save important user preferences into long-term memory.', schema: z.object({ key: z.string().describe("The preference category (e.g., 'dietary', 'travel')"), value: z.string().describe("The specific user preference") }), async execute({ key, value }) { // Logic to save to your database (e.g., Prisma, Drizzle, MongoDB) // await db.preferences.upsert({ key, value }); return `Successfully saved ${key}: ${value}`; } }); const personalAgent = new Agent({ name: 'Concierge', instructions: 'You are a personal concierge. Whenever a user states a personal preference, use the save_user_preference tool to remember it for future sessions.', tools: [saveMemoryTool] }); ``` --- ### Current Status and Community Alternatives - **Current Architecture:** As of April 2026, the `openai-agents-js` framework embraces a **"Bring Your Own Data Layer"** methodology. It strictly manages the agent loop, handoffs, and LLM reasoning, but expects you to manage session storage. - **Server-Managed Conversations**: For production apps, developers increasingly use the underlying OpenAI Responses API to pass `conversationId` or `previousResponseId`, forcing the OpenAI servers to handle the history state so that edge-compute apps don't have to ferry massive context windows back and forth over the wire. - **Community Extensions (`@stackone/openai-agents-js-sessions`)**: Because the Python version of the SDK has built-in database session adapters that the JS version natively lacks, the open-source community created the `@stackone/openai-agents-js-sessions` package. This allows you to attach SQLite, PostgreSQL, or MySQL (via Drizzle ORM) directly to the JS agent for automatic historical tracking. **Competing Frameworks:** If you require deeply integrated memory components (such as automated RAG, built-in vector store chunking, and complex subgraph checkpoints), you might prefer heavier alternatives like **LangGraph.js** or **Mastra**. The OpenAI Agents SDK is intentionally barebones to prioritize determinism and speed. ## Sources 1. dev.to 2. team400.ai 3. npmjs.com 4. codesignal.com 5. github.io 6. mfun.ink 7. github.com 8. reddit.com --- *Search queries: " openai-agents-js", ""openai-agents" npm", "npm "openai-agents-js"", ""openai-agents-js" memory", ""@openai/agents" history array", ""openai-agents-js" "Sessions"", ""@openai/agents" session memory"*