Репозитории /
AiRouter /
tests/test_provider.py
test_provider.py
| 1 | from __future__ import annotations |
| 2 | |
| 3 | import asyncio |
| 4 | import json |
| 5 | |
| 6 | from airouter.provider import OpenAIClient, Usage |
| 7 | |
| 8 | |
| 9 | class FakeResponse: |
| 10 | def __init__(self, lines): |
| 11 | self.lines = lines |
| 12 | |
| 13 | async def aiter_lines(self): |
| 14 | for line in self.lines: |
| 15 | yield line |
| 16 | |
| 17 | |
| 18 | def test_sse_accumulates_text_and_tool_calls(): |
| 19 | client = object.__new__(OpenAIClient) |
| 20 | chunks = [ |
| 21 | 'data: {"choices":[{"delta":{"role":"assistant","content":"Hel"}}]}', |
| 22 | 'data: {"choices":[{"delta":{"content":"lo","tool_calls":[{"index":0,"id":"call_1","function":{"name":"bash","arguments":"{\\"comm"}}]}}]}', |
| 23 | 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"and\\":\\"echo hi\\"}"}}]},"finish_reason":"tool_calls"}]}', |
| 24 | '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"}}}', |
| 25 | "data: [DONE]", |
| 26 | ] |
| 27 | text = [] |
| 28 | |
| 29 | async def scenario(): |
| 30 | return await client._read_sse(FakeResponse(chunks), on_text=text.append, on_reasoning=None) |
| 31 | |
| 32 | turn = asyncio.run(scenario()) |
| 33 | assert turn.content == "Hello" |
| 34 | assert len(turn.tool_calls) == 1 |
| 35 | assert turn.tool_calls[0].name == "bash" |
| 36 | assert json.loads(turn.tool_calls[0].arguments) == {"command": "echo hi"} |
| 37 | assert turn.finish_reason == "tool_calls" |
| 38 | assert turn.usage.prompt_tokens == 100 |
| 39 | assert turn.usage.completion_tokens == 20 |
| 40 | assert turn.usage.reasoning_tokens == 5 |
| 41 | assert turn.usage.cache_read_tokens == 80 |
| 42 | assert turn.usage.cost == 0.001 |
| 43 | assert turn.usage.allowance == 0.002 |
| 44 | assert turn.usage.billing_source == "go" |
| 45 | assert "".join(text) == "Hello" |
| 46 | |
| 47 | |
| 48 | def test_usage_roundtrip(): |
| 49 | usage = Usage(prompt_tokens=1, completion_tokens=2, total_tokens=3, cost=0.5) |
| 50 | assert Usage.from_dict(usage.to_dict()).to_dict() == usage.to_dict() |
| 51 | |
| 52 | |
| 53 | def test_json_response_fallback(): |
| 54 | client = object.__new__(OpenAIClient) |
| 55 | data = { |
| 56 | "choices": [ |
| 57 | { |
| 58 | "finish_reason": "stop", |
| 59 | "message": {"role": "assistant", "content": "plain response"}, |
| 60 | } |
| 61 | ], |
| 62 | "usage": {"prompt_tokens": 3, "completion_tokens": 4}, |
| 63 | } |
| 64 | turn = client._turn_from_json(data, on_text=None, on_reasoning=None) |
| 65 | assert turn.content == "plain response" |
| 66 | assert turn.usage.total_tokens == 7 |