Skip to content

Commit 2a6d651

Browse files
fix: add compaction usage to the run context, not just the session
run_compaction now opts into the wrapper protocol that _call_session_method already implements, so the tokens billed by responses.compact land in wrapper.usage and therefore in RunResult.context_wrapper.usage, which is where the run's total is read from. The session-level compaction_usage attribute stays for callers that drive compaction directly, outside a run. Tests cover the wrapper path, the opt-in detection the run loop uses, and a call through _call_session_method itself. Claude-Session: https://claude.ai/code/session_01KJrBqn4AgyHTazfdUuXbuA
1 parent 8e5fb9c commit 2a6d651

2 files changed

Lines changed: 64 additions & 4 deletions

File tree

‎src/agents/memory/openai_responses_compaction_session.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
)
2323

2424
if TYPE_CHECKING:
25+
from ..run_context import RunContextWrapper
2526
from .session import Session
2627

2728
logger = logging.getLogger("openai-agents.openai.compaction")
@@ -175,8 +176,20 @@ def _resolve_compaction_mode_for_response(
175176
return "input"
176177
return _resolve_compaction_mode(mode, response_id=response_id, store=store)
177178

178-
async def run_compaction(self, args: OpenAIResponsesCompactionArgs | None = None) -> None:
179-
"""Run compaction using responses.compact API."""
179+
async def run_compaction(
180+
self,
181+
args: OpenAIResponsesCompactionArgs | None = None,
182+
*,
183+
wrapper: RunContextWrapper[Any] | None = None,
184+
) -> None:
185+
"""Run compaction using responses.compact API.
186+
187+
Args:
188+
args: Compaction arguments from the run loop.
189+
wrapper: Run context, when the caller provides one. Compaction is a billed
190+
model call, so its usage is added to ``wrapper.usage`` and therefore
191+
reaches ``RunResult.context_wrapper.usage`` like any other model call.
192+
"""
180193
if args and args.get("response_id"):
181194
self._response_id = args["response_id"]
182195
requested_mode = args.get("compaction_mode") if args else None
@@ -236,7 +249,7 @@ async def run_compaction(self, args: OpenAIResponsesCompactionArgs | None = None
236249

237250
compacted = await self.client.responses.compact(**compact_kwargs)
238251

239-
self._record_compaction_usage(getattr(compacted, "usage", None))
252+
self._record_compaction_usage(getattr(compacted, "usage", None), wrapper)
240253

241254
output_items = _strip_orphaned_assistant_ids(
242255
_normalize_compaction_output_items(compacted.output or [])
@@ -259,7 +272,11 @@ async def run_compaction(self, args: OpenAIResponsesCompactionArgs | None = None
259272
len(self._compaction_candidate_items or []),
260273
)
261274

262-
def _record_compaction_usage(self, compacted_usage: Any) -> None:
275+
def _record_compaction_usage(
276+
self,
277+
compacted_usage: Any,
278+
wrapper: RunContextWrapper[Any] | None = None,
279+
) -> None:
263280
"""Accumulate the tokens a compaction pass billed.
264281
265282
Accounting must never break a run, so anything unexpected on the usage
@@ -297,6 +314,8 @@ def _count(name: str) -> int | None:
297314
usage.output_tokens_details = output_details
298315

299316
self.compaction_usage.add(usage)
317+
if wrapper is not None:
318+
wrapper.usage.add(usage)
300319
logger.debug(
301320
"compact: usage for %s (input=%s, output=%s, total=%s)",
302321
self._response_id,

‎tests/memory/test_compaction_usage.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from agents.memory.openai_responses_compaction_session import (
1111
OpenAIResponsesCompactionSession,
1212
)
13+
from agents.memory.session import _call_session_method, _session_method_accepts_wrapper
14+
from agents.run_context import RunContextWrapper
1315
from agents.memory.session import Session
1416

1517

@@ -91,3 +93,42 @@ async def test_missing_usage_is_tolerated() -> None:
9193
await session.run_compaction()
9294

9395
assert session.compaction_usage.total_tokens == 0
96+
97+
98+
@pytest.mark.asyncio
99+
async def test_compaction_usage_reaches_the_run_context() -> None:
100+
"""The run's reported total must include compaction, not just the session."""
101+
client = MagicMock()
102+
client.responses.compact = AsyncMock(return_value=_compact_response(150_000, 42_000))
103+
session = _session(client)
104+
session._response_id = "resp_1"
105+
session._session_items = []
106+
session._compaction_candidate_items = []
107+
108+
wrapper: RunContextWrapper[None] = RunContextWrapper(context=None)
109+
await session.run_compaction(wrapper=wrapper)
110+
111+
assert wrapper.usage.total_tokens == 192_000
112+
assert wrapper.usage.requests == 1
113+
114+
115+
def test_run_compaction_opts_into_the_wrapper_protocol() -> None:
116+
"""The run loop only passes wrapper to methods that declare it."""
117+
session = _session(MagicMock())
118+
assert _session_method_accepts_wrapper(session.run_compaction)
119+
120+
121+
@pytest.mark.asyncio
122+
async def test_run_loop_call_shape_passes_wrapper() -> None:
123+
"""Exercise the helper the run loop actually uses."""
124+
client = MagicMock()
125+
client.responses.compact = AsyncMock(return_value=_compact_response(100, 10))
126+
session = _session(client)
127+
session._response_id = "resp_1"
128+
session._session_items = []
129+
session._compaction_candidate_items = []
130+
131+
wrapper: RunContextWrapper[None] = RunContextWrapper(context=None)
132+
await _call_session_method(session.run_compaction, None, wrapper=wrapper)
133+
134+
assert wrapper.usage.total_tokens == 110

0 commit comments

Comments
 (0)