|
| 1 | +"""Tests that LiteLLMService puts LLM token usage on spans for billing. |
| 2 | +
|
| 3 | +Covers the paths that previously dropped usage: both auto_send variants (span |
| 4 | +output was only the TaskMessage dump) and streaming (litellm omits usage unless |
| 5 | +``stream_options.include_usage`` is set). |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +from datetime import UTC, datetime |
| 11 | +from contextlib import asynccontextmanager |
| 12 | +from unittest.mock import AsyncMock, MagicMock |
| 13 | + |
| 14 | +from agentex.types.span import Span |
| 15 | +from agentex.types.task_message import TaskMessage |
| 16 | +from agentex.types.task_message_content import TextContent |
| 17 | +from agentex.lib.types.llm_messages import ( |
| 18 | + Delta, |
| 19 | + Usage, |
| 20 | + Choice, |
| 21 | + LLMConfig, |
| 22 | + Completion, |
| 23 | + AssistantMessage, |
| 24 | +) |
| 25 | +from agentex.lib.core.services.adk.providers.litellm import ( |
| 26 | + LiteLLMService, |
| 27 | + _stream_kwargs_with_usage, |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +class FakeTrace: |
| 32 | + def __init__(self) -> None: |
| 33 | + self.spans: list[Span] = [] |
| 34 | + |
| 35 | + @asynccontextmanager |
| 36 | + async def span(self, name, parent_id=None, input=None, data=None, task_id=None): |
| 37 | + span = Span( |
| 38 | + id=f"span-{len(self.spans)}", |
| 39 | + name=name, |
| 40 | + start_time=datetime.now(UTC), |
| 41 | + trace_id="trace-1", |
| 42 | + parent_id=parent_id, |
| 43 | + input=input, |
| 44 | + ) |
| 45 | + self.spans.append(span) |
| 46 | + yield span |
| 47 | + |
| 48 | + |
| 49 | +class FakeTracer: |
| 50 | + def __init__(self) -> None: |
| 51 | + self.trace_obj = FakeTrace() |
| 52 | + |
| 53 | + def trace(self, trace_id): |
| 54 | + return self.trace_obj |
| 55 | + |
| 56 | + |
| 57 | +def _make_streaming_service(): |
| 58 | + streaming_context = MagicMock() |
| 59 | + streaming_context.task_message = TaskMessage( |
| 60 | + id="msg-1", |
| 61 | + task_id="task-1", |
| 62 | + content=TextContent(author="agent", content="", format="markdown"), |
| 63 | + ) |
| 64 | + streaming_context.stream_update = AsyncMock() |
| 65 | + |
| 66 | + @asynccontextmanager |
| 67 | + async def fake_context(**kwargs): |
| 68 | + yield streaming_context |
| 69 | + |
| 70 | + streaming_service = MagicMock() |
| 71 | + streaming_service.streaming_task_message_context = fake_context |
| 72 | + return streaming_service, streaming_context |
| 73 | + |
| 74 | + |
| 75 | +def _make_service(llm_gateway) -> tuple[LiteLLMService, FakeTracer]: |
| 76 | + streaming_service, _ = _make_streaming_service() |
| 77 | + tracer = FakeTracer() |
| 78 | + service = LiteLLMService( |
| 79 | + agentex_client=MagicMock(), |
| 80 | + streaming_service=streaming_service, |
| 81 | + tracer=tracer, |
| 82 | + llm_gateway=llm_gateway, |
| 83 | + ) |
| 84 | + return service, tracer |
| 85 | + |
| 86 | + |
| 87 | +def _stream_gateway(chunks, captured_kwargs): |
| 88 | + gateway = MagicMock() |
| 89 | + |
| 90 | + def acompletion_stream(**kwargs): |
| 91 | + captured_kwargs.update(kwargs) |
| 92 | + |
| 93 | + async def stream(): |
| 94 | + for chunk in chunks: |
| 95 | + yield chunk |
| 96 | + |
| 97 | + return stream() |
| 98 | + |
| 99 | + gateway.acompletion_stream = acompletion_stream |
| 100 | + return gateway |
| 101 | + |
| 102 | + |
| 103 | +def _delta_chunk(content: str, role: str | None = None) -> Completion: |
| 104 | + return Completion(choices=[Choice(index=0, delta=Delta(content=content, role=role))]) |
| 105 | + |
| 106 | + |
| 107 | +def _usage_only_chunk() -> Completion: |
| 108 | + return Completion( |
| 109 | + choices=[], |
| 110 | + usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15), |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | +class TestStreamKwargsWithUsage: |
| 115 | + def test_defaults_include_usage_on(self): |
| 116 | + config = LLMConfig(model="gpt-4o", messages=[], stream=True) |
| 117 | + assert _stream_kwargs_with_usage(config)["stream_options"] == {"include_usage": True} |
| 118 | + |
| 119 | + def test_caller_opt_out_preserved(self): |
| 120 | + config = LLMConfig(model="gpt-4o", messages=[], stream=True, stream_options={"include_usage": False}) |
| 121 | + assert _stream_kwargs_with_usage(config)["stream_options"] == {"include_usage": False} |
| 122 | + |
| 123 | + def test_merges_with_other_stream_options(self): |
| 124 | + config = LLMConfig(model="gpt-4o", messages=[], stream=True, stream_options={"other": 1}) |
| 125 | + assert _stream_kwargs_with_usage(config)["stream_options"] == {"include_usage": True, "other": 1} |
| 126 | + |
| 127 | + |
| 128 | +class TestChatCompletionAutoSend: |
| 129 | + async def test_span_output_carries_usage(self): |
| 130 | + completion = Completion( |
| 131 | + choices=[Choice(index=0, message=AssistantMessage(content="Hello!"), finish_reason="stop")], |
| 132 | + usage=Usage(prompt_tokens=7, completion_tokens=3, total_tokens=10), |
| 133 | + ) |
| 134 | + gateway = MagicMock() |
| 135 | + gateway.acompletion = AsyncMock(return_value=completion) |
| 136 | + service, tracer = _make_service(gateway) |
| 137 | + |
| 138 | + await service.chat_completion_auto_send( |
| 139 | + task_id="task-1", |
| 140 | + llm_config=LLMConfig(model="gpt-4o", messages=[], stream=False), |
| 141 | + trace_id="trace-1", |
| 142 | + ) |
| 143 | + |
| 144 | + span = tracer.trace_obj.spans[0] |
| 145 | + assert span.output["usage"] == {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10} |
| 146 | + |
| 147 | + async def test_span_output_omits_usage_when_absent(self): |
| 148 | + completion = Completion( |
| 149 | + choices=[Choice(index=0, message=AssistantMessage(content="Hello!"), finish_reason="stop")], |
| 150 | + ) |
| 151 | + gateway = MagicMock() |
| 152 | + gateway.acompletion = AsyncMock(return_value=completion) |
| 153 | + service, tracer = _make_service(gateway) |
| 154 | + |
| 155 | + await service.chat_completion_auto_send( |
| 156 | + task_id="task-1", |
| 157 | + llm_config=LLMConfig(model="gpt-4o", messages=[], stream=False), |
| 158 | + trace_id="trace-1", |
| 159 | + ) |
| 160 | + |
| 161 | + assert "usage" not in tracer.trace_obj.spans[0].output |
| 162 | + |
| 163 | + |
| 164 | +class TestChatCompletionStream: |
| 165 | + async def test_stream_requests_usage_and_span_output_carries_it(self): |
| 166 | + captured_kwargs: dict = {} |
| 167 | + chunks = [_delta_chunk("Hel", role="assistant"), _delta_chunk("lo!"), _usage_only_chunk()] |
| 168 | + service, tracer = _make_service(_stream_gateway(chunks, captured_kwargs)) |
| 169 | + |
| 170 | + results = [] |
| 171 | + async for chunk in service.chat_completion_stream( |
| 172 | + llm_config=LLMConfig(model="gpt-4o", messages=[], stream=True), |
| 173 | + trace_id="trace-1", |
| 174 | + ): |
| 175 | + results.append(chunk) |
| 176 | + |
| 177 | + assert len(results) == 3 |
| 178 | + assert captured_kwargs["stream_options"] == {"include_usage": True} |
| 179 | + span = tracer.trace_obj.spans[0] |
| 180 | + assert span.output["usage"] == {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15} |
| 181 | + assert span.output["choices"][0]["message"]["content"] == "Hello!" |
| 182 | + |
| 183 | + |
| 184 | +class TestChatCompletionStreamAutoSend: |
| 185 | + async def test_usage_only_final_chunk_reaches_span_output(self): |
| 186 | + captured_kwargs: dict = {} |
| 187 | + chunks = [_delta_chunk("Hel", role="assistant"), _delta_chunk("lo!"), _usage_only_chunk()] |
| 188 | + service, tracer = _make_service(_stream_gateway(chunks, captured_kwargs)) |
| 189 | + |
| 190 | + await service.chat_completion_stream_auto_send( |
| 191 | + task_id="task-1", |
| 192 | + llm_config=LLMConfig(model="gpt-4o", messages=[], stream=True), |
| 193 | + trace_id="trace-1", |
| 194 | + ) |
| 195 | + |
| 196 | + assert captured_kwargs["stream_options"] == {"include_usage": True} |
| 197 | + span = tracer.trace_obj.spans[0] |
| 198 | + assert span.output["usage"] == {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15} |
| 199 | + # TaskMessage dump is still the base of the span output |
| 200 | + assert span.output["id"] == "msg-1" |
| 201 | + |
| 202 | + async def test_stream_without_usage_chunk_omits_usage(self): |
| 203 | + captured_kwargs: dict = {} |
| 204 | + chunks = [_delta_chunk("Hi", role="assistant")] |
| 205 | + service, tracer = _make_service(_stream_gateway(chunks, captured_kwargs)) |
| 206 | + |
| 207 | + await service.chat_completion_stream_auto_send( |
| 208 | + task_id="task-1", |
| 209 | + llm_config=LLMConfig(model="gpt-4o", messages=[], stream=True), |
| 210 | + trace_id="trace-1", |
| 211 | + ) |
| 212 | + |
| 213 | + assert "usage" not in tracer.trace_obj.spans[0].output |
0 commit comments