Skip to content

Commit dafcc8a

Browse files
committed
docs: Add the Sessions feature document page
1 parent a08cc9c commit dafcc8a

File tree

9 files changed

+603
-0
lines changed

9 files changed

+603
-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: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
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**. All you need is any
13+
object that implements the `Session` interface—pass it to `Runner.run` and the
14+
SDK will handle the rest. When a session is present, the runner automatically:
15+
16+
1. Fetches previously stored conversation items and prepends them to the next turn.
17+
2. Persists new user input and assistant output after each run completes.
18+
3. Keeps the session available for future turns, whether you call the runner with
19+
new user text or resume from an interrupted `RunState`.
20+
21+
This removes the need to manually call `toInputList()` or stitch history together
22+
between turns. The TypeScript SDK currently ships with one ready-to-use
23+
`OpenAIConversationsSession`, and the same `Session` interface lets you bring your
24+
own storage. For inspiration beyond the OpenAI Conversations API, browse the
25+
sample session backends under `examples/memory/` (Prisma, file-backed, and more).
26+
27+
> Tip: To run the `OpenAIConversationsSession` examples on this page, set the
28+
> `OPENAI_API_KEY` environment variable (or provide an `apiKey` when constructing
29+
> the session) so the SDK can call the Conversations API.
30+
31+
---
32+
33+
## Quick start
34+
35+
Use an `OpenAIConversationsSession` (or any other `Session` implementation) to sync memory with the
36+
[Conversations API](https://platform.openai.com/docs/api-reference/conversations).
37+
38+
<Code
39+
lang="typescript"
40+
code={sessionsQuickstart}
41+
title="Use the Conversations API as session memory"
42+
/>
43+
44+
When you reuse the same session instance, the agent receives the full conversation
45+
history before every turn and writes new items back automatically.
46+
47+
Swap `OpenAIConversationsSession` with any other `Session` implementation—no other
48+
code changes are required.
49+
50+
---
51+
52+
## How the runner uses sessions
53+
54+
- **Before each run** the runner retrieves the session history, merges it with the
55+
new turn’s input, and passes the combined list to your agent.
56+
- **After a non-streaming run** a single call to `session.addItems()` persists both
57+
the original user input and the model outputs from the latest turn.
58+
- **For streaming runs** the runner writes the user input up front and appends
59+
streamed outputs once the turn completes.
60+
- **When resuming from `RunResult.state`** (for approval flows or other interruptions)
61+
continue passing the same `session`. The resumed turn is added to memory without
62+
re-preparing the input.
63+
64+
---
65+
66+
## Inspecting and editing history
67+
68+
Sessions expose simple CRUD helpers so you can build “undo”, “clear chat”, or audit
69+
features.
70+
71+
<Code
72+
lang="typescript"
73+
code={manageHistory}
74+
title="Read and edit stored items"
75+
/>
76+
77+
`session.getItems()` returns the stored `AgentInputItem[]`. Call `popItem()` to
78+
remove the last entry—useful for user corrections before you rerun the agent.
79+
80+
---
81+
82+
## Bring your own storage
83+
84+
Implement the `Session` interface to back memory with Redis, DynamoDB,
85+
SQLite, or another datastore. Only five asynchronous methods are required.
86+
87+
<Code
88+
lang="typescript"
89+
code={customSession}
90+
title="Custom in-memory session implementation"
91+
/>
92+
93+
Custom sessions let you enforce retention policies, add encryption, or attach
94+
metadata to each conversation turn before persisting it.
95+
96+
---
97+
98+
## Control how history and new items merge
99+
100+
When you pass an array of `AgentInputItem`s as the run input, provide a
101+
`sessionInputCallback` to merge them with stored history deterministically.
102+
The runner loads the existing history, calls your callback **before the model
103+
invocation**, and hands the returned array to the model as the turn’s complete
104+
input. This hook is ideal for trimming old items, deduplicating tool results, or
105+
highlighting only the context you want the model to see.
106+
107+
<Code
108+
lang="typescript"
109+
code={sessionInputCallback}
110+
title="Truncate history with sessionInputCallback"
111+
/>
112+
113+
For string inputs the runner can merge history automatically, so you can omit the
114+
callback.
115+
116+
---
117+
118+
## Handling approvals and resumable runs
119+
120+
Human-in-the-loop flows often pause a run to wait for approval:
121+
122+
```typescript
123+
const result = await runner.run(agent, 'Search the itinerary', {
124+
session,
125+
stream: true,
126+
});
127+
128+
if (result.requiresApproval) {
129+
// ... collect user feedback, then resume the agent in a later turn
130+
const continuation = await runner.run(agent, result.state, { session });
131+
console.log(continuation.finalOutput);
132+
}
133+
```
134+
135+
Because sessions now work when resuming from a previous `RunState`, the continued
136+
turn is appended to the same memory record, maintaining a single coherent history
137+
for the conversation. This keeps human-in-the-loop (HITL) flows fully compatible—
138+
your approval checkpoints continue to round-trip through `RunState` while the
139+
session keeps the transcript complete.
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
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` が同梱されています。同じ `Session` インターフェースを使えば、独自のストレージを持ち込むこともできます。OpenAI Conversations API 以外の発想については、`examples/memory/` 配下のサンプルセッションバックエンド(Prisma、ファイルバックエンドなど)を参照してください。
19+
20+
> Tip: このページの `OpenAIConversationsSession` の例を実行するには、`OPENAI_API_KEY` 環境変数を設定する(またはセッション構築時に `apiKey` を指定する)ことで、SDK が Conversations API を呼び出せるようにしてください。
21+
22+
---
23+
24+
## クイックスタート
25+
26+
`OpenAIConversationsSession`(または他の任意の `Session` 実装)を使用してメモリを
27+
[Conversations API](https://platform.openai.com/docs/api-reference/conversations)
28+
と同期します。
29+
30+
<Code
31+
lang="typescript"
32+
code={sessionsQuickstart}
33+
title="Use the Conversations API as session memory"
34+
/>
35+
36+
同じセッションインスタンスを再利用すると、エージェントは毎ターンの前に会話履歴全体を受け取り、新しいアイテムを書き戻します。
37+
38+
`OpenAIConversationsSession` を他の任意の `Session` 実装に差し替えても、他のコード変更は不要です。
39+
40+
---
41+
42+
## ランナーによるセッションの利用方法
43+
44+
- **各実行の前に** ランナーはセッション履歴を取得し、新しいターンの入力とマージして、その結合リストをエージェントに渡します
45+
- **非ストリーミング実行の後に** `session.addItems()` を 1 回呼び出して、元のユーザー入力と直近ターンのモデル出力の両方を永続化します
46+
- **ストリーミング実行では** ユーザー入力を先に書き込み、ターンが完了したらストリーミング出力を追記します
47+
- **`RunResult.state` から再開する場合**(承認フローやその他の中断)同じ `session` を渡し続けます。再開したターンは入力の再準備なしにメモリへ追加されます
48+
49+
---
50+
51+
## 履歴の確認と編集
52+
53+
セッションはシンプルな CRUD ヘルパーを公開しているため、「元に戻す」「チャットをクリア」「監査」といった機能を構築できます。
54+
55+
<Code
56+
lang="typescript"
57+
code={manageHistory}
58+
title="Read and edit stored items"
59+
/>
60+
61+
`session.getItems()` は保存済みの `AgentInputItem[]` を返します。`popItem()` を呼び出して最後のエントリを削除できます。これは、エージェントを再実行する前のユーザー修正に便利です。
62+
63+
---
64+
65+
## 独自ストレージの持ち込み
66+
67+
`Session` インターフェースを実装して、Redis、DynamoDB、SQLite などのデータストアでメモリを裏付けできます。必要なのは 5 つの非同期メソッドだけです。
68+
69+
<Code
70+
lang="typescript"
71+
code={customSession}
72+
title="Custom in-memory session implementation"
73+
/>
74+
75+
カスタムセッションを使うことで、保持ポリシーの適用、暗号化の追加、または永続化前に各会話ターンへメタデータを付与できます。
76+
77+
---
78+
79+
## 履歴と新規アイテムのマージ方法の制御
80+
81+
実行入力として `AgentInputItem` の配列を渡すときは、保存済み履歴と決定論的にマージするために `sessionInputCallback` を指定します。ランナーは既存の履歴を読み込み、**モデル呼び出しの前に** コールバックを呼び出し、返された配列をそのターンの完全な入力としてモデルに渡します。このフックは、古いアイテムの切り詰め、ツール結果の重複排除、またはモデルに見せたいコンテキストだけを強調表示するのに最適です。
82+
83+
<Code
84+
lang="typescript"
85+
code={sessionInputCallback}
86+
title="Truncate history with sessionInputCallback"
87+
/>
88+
89+
文字列入力の場合、ランナーは履歴を自動的にマージできるため、コールバックを省略できます。
90+
91+
---
92+
93+
## 承認と再開可能な実行の取り扱い
94+
95+
Human in the loop (人間の介入) フローでは、承認待ちのために実行を一時停止することがよくあります。
96+
97+
```typescript
98+
const result = await runner.run(agent, 'Search the itinerary', {
99+
session,
100+
stream: true,
101+
});
102+
103+
if (result.requiresApproval) {
104+
// ... collect user feedback, then resume the agent in a later turn
105+
const continuation = await runner.run(agent, result.state, { session });
106+
console.log(continuation.finalOutput);
107+
}
108+
```
109+
110+
セッションは以前の `RunState` からの再開時にも機能するため、継続したターンは同じメモリレコードに追加され、会話の一貫した単一の履歴が維持されます。これにより Human in the loop (人間の介入) (HITL) フローとの完全な互換性が保たれます。承認チェックポイントは引き続き `RunState` を往復しつつ、セッションが全文書を完全に保ちます。
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
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` 을 제공하며, 동일한 `Session` 인터페이스로 직접 스토리지를 연결할 수도 있습니다. OpenAI Conversations API 이외의 영감이 필요하다면 `examples/memory/` 아래의 샘플 세션 백엔드들(Prisma, 파일 기반 등)을 살펴보세요.
19+
20+
> 팁: 이 페이지의 `OpenAIConversationsSession` 예제를 실행하려면 `OPENAI_API_KEY` 환경 변수를 설정하세요(또는 세션을 생성할 때 `apiKey` 를 제공). 그러면 SDK 가 Conversations API 를 호출할 수 있습니다.
21+
22+
---
23+
24+
## 빠른 시작
25+
26+
`OpenAIConversationsSession`(또는 다른 아무 `Session` 구현)으로 메모리를
27+
[Conversations API](https://platform.openai.com/docs/api-reference/conversations) 와 동기화하세요.
28+
29+
<Code
30+
lang="typescript"
31+
code={sessionsQuickstart}
32+
title="Conversations API 를 세션 메모리로 사용하기"
33+
/>
34+
35+
같은 세션 인스턴스를 재사용하면, 에이전트는 매 턴마다 전체 대화 히스토리를 먼저 받고 새로운 항목을 자동으로 다시 기록합니다.
36+
37+
`OpenAIConversationsSession` 을 다른 아무 `Session` 구현으로 바꿔도 됩니다—그 외 코드는 변경할 필요가 없습니다.
38+
39+
---
40+
41+
## 러너의 세션 사용 방식
42+
43+
- **각 실행 전** 러너는 세션 히스토리를 가져와 새 턴 입력과 병합하고, 결합된 목록을 에이전트에 전달합니다
44+
- **비 스트리밍 실행 후** 한 번의 `session.addItems()` 호출로 최신 턴의 원본 사용자 입력과 모델 출력을 모두 영속화합니다
45+
- **스트리밍 실행의 경우** 러너는 사용자 입력을 먼저 기록하고 턴이 완료되면 스트리밍된 출력을 추가합니다
46+
- **`RunResult.state` 에서 재개할 때**(승인 플로우나 기타 인터럽션) 동일한 `session` 을 계속 전달하세요. 재개된 턴은 입력을 다시 준비하지 않고도 메모리에 추가됩니다
47+
48+
---
49+
50+
## 히스토리 검사 및 편집
51+
52+
세션은 “실행 취소”, “채팅 지우기”, 감사 기능을 만들 수 있도록 간단한 CRUD 도우미를 제공합니다.
53+
54+
<Code lang="typescript" code={manageHistory} title="저장된 항목 읽기 및 편집" />
55+
56+
`session.getItems()` 는 저장된 `AgentInputItem[]` 를 반환합니다. `popItem()` 을 호출해 마지막 항목을 제거할 수 있으며, 에이전트를 다시 실행하기 전에 사용자의 정정에 유용합니다.
57+
58+
---
59+
60+
## 사용자 스토리지 사용
61+
62+
`Session` 인터페이스를 구현해 Redis, DynamoDB, SQLite 또는 다른 데이터 스토어로 메모리를 지원하세요. 필요한 비동기 메서드는 단 5개입니다.
63+
64+
<Code
65+
lang="typescript"
66+
code={customSession}
67+
title="커스텀 인메모리 세션 구현"
68+
/>
69+
70+
커스텀 세션으로 보존 정책을 강제하고, 암호화를 추가하거나, 각 대화 턴에 메타데이터를 첨부한 뒤 영속화할 수 있습니다.
71+
72+
---
73+
74+
## 히스토리와 새 항목 병합 제어
75+
76+
실행 입력으로 `AgentInputItem` 배열을 전달할 때, 저장된 히스토리와 결정적으로 병합하기 위해 `sessionInputCallback` 을 제공하세요. 러너는 기존 히스토리를 로드하고, **모델 호출 이전에** 콜백을 호출하며, 반환된 배열을 해당 턴의 완전한 입력으로 모델에 전달합니다. 이 훅은 오래된 항목을 잘라내거나 도구 결과의 중복을 제거하거나, 모델이 보길 원하는 컨텍스트만 강조하는 데 이상적입니다.
77+
78+
<Code
79+
lang="typescript"
80+
code={sessionInputCallback}
81+
title="sessionInputCallback 으로 히스토리 잘라내기"
82+
/>
83+
84+
문자열 입력의 경우 러너가 히스토리를 자동으로 병합할 수 있으므로 콜백을 생략해도 됩니다.
85+
86+
---
87+
88+
## 승인 및 재개 가능한 실행 처리
89+
90+
휴먼인더루프 (HITL) 플로우는 종종 승인을 기다리기 위해 실행을 일시 중지합니다:
91+
92+
```typescript
93+
const result = await runner.run(agent, 'Search the itinerary', {
94+
session,
95+
stream: true,
96+
});
97+
98+
if (result.requiresApproval) {
99+
// ... collect user feedback, then resume the agent in a later turn
100+
const continuation = await runner.run(agent, result.state, { session });
101+
console.log(continuation.finalOutput);
102+
}
103+
```
104+
105+
이제 이전 `RunState` 에서 재개할 때도 세션이 동작하므로, 이어지는 턴은 동일한 메모리 레코드에 추가되어 대화의 일관된 히스토리를 유지합니다. 이는 휴먼인더루프 (HITL) 플로우와 완전히 호환되며—승인 체크포인트는 계속 `RunState` 를 통해 라운드트립하고, 세션은 전체 대화 기록을 완성된 상태로 유지합니다.

0 commit comments

Comments
 (0)