|
| 1 | +--- |
| 2 | +title: Sessions |
| 3 | +description: Persist multi-turn conversation history so agents can resume context across runs. |
| 4 | +--- |
| 5 | + |
| 6 | +import { Code } from '@astrojs/starlight/components'; |
| 7 | +import sessionsQuickstart from '../../../../../examples/docs/sessions/basicSession.ts?raw'; |
| 8 | +import manageHistory from '../../../../../examples/docs/sessions/manageHistory.ts?raw'; |
| 9 | +import customSession from '../../../../../examples/docs/sessions/customSession.ts?raw'; |
| 10 | +import sessionInputCallback from '../../../../../examples/docs/sessions/sessionInputCallback.ts?raw'; |
| 11 | + |
| 12 | +Sessions give the Agents SDK a **persistent memory layer**. Provide any object that implements the `Session` interface to `Runner.run`, and the SDK handles the rest. When a session is present, the runner automatically: |
| 13 | + |
| 14 | +1. Fetches previously stored conversation items and prepends them to the next turn. |
| 15 | +2. Persists new user input and assistant output after each run completes. |
| 16 | +3. Keeps the session available for future turns, whether you call the runner with new user text or resume from an interrupted `RunState`. |
| 17 | + |
| 18 | +This removes the need to manually call `toInputList()` or stitch history between turns. The TypeScript SDK ships with two implementations: `OpenAIConversationsSession` for the Conversations API and `MemorySession`, which is intended for local development. Because they share the `Session` interface, you can plug in your own storage backend. For inspiration beyond the Conversations API, explore the sample session backends under `examples/memory/` (Prisma, file-backed, and more). |
| 19 | + |
| 20 | +> Tip: To run the `OpenAIConversationsSession` examples on this page, set the `OPENAI_API_KEY` environment variable (or provide an `apiKey` when constructing the session) so the SDK can call the Conversations API. |
| 21 | +
|
| 22 | +--- |
| 23 | + |
| 24 | +## Quick start |
| 25 | + |
| 26 | +Use `OpenAIConversationsSession` to sync memory with the [Conversations API](https://platform.openai.com/docs/api-reference/conversations), or swap in any other `Session` implementation. |
| 27 | + |
| 28 | +<Code |
| 29 | + lang="typescript" |
| 30 | + code={sessionsQuickstart} |
| 31 | + title="Use the Conversations API as session memory" |
| 32 | +/> |
| 33 | + |
| 34 | +Reusing the same session instance ensures the agent receives the full conversation history before every turn and automatically persists new items. Switching to a different `Session` implementation requires no other code changes. |
| 35 | + |
| 36 | +--- |
| 37 | + |
| 38 | +## How the runner uses sessions |
| 39 | + |
| 40 | +- **Before each run** it retrieves the session history, merges it with the new turn's input, and passes the combined list to your agent. |
| 41 | +- **After a non-streaming run** one call to `session.addItems()` persists both the original user input and the model outputs from the latest turn. |
| 42 | +- **For streaming runs** it writes the user input first and appends streamed outputs once the turn completes. |
| 43 | +- **When resuming from `RunResult.state`** (for approvals or other interruptions) keep passing the same `session`. The resumed turn is added to memory without re-preparing the input. |
| 44 | + |
| 45 | +--- |
| 46 | + |
| 47 | +## Inspecting and editing history |
| 48 | + |
| 49 | +Sessions expose simple CRUD helpers so you can build "undo", "clear chat", or audit features. |
| 50 | + |
| 51 | +<Code |
| 52 | + lang="typescript" |
| 53 | + code={manageHistory} |
| 54 | + title="Read and edit stored items" |
| 55 | +/> |
| 56 | + |
| 57 | +`session.getItems()` returns the stored `AgentInputItem[]`. Call `popItem()` to remove the last entry—useful for user corrections before you rerun the agent. |
| 58 | + |
| 59 | +--- |
| 60 | + |
| 61 | +## Bring your own storage |
| 62 | + |
| 63 | +Implement the `Session` interface to back memory with Redis, DynamoDB, SQLite, or another datastore. Only five asynchronous methods are required. |
| 64 | + |
| 65 | +<Code |
| 66 | + lang="typescript" |
| 67 | + code={customSession} |
| 68 | + title="Custom in-memory session implementation" |
| 69 | +/> |
| 70 | + |
| 71 | +Custom sessions let you enforce retention policies, add encryption, or attach metadata to each conversation turn before persisting it. |
| 72 | + |
| 73 | +--- |
| 74 | + |
| 75 | +## Control how history and new items merge |
| 76 | + |
| 77 | +When you pass an array of `AgentInputItem`s as the run input, provide a `sessionInputCallback` to merge them with stored history deterministically. The runner loads the existing history, calls your callback **before the model invocation**, and hands the returned array to the model as the turn’s complete input. This hook is ideal for trimming old items, deduplicating tool results, or highlighting only the context you want the model to see. |
| 78 | + |
| 79 | +<Code |
| 80 | + lang="typescript" |
| 81 | + code={sessionInputCallback} |
| 82 | + title="Truncate history with sessionInputCallback" |
| 83 | +/> |
| 84 | + |
| 85 | +For string inputs the runner merges history automatically, so the callback is optional. |
| 86 | + |
| 87 | +--- |
| 88 | + |
| 89 | +## Handling approvals and resumable runs |
| 90 | + |
| 91 | +Human-in-the-loop flows often pause a run to wait for approval: |
| 92 | + |
| 93 | +```typescript |
| 94 | +const result = await runner.run(agent, 'Search the itinerary', { |
| 95 | + session, |
| 96 | + stream: true, |
| 97 | +}); |
| 98 | + |
| 99 | +if (result.requiresApproval) { |
| 100 | + // ... collect user feedback, then resume the agent in a later turn |
| 101 | + const continuation = await runner.run(agent, result.state, { session }); |
| 102 | + console.log(continuation.finalOutput); |
| 103 | +} |
| 104 | +``` |
| 105 | + |
| 106 | +When you resume from a previous `RunState`, the new turn is appended to the same memory record to preserve a single conversation history. Human-in-the-loop (HITL) flows stay fully compatible—approval checkpoints still round-trip through `RunState` while the session keeps the transcript complete. |
0 commit comments