Skip to content

Commit b54250c

Browse files
authored
docs: Add the Sessions feature document page (#627)
1 parent c9be6d8 commit b54250c

File tree

9 files changed

+596
-0
lines changed

9 files changed

+596
-0
lines changed

docs/astro.config.mjs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,15 @@ const sidebar = [
181181
ko: '컨텍스트 관리',
182182
},
183183
},
184+
{
185+
label: 'Sessions',
186+
link: '/guides/sessions',
187+
translations: {
188+
ja: 'セッション',
189+
zh: '会话',
190+
ko: '세션',
191+
},
192+
},
184193
{
185194
label: 'Models',
186195
link: '/guides/models',
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
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.
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
title: セッション
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+
セッションは Agents SDK による **永続的なメモリレイヤー** を提供します。`Session` インターフェースを実装する任意のオブジェクトを `Runner.run` に渡すだけで、残りは SDK が処理します。セッションがある場合、ランナーは自動的に次を行います:
13+
14+
1. 以前に保存された会話アイテムを取得し、次のターンの先頭に付加します
15+
2. 各実行完了後に、新しいユーザー入力とアシスタント出力を永続化します
16+
3. 新しいユーザーのテキストでランナーを呼び出す場合でも、中断された `RunState` から再開する場合でも、将来のターンにセッションを利用可能に保ちます
17+
18+
これにより、手動で `toInputList()` を呼び出したり、ターン間で履歴をつなぎ合わせたりする必要がなくなります。TypeScript SDK には 2 つの実装が同梱されています: Conversations API 用の `OpenAIConversationsSession` と、ローカル開発向けの `MemorySession` です。両者は `Session` インターフェースを共有するため、独自のストレージバックエンドを差し替えできます。Conversations API 以外のアイデアについては、`examples/memory/` 配下のサンプルセッションバックエンド(Prisma、ファイル永続など)を参照してください。
19+
20+
> ヒント: このページの `OpenAIConversationsSession` の例を実行するには、`OPENAI_API_KEY` 環境変数を設定する(またはセッション構築時に `apiKey` を指定する)ことで、SDK が Conversations API を呼び出せるようにしてください。
21+
22+
---
23+
24+
## クイックスタート
25+
26+
`OpenAIConversationsSession` を使用して [Conversations API](https://platform.openai.com/docs/api-reference/conversations) とメモリを同期するか、他の任意の `Session` 実装に差し替えます。
27+
28+
<Code
29+
lang="typescript"
30+
code={sessionsQuickstart}
31+
title="Conversations API をセッションメモリとして使用"
32+
/>
33+
34+
同じセッションインスタンスを再利用すると、各ターンの前にエージェントが完全な会話履歴を受け取り、新しいアイテムが自動的に永続化されます。別の `Session` 実装への切り替えでも、他のコード変更は不要です。
35+
36+
---
37+
38+
## ランナーによるセッションの使用方法
39+
40+
- **各実行前に** セッション履歴を取得し、新しいターンの入力とマージして、結合リストをエージェントに渡します
41+
- **非ストリーミング実行後に** 1 回の `session.addItems()` 呼び出しで、直近ターンの元のユーザー入力とモデル出力の両方を永続化します
42+
- **ストリーミング実行では** まずユーザー入力を書き込み、ターン完了時にストリーム出力を追記します
43+
- **`RunResult.state` から再開する場合**(承認やその他の中断)も同じ `session` を渡し続けます。再開したターンは、入力を再準備せずにメモリへ追加されます
44+
45+
---
46+
47+
## 履歴の確認と編集
48+
49+
セッションはシンプルな CRUD ヘルパーを公開しているため、「取り消し」「チャットのクリア」や監査機能を構築できます。
50+
51+
<Code
52+
lang="typescript"
53+
code={manageHistory}
54+
title="保存済みアイテムの読み取りと編集"
55+
/>
56+
57+
`session.getItems()` は保存された `AgentInputItem[]` を返します。`popItem()` を呼び出して最後のエントリを削除できます。エージェントを再実行する前のユーザー修正に便利です。
58+
59+
---
60+
61+
## 独自ストレージの持ち込み
62+
63+
`Session` インターフェースを実装して、Redis、DynamoDB、SQLite などのデータストアでメモリを支えることができます。必要なのは 5 つの非同期メソッドだけです。
64+
65+
<Code
66+
lang="typescript"
67+
code={customSession}
68+
title="カスタムのインメモリセッション実装"
69+
/>
70+
71+
カスタムセッションにより、保持ポリシーの適用、暗号化の追加、各会話ターンにメタデータを付与してから永続化することが可能になります。
72+
73+
---
74+
75+
## 履歴と新規アイテムのマージ方法の制御
76+
77+
実行入力として `AgentInputItem` の配列を渡す場合、`sessionInputCallback` を指定して、保存済み履歴とのマージを決定的に行えます。ランナーは既存履歴を読み込み、**モデル呼び出し前に** コールバックを呼び出し、返された配列を当該ターンの完全な入力としてモデルに渡します。このフックは、古いアイテムのトリミング、ツール結果の重複排除、モデルに見せたいコンテキストのみを強調する用途に最適です。
78+
79+
<Code
80+
lang="typescript"
81+
code={sessionInputCallback}
82+
title="sessionInputCallback で履歴を切り詰め"
83+
/>
84+
85+
文字列入力ではランナーが自動で履歴をマージするため、コールバックは任意です。
86+
87+
---
88+
89+
## 承認と再開可能な実行の取り扱い
90+
91+
Human-in-the-loop フローでは、承認待ちのために実行を一時停止することがあります:
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+
以前の `RunState` から再開する場合、新しいターンは同じメモリレコードに追記され、単一の会話履歴が維持されます。Human in the loop (人間の介入)(HITL)フローとの互換性は完全に保たれ、承認チェックポイントは引き続き `RunState` を経由して往復しつつ、セッションが完全なトランスクリプトを保持します。
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
---
2+
title: 세션
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+
세션은 Agents SDK에 **지속형 메모리 계층**을 제공합니다. `Session` 인터페이스를 구현한 객체를 `Runner.run`에 전달하면 나머지는 SDK가 처리합니다. 세션이 있으면 러너는 자동으로 다음을 수행합니다:
13+
14+
1. 이전에 저장된 대화 항목을 가져와 다음 턴의 앞에 붙입니다.
15+
2. 각 실행이 완료된 후 새로운 사용자 입력과 어시스턴트 출력을 지속 저장합니다.
16+
3. 새로운 사용자 텍스트로 러너를 호출하든 인터럽트된 `RunState`에서 재개하든, 이후 턴에서도 세션을 계속 사용 가능하게 유지합니다.
17+
18+
이를 통해 수동으로 `toInputList()`를 호출하거나 턴 간 히스토리를 이어 붙일 필요가 없습니다. TypeScript SDK에는 `OpenAIConversationsSession`(Conversations API용)과 로컬 개발을 위한 `MemorySession`의 두 구현이 포함되어 있습니다. 둘 다 `Session` 인터페이스를 공유하므로, 자체 스토리지 백엔드를 연결할 수 있습니다. Conversations API 외에도 영감을 얻고 싶다면 `examples/memory/` 아래의 샘플 세션 백엔드(Prisma, 파일 기반 등)를 살펴보세요.
19+
20+
> Tip: 이 페이지의 `OpenAIConversationsSession` 예제를 실행하려면 `OPENAI_API_KEY` 환경 변수를 설정하세요(또는 세션을 생성할 때 `apiKey`를 제공). 그러면 SDK가 Conversations API를 호출할 수 있습니다.
21+
22+
---
23+
24+
## 빠른 시작
25+
26+
메모리를 [Conversations API](https://platform.openai.com/docs/api-reference/conversations)와 동기화하려면 `OpenAIConversationsSession`을 사용하거나, 다른 어떤 `Session` 구현으로 교체하세요.
27+
28+
<Code
29+
lang="typescript"
30+
code={sessionsQuickstart}
31+
title="Conversations API를 세션 메모리로 사용"
32+
/>
33+
34+
동일한 세션 인스턴스를 재사용하면, 매 턴 전에 에이전트가 전체 대화 히스토리를 받고 새 항목이 자동으로 지속 저장됩니다. 다른 `Session` 구현으로 전환해도 추가 코드 변경은 필요 없습니다.
35+
36+
---
37+
38+
## 러너의 세션 사용 방식
39+
40+
- **각 실행 전** 세션 히스토리를 가져와 새 턴의 입력과 병합하고, 결합된 목록을 에이전트에 전달합니다
41+
- **비 스트리밍 실행 후** 한 번의 `session.addItems()` 호출로 최신 턴의 원본 사용자 입력과 모델 출력을 모두 저장합니다
42+
- **스트리밍 실행의 경우** 사용자 입력을 먼저 기록하고, 턴이 완료되면 스트리밍된 출력을 이어서 추가합니다
43+
- **`RunResult.state`에서 재개할 때**(승인 또는 기타 인터럽션(중단 처리)) 동일한 `session`을 계속 전달하세요. 재개된 턴은 입력을 다시 준비하지 않고 메모리에 추가됩니다
44+
45+
---
46+
47+
## 히스토리 검사 및 편집
48+
49+
세션은 간단한 CRUD 헬퍼를 제공하므로 "실행 취소", "채팅 지우기", 감사 기능을 구축할 수 있습니다.
50+
51+
<Code lang="typescript" code={manageHistory} title="저장된 항목 읽기 및 편집" />
52+
53+
`session.getItems()`는 저장된 `AgentInputItem[]`를 반환합니다. `popItem()`을 호출해 마지막 항목을 제거할 수 있으며, 이는 에이전트를 다시 실행하기 전에 사용자가 정정할 때 유용합니다.
54+
55+
---
56+
57+
## 자체 스토리지 사용
58+
59+
`Session` 인터페이스를 구현해 Redis, DynamoDB, SQLite 또는 다른 데이터 스토어로 메모리를 지원하세요. 필요한 것은 비동기 메서드 다섯 개뿐입니다.
60+
61+
<Code
62+
lang="typescript"
63+
code={customSession}
64+
title="커스텀 인메모리 세션 구현"
65+
/>
66+
67+
커스텀 세션을 통해 보존 정책을 적용하고, 암호화를 추가하거나, 지속 저장 전에 각 대화 턴에 메타데이터를 부착할 수 있습니다.
68+
69+
---
70+
71+
## 히스토리와 새 항목 병합 제어
72+
73+
실행 입력으로 `AgentInputItem` 배열을 전달할 때, `sessionInputCallback`을 제공해 저장된 히스토리와 결정적으로 병합할 수 있습니다. 러너는 기존 히스토리를 로드하고, 모델 호출 **이전에** 콜백을 호출하며, 반환된 배열을 해당 턴의 완전한 입력으로 모델에 전달합니다. 이 훅은 오래된 항목을 잘라내거나, 도구 결과의 중복을 제거하거나, 모델에 보여주고 싶은 컨텍스트만 강조할 때 이상적입니다.
74+
75+
<Code
76+
lang="typescript"
77+
code={sessionInputCallback}
78+
title="sessionInputCallback으로 히스토리 길이 제한"
79+
/>
80+
81+
문자열 입력의 경우 러너가 히스토리를 자동으로 병합하므로 콜백은 선택 사항입니다.
82+
83+
---
84+
85+
## 승인 및 재개 가능한 실행 처리
86+
87+
휴먼인더루프 (HITL) 플로우는 종종 승인을 기다리기 위해 실행을 일시 정지합니다:
88+
89+
```typescript
90+
const result = await runner.run(agent, 'Search the itinerary', {
91+
session,
92+
stream: true,
93+
});
94+
95+
if (result.requiresApproval) {
96+
// ... collect user feedback, then resume the agent in a later turn
97+
const continuation = await runner.run(agent, result.state, { session });
98+
console.log(continuation.finalOutput);
99+
}
100+
```
101+
102+
이전 `RunState`에서 재개하면, 단일 대화 히스토리를 보존하기 위해 새 턴이 동일한 메모리 레코드에 추가됩니다. 휴먼인더루프 (HITL) 플로우는 완전히 호환되며—승인 체크포인트는 계속 `RunState`를 통해 라운드트립하는 한편 세션은 전체 대화록을 유지합니다.

0 commit comments

Comments
 (0)