From 1d421d17a1d428b17d3eeb174fc54cccd9ca2890 Mon Sep 17 00:00:00 2001 From: droideronline Date: Wed, 4 Nov 2026 14:12:19 +0530 Subject: [PATCH] Python: Sum streamed GitHubCopilotAgent usage across model calls Each ASSISTANT_USAGE event carries the usage of a single model call, but the streaming handler emitted it with merge_mode="replace", so core kept only the last call. Emit it with merge_mode="append" so the calls are summed, matching the non-streaming path. --- .../agent_framework_github_copilot/_agent.py | 2 +- .../tests/test_github_copilot_agent.py | 38 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/python/packages/github_copilot/agent_framework_github_copilot/_agent.py b/python/packages/github_copilot/agent_framework_github_copilot/_agent.py index 94633fb3018..c4f3f70b4ac 100644 --- a/python/packages/github_copilot/agent_framework_github_copilot/_agent.py +++ b/python/packages/github_copilot/agent_framework_github_copilot/_agent.py @@ -1164,7 +1164,7 @@ def event_handler(event: SessionEvent) -> None: contents=[ Content.from_usage( usage_details, - merge_mode="replace", + merge_mode="append", raw_representation=event.data, ) ] diff --git a/python/packages/github_copilot/tests/test_github_copilot_agent.py b/python/packages/github_copilot/tests/test_github_copilot_agent.py index 813d5075831..7fe0c7539cb 100644 --- a/python/packages/github_copilot/tests/test_github_copilot_agent.py +++ b/python/packages/github_copilot/tests/test_github_copilot_agent.py @@ -771,6 +771,44 @@ def mock_on(handler: Any) -> Any: } assert response.additional_properties["model"] == "gpt-5.1-mini" + async def test_run_streaming_sums_usage_across_multiple_model_calls( + self, + mock_client: MagicMock, + mock_session: MagicMock, + assistant_delta_event: SessionEvent, + session_idle_event: SessionEvent, + ) -> None: + """Test streaming sums per-call usage events instead of keeping only the last one.""" + usage_events = [ + SessionEvent( + data=AssistantUsageData(model="gpt-5.1-mini", input_tokens=n * 100, output_tokens=n * 10), + id=uuid4(), + timestamp=datetime.now(timezone.utc), + type=SessionEventType.ASSISTANT_USAGE, + ) + for n in (1, 2, 3) + ] + events = [assistant_delta_event, *usage_events, session_idle_event] + + def mock_on(handler: Any) -> Any: + for event in events: + handler(event) + return lambda: None + + mock_session.on = mock_on + + agent = GitHubCopilotAgent(client=mock_client) + stream = agent.run("Hello", stream=True) + async for _ in stream: + pass + response = await stream.get_final_response() + + assert response.usage_details == { + "input_token_count": 600, + "output_token_count": 60, + "total_token_count": 660, + } + async def test_run_streaming_with_session( self, mock_client: MagicMock,