67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
|
|
from airouter.provider import OpenAIClient, Usage
|
|
|
|
|
|
class FakeResponse:
|
|
def __init__(self, lines):
|
|
self.lines = lines
|
|
|
|
async def aiter_lines(self):
|
|
for line in self.lines:
|
|
yield line
|
|
|
|
|
|
def test_sse_accumulates_text_and_tool_calls():
|
|
client = object.__new__(OpenAIClient)
|
|
chunks = [
|
|
'data: {"choices":[{"delta":{"role":"assistant","content":"Hel"}}]}',
|
|
'data: {"choices":[{"delta":{"content":"lo","tool_calls":[{"index":0,"id":"call_1","function":{"name":"bash","arguments":"{\\"comm"}}]}}]}',
|
|
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"and\\":\\"echo hi\\"}"}}]},"finish_reason":"tool_calls"}]}',
|
|
'data: {"choices":[],"usage":{"prompt_tokens":100,"completion_tokens":20,"total_tokens":120,"completion_tokens_details":{"reasoning_tokens":5},"prompt_tokens_details":{"cached_tokens":80},"cost":0.001,"opencode":{"allowance":0.002,"billing_source":"go"}}}',
|
|
"data: [DONE]",
|
|
]
|
|
text = []
|
|
|
|
async def scenario():
|
|
return await client._read_sse(FakeResponse(chunks), on_text=text.append, on_reasoning=None)
|
|
|
|
turn = asyncio.run(scenario())
|
|
assert turn.content == "Hello"
|
|
assert len(turn.tool_calls) == 1
|
|
assert turn.tool_calls[0].name == "bash"
|
|
assert json.loads(turn.tool_calls[0].arguments) == {"command": "echo hi"}
|
|
assert turn.finish_reason == "tool_calls"
|
|
assert turn.usage.prompt_tokens == 100
|
|
assert turn.usage.completion_tokens == 20
|
|
assert turn.usage.reasoning_tokens == 5
|
|
assert turn.usage.cache_read_tokens == 80
|
|
assert turn.usage.cost == 0.001
|
|
assert turn.usage.allowance == 0.002
|
|
assert turn.usage.billing_source == "go"
|
|
assert "".join(text) == "Hello"
|
|
|
|
|
|
def test_usage_roundtrip():
|
|
usage = Usage(prompt_tokens=1, completion_tokens=2, total_tokens=3, cost=0.5)
|
|
assert Usage.from_dict(usage.to_dict()).to_dict() == usage.to_dict()
|
|
|
|
|
|
def test_json_response_fallback():
|
|
client = object.__new__(OpenAIClient)
|
|
data = {
|
|
"choices": [
|
|
{
|
|
"finish_reason": "stop",
|
|
"message": {"role": "assistant", "content": "plain response"},
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 3, "completion_tokens": 4},
|
|
}
|
|
turn = client._turn_from_json(data, on_text=None, on_reasoning=None)
|
|
assert turn.content == "plain response"
|
|
assert turn.usage.total_tokens == 7
|