84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
"""Shared test helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import inspect
|
|
import json
|
|
from typing import Any
|
|
from collections.abc import Callable
|
|
|
|
from airouter.provider import AssistantTurn, ToolCall, Usage
|
|
|
|
|
|
class FakeProvider:
|
|
"""Duck-typed replacement for OpenAIClient."""
|
|
|
|
def __init__(self, responders: dict[str, Any] | Callable[..., Any]) -> None:
|
|
self.responders = responders
|
|
self.calls: list[dict[str, Any]] = []
|
|
self.closed = False
|
|
self._counts: dict[str, int] = {}
|
|
|
|
async def stream_chat(
|
|
self,
|
|
*,
|
|
model: str,
|
|
messages: list[dict[str, Any]],
|
|
tools: list[dict[str, Any]] | None = None,
|
|
session_id: str,
|
|
on_text: Callable[[str], None] | None = None,
|
|
on_reasoning: Callable[[str], None] | None = None,
|
|
temperature: float | None = 0.2,
|
|
max_tokens: int | None = None,
|
|
extra_headers: dict[str, str] | None = None,
|
|
) -> AssistantTurn:
|
|
self.calls.append(
|
|
{
|
|
"model": model,
|
|
"messages": messages,
|
|
"tools": tools,
|
|
"session_id": session_id,
|
|
}
|
|
)
|
|
count = self._counts.get(model, 0)
|
|
self._counts[model] = count + 1
|
|
responder = self.responders[model] if isinstance(self.responders, dict) else self.responders
|
|
if callable(responder):
|
|
try:
|
|
result = responder(messages, count, session_id)
|
|
except TypeError:
|
|
result = responder(messages)
|
|
elif isinstance(responder, list):
|
|
if count >= len(responder):
|
|
result = responder[-1]
|
|
else:
|
|
result = responder[count]
|
|
else:
|
|
result = responder
|
|
if inspect.isawaitable(result):
|
|
result = await result
|
|
if isinstance(result, str):
|
|
result = AssistantTurn(content=result)
|
|
if not result.usage.total_tokens:
|
|
result.usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15)
|
|
if result.content and on_text:
|
|
on_text(result.content)
|
|
if result.reasoning and on_reasoning:
|
|
on_reasoning(result.reasoning)
|
|
return result
|
|
|
|
async def aclose(self) -> None:
|
|
self.closed = True
|
|
|
|
|
|
def tool_call(name: str, args: dict[str, Any], call_id: str = "call_1") -> ToolCall:
|
|
return ToolCall(id=call_id, name=name, arguments=json.dumps(args, ensure_ascii=False))
|
|
|
|
|
|
def turn_with_tool(name: str, args: dict[str, Any], call_id: str = "call_1") -> AssistantTurn:
|
|
return AssistantTurn(tool_calls=[tool_call(name, args, call_id)], finish_reason="tool_calls")
|
|
|
|
|
|
def turn_text(text: str) -> AssistantTurn:
|
|
return AssistantTurn(content=text, finish_reason="stop")
|