Skip to content

Commit a5a2cd7

Browse files
committed
feat: pass run context wrapper to session get_items/add_items
Sessions can now opt into receiving the current run's RunContextWrapper by accepting a keyword-only wrapper parameter on get_items/add_items. The runner inspects the session's signature and only forwards the wrapper to implementations that accept it, so existing custom sessions keep working unchanged. Wrapper-style sessions (EncryptedSession, OpenAIResponsesCompactionSession) forward the wrapper to opted-in underlying sessions. This revives the approach from openai#2690, which addressed maintainer review feedback before going stale, rebased onto the current runner internals and extended to MongoDBSession and the guardrail-trip persistence path. Closes openai#2072
1 parent 869e869 commit a5a2cd7

24 files changed

Lines changed: 984 additions & 76 deletions

‎docs/sessions/index.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,52 @@ result = await Runner.run(
680680
)
681681
```
682682

683+
### Accessing the run context in custom sessions
684+
685+
Custom sessions can opt into receiving the current run's [`RunContextWrapper`][agents.run_context.RunContextWrapper] by accepting a keyword-only `wrapper` parameter on `get_items` and `add_items`. The runner passes the wrapper only when the session's signature accepts it, so existing session implementations keep working unchanged:
686+
687+
```python
688+
from typing import Any
689+
690+
from agents.memory.session import SessionABC
691+
from agents.items import TResponseInputItem
692+
from agents.run_context import RunContextWrapper
693+
694+
class ContextAwareSession(SessionABC):
695+
"""Session that scopes storage by data from the run context."""
696+
697+
def __init__(self, session_id: str):
698+
self.session_id = session_id
699+
700+
async def get_items(
701+
self,
702+
limit: int | None = None,
703+
*,
704+
wrapper: RunContextWrapper[Any] | None = None,
705+
) -> list[TResponseInputItem]:
706+
# Use wrapper.context (e.g. a user ID) to scope retrieval.
707+
user_id = wrapper.context.user_id if wrapper is not None else None
708+
return await self._load_items(user_id, limit)
709+
710+
async def add_items(
711+
self,
712+
items: list[TResponseInputItem],
713+
*,
714+
wrapper: RunContextWrapper[Any] | None = None,
715+
) -> None:
716+
# Persist items together with data from the run context.
717+
user_id = wrapper.context.user_id if wrapper is not None else None
718+
await self._store_items(user_id, items)
719+
720+
async def pop_item(self) -> TResponseInputItem | None:
721+
...
722+
723+
async def clear_session(self) -> None:
724+
...
725+
```
726+
727+
The `wrapper` parameter may be `None`, for example when session methods are called directly rather than through the runner, so implementations should always handle that case. Sessions that accept `**kwargs` on these methods also receive the wrapper through them.
728+
683729
## Community session implementations
684730

685731
The community has developed additional session implementations:

‎examples/memory/file_session.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
from agents.memory.session import Session
1717
from agents.memory.session_settings import SessionSettings
18+
from agents.run_context import RunContextWrapper
1819

1920

2021
class FileSession(Session):
@@ -43,14 +44,24 @@ async def get_session_id(self) -> str:
4344
"""Return the session id, creating one if needed."""
4445
return await self._ensure_session_id()
4546

46-
async def get_items(self, limit: int | None = None) -> list[Any]:
47+
async def get_items(
48+
self,
49+
limit: int | None = None,
50+
*,
51+
wrapper: RunContextWrapper[Any] | None = None,
52+
) -> list[Any]:
4753
session_id = await self._ensure_session_id()
4854
items = await self._read_items(session_id)
4955
if limit is not None and limit >= 0:
5056
return items[-limit:]
5157
return items
5258

53-
async def add_items(self, items: list[Any]) -> None:
59+
async def add_items(
60+
self,
61+
items: list[Any],
62+
*,
63+
wrapper: RunContextWrapper[Any] | None = None,
64+
) -> None:
5465
if not items:
5566
return
5667
session_id = await self._ensure_session_id()

‎src/agents/extensions/memory/advanced_sqlite_session.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from ...items import TResponseInputItem
1616
from ...memory import SQLiteSession
1717
from ...memory.session_settings import SessionSettings, resolve_session_limit
18+
from ...run_context import RunContextWrapper
1819

1920

2021
class AdvancedSQLiteSession(SQLiteSession):
@@ -121,7 +122,12 @@ def _init_structure_tables(self):
121122

122123
conn.commit()
123124

124-
async def add_items(self, items: list[TResponseInputItem]) -> None:
125+
async def add_items(
126+
self,
127+
items: list[TResponseInputItem],
128+
*,
129+
wrapper: RunContextWrapper[Any] | None = None,
130+
) -> None:
125131
"""Add items to the session.
126132
127133
Args:
@@ -160,6 +166,8 @@ async def get_items(
160166
self,
161167
limit: int | None = None,
162168
branch_id: str | None = None,
169+
*,
170+
wrapper: RunContextWrapper[Any] | None = None,
163171
) -> list[TResponseInputItem]:
164172
"""Get items from current or specified branch.
165173

‎src/agents/extensions/memory/async_sqlite_session.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55
from collections.abc import AsyncIterator
66
from contextlib import asynccontextmanager
77
from pathlib import Path
8-
from typing import cast
8+
from typing import Any, cast
99

1010
import aiosqlite
1111

1212
from ...items import TResponseInputItem
1313
from ...memory import SessionABC
1414
from ...memory.session_settings import SessionSettings, resolve_session_limit
15+
from ...run_context import RunContextWrapper
1516

1617

1718
class AsyncSQLiteSession(SessionABC):
@@ -106,7 +107,12 @@ async def _locked_connection(self) -> AsyncIterator[aiosqlite.Connection]:
106107
conn = await self._get_connection()
107108
yield conn
108109

109-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
110+
async def get_items(
111+
self,
112+
limit: int | None = None,
113+
*,
114+
wrapper: RunContextWrapper[Any] | None = None,
115+
) -> list[TResponseInputItem]:
110116
"""Retrieve the conversation history for this session.
111117
112118
Args:
@@ -156,7 +162,12 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
156162

157163
return items
158164

159-
async def add_items(self, items: list[TResponseInputItem]) -> None:
165+
async def add_items(
166+
self,
167+
items: list[TResponseInputItem],
168+
*,
169+
wrapper: RunContextWrapper[Any] | None = None,
170+
) -> None:
160171
"""Add new items to the conversation history.
161172
162173
Args:

‎src/agents/extensions/memory/dapr_session.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import time
3030
from typing import Any, Final, Literal
3131

32+
from ...run_context import RunContextWrapper
3233
from ._optional_imports import raise_optional_dependency_error
3334

3435
try:
@@ -250,7 +251,12 @@ async def _handle_concurrency_conflict(self, error: Exception, attempt: int) ->
250251
# Session protocol implementation
251252
# ------------------------------------------------------------------
252253

253-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
254+
async def get_items(
255+
self,
256+
limit: int | None = None,
257+
*,
258+
wrapper: RunContextWrapper[Any] | None = None,
259+
) -> list[TResponseInputItem]:
254260
"""Retrieve the conversation history for this session.
255261
256262
Args:
@@ -289,7 +295,12 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
289295
continue
290296
return items
291297

292-
async def add_items(self, items: list[TResponseInputItem]) -> None:
298+
async def add_items(
299+
self,
300+
items: list[TResponseInputItem],
301+
*,
302+
wrapper: RunContextWrapper[Any] | None = None,
303+
) -> None:
293304
"""Add new items to the conversation history.
294305
295306
Args:

‎src/agents/extensions/memory/encrypt_session.py‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@
3737
from typing_extensions import TypedDict
3838

3939
from ...items import TResponseInputItem
40-
from ...memory.session import SessionABC
40+
from ...memory.session import SessionABC, session_method_accepts_wrapper
4141
from ...memory.session_settings import SessionSettings, resolve_session_limit
42+
from ...run_context import RunContextWrapper
4243

4344

4445
class EncryptedEnvelope(TypedDict):
@@ -180,24 +181,52 @@ def _unwrap_valid_items(
180181
valid_items.append(item)
181182
return valid_items
182183

183-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
184+
async def _get_underlying_items(
185+
self, limit: int | None, wrapper: RunContextWrapper[Any] | None
186+
) -> list[TResponseInputItem]:
187+
# Forward the wrapper only when the underlying session opts in, so wrapping older
188+
# custom sessions keeps working unchanged.
189+
if wrapper is not None and session_method_accepts_wrapper(
190+
self.underlying_session.get_items
191+
):
192+
return await self.underlying_session.get_items(limit, wrapper=wrapper)
193+
return await self.underlying_session.get_items(limit)
194+
195+
async def get_items(
196+
self,
197+
limit: int | None = None,
198+
*,
199+
wrapper: RunContextWrapper[Any] | None = None,
200+
) -> list[TResponseInputItem]:
184201
effective_limit = resolve_session_limit(limit, self.session_settings)
185202
if effective_limit is not None and effective_limit > 0:
186203
window = effective_limit
187204
while True:
188-
encrypted_items = await self.underlying_session.get_items(window)
205+
encrypted_items = await self._get_underlying_items(window, wrapper)
189206
valid_items = self._unwrap_valid_items(encrypted_items)
190207
if len(valid_items) >= effective_limit:
191208
return valid_items[-effective_limit:]
192209
if len(encrypted_items) < window:
193210
return valid_items
194211
window *= 2
195212

196-
encrypted_items = await self.underlying_session.get_items(limit)
213+
encrypted_items = await self._get_underlying_items(limit, wrapper)
197214
return self._unwrap_valid_items(encrypted_items)
198215

199-
async def add_items(self, items: list[TResponseInputItem]) -> None:
216+
async def add_items(
217+
self,
218+
items: list[TResponseInputItem],
219+
*,
220+
wrapper: RunContextWrapper[Any] | None = None,
221+
) -> None:
200222
wrapped: list[EncryptedEnvelope] = [self._wrap(it) for it in items]
223+
if wrapper is not None and session_method_accepts_wrapper(
224+
self.underlying_session.add_items
225+
):
226+
await self.underlying_session.add_items(
227+
cast(list[TResponseInputItem], wrapped), wrapper=wrapper
228+
)
229+
return
201230
await self.underlying_session.add_items(cast(list[TResponseInputItem], wrapped))
202231

203232
async def pop_item(self) -> TResponseInputItem | None:

‎src/agents/extensions/memory/mongodb_session.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from datetime import datetime, timezone
3838
from typing import Any
3939

40+
from ...run_context import RunContextWrapper
4041
from ._optional_imports import raise_optional_dependency_error
4142

4243
try:
@@ -247,7 +248,12 @@ async def _deserialize_item(self, raw: str) -> TResponseInputItem:
247248
# Session protocol implementation
248249
# ------------------------------------------------------------------
249250

250-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
251+
async def get_items(
252+
self,
253+
limit: int | None = None,
254+
*,
255+
wrapper: RunContextWrapper[Any] | None = None,
256+
) -> list[TResponseInputItem]:
251257
"""Retrieve the conversation history for this session.
252258
253259
Args:
@@ -289,7 +295,12 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
289295

290296
return items
291297

292-
async def add_items(self, items: list[TResponseInputItem]) -> None:
298+
async def add_items(
299+
self,
300+
items: list[TResponseInputItem],
301+
*,
302+
wrapper: RunContextWrapper[Any] | None = None,
303+
) -> None:
293304
"""Add new items to the conversation history.
294305
295306
Args:

‎src/agents/extensions/memory/redis_session.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import time
2727
from typing import Any
2828

29+
from ...run_context import RunContextWrapper
2930
from ._optional_imports import raise_optional_dependency_error
3031

3132
try:
@@ -145,7 +146,12 @@ async def _set_ttl_if_configured(self, *keys: str) -> None:
145146
# Session protocol implementation
146147
# ------------------------------------------------------------------
147148

148-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
149+
async def get_items(
150+
self,
151+
limit: int | None = None,
152+
*,
153+
wrapper: RunContextWrapper[Any] | None = None,
154+
) -> list[TResponseInputItem]:
149155
"""Retrieve the conversation history for this session.
150156
151157
Args:
@@ -184,7 +190,12 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
184190

185191
return items
186192

187-
async def add_items(self, items: list[TResponseInputItem]) -> None:
193+
async def add_items(
194+
self,
195+
items: list[TResponseInputItem],
196+
*,
197+
wrapper: RunContextWrapper[Any] | None = None,
198+
) -> None:
188199
"""Add new items to the conversation history.
189200
190201
Args:

‎src/agents/extensions/memory/sqlalchemy_session.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
from ...items import TResponseInputItem
5252
from ...memory.session import SessionABC
5353
from ...memory.session_settings import SessionSettings, resolve_session_limit
54+
from ...run_context import RunContextWrapper
5455

5556

5657
class SQLAlchemySession(SessionABC):
@@ -274,7 +275,12 @@ async def _ensure_tables(self) -> None:
274275
finally:
275276
self._init_lock.release()
276277

277-
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
278+
async def get_items(
279+
self,
280+
limit: int | None = None,
281+
*,
282+
wrapper: RunContextWrapper[Any] | None = None,
283+
) -> list[TResponseInputItem]:
278284
"""Retrieve the conversation history for this session.
279285
280286
Args:
@@ -326,7 +332,12 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
326332
continue
327333
return items
328334

329-
async def add_items(self, items: list[TResponseInputItem]) -> None:
335+
async def add_items(
336+
self,
337+
items: list[TResponseInputItem],
338+
*,
339+
wrapper: RunContextWrapper[Any] | None = None,
340+
) -> None:
330341
"""Add new items to the conversation history.
331342
332343
Args:

0 commit comments

Comments
 (0)