1"""A small client for any OpenAI-compatible chat completions API with tool calling.
2
3OpenRouter, OpenAI, Google's OpenAI-compatible Gemini endpoint, Groq and a local Ollama all speak this shape, so the
4provider and model are just settings.
5
6Reasoning models (Claude Haiku 5.5, GPT-6 Luna) think by default and bill thinking as output. ``reasoning`` sets
7OpenRouter's ``reasoning.effort`` for every request. When a model does think, its ``reasoning_details`` are kept on
8the assistant message so they go back with the tool results, which Claude needs to carry on after a tool call.
9"""
10
11import asyncio
12import json
13from dataclasses import dataclass
14from typing import Any, Final
15
16import httpx
17from pydantic import BaseModel, Field, ValidationError
18
19RATE_LIMIT_RETRIES: Final = 3
20MAX_RETRY_WAIT_SECONDS: Final = 20.0
21
22
23def _retry_after(response: httpx.Response) -> float:
24 """Seconds to wait after a 429: ``Retry-After`` if the API sent one, capped, else a few seconds."""
25 try:
26 seconds = float(response.headers.get("retry-after", "5"))
27 except ValueError:
28 seconds = 5.0
29 return min(max(seconds, 1.0), MAX_RETRY_WAIT_SECONDS)
30
31
32class LLMError(Exception):
33 """The model API failed or answered with something that isn't a chat completion."""
34
35
36@dataclass(frozen=True, slots=True)
43
44
45@dataclass(frozen=True, slots=True)
[docs]
46class Usage:
47 """Tokens a request used, and what it cost in USD when the API says (OpenRouter does)."""
48
49 input_tokens: int = 0
50 output_tokens: int = 0
51 cost: float | None = None
52
53 def __add__(self, other: Usage) -> Usage:
54 cost = None if self.cost is None and other.cost is None else (self.cost or 0.0) + (other.cost or 0.0)
55 return Usage(self.input_tokens + other.input_tokens, self.output_tokens + other.output_tokens, cost)
56
57
58@dataclass(frozen=True, slots=True)
[docs]
59class Reply:
60 """One model turn: ``message`` goes back into the history verbatim; ``text`` and ``tool_calls`` are parsed."""
61
62 message: dict[str, Any]
63 text: str
64 tool_calls: list[ToolCall]
65 usage: Usage = Usage()
66
67
68class _Function(BaseModel):
69 name: str
70 arguments: str = ""
71
72
73class _ToolCall(BaseModel):
74 id: str
75 function: _Function
76
77
78class _Message(BaseModel):
79 content: str | None = None
80 tool_calls: list[_ToolCall] | None = None
81 reasoning_details: list[dict[str, Any]] | None = None
82
83
84class _Choice(BaseModel):
85 message: _Message
86
87
88class _Usage(BaseModel):
89 prompt_tokens: int = 0
90 completion_tokens: int = 0
91 cost: float | None = None
92
93
94class _Completion(BaseModel):
95 choices: list[_Choice] = Field(min_length=1)
96 usage: _Usage | None = None
97
98
99def _parse_arguments(raw: str) -> dict[str, Any] | None:
100 if not raw.strip():
101 return {}
102 try:
103 parsed = json.loads(raw)
104 except json.JSONDecodeError:
105 return None
106 return parsed if isinstance(parsed, dict) else None
107
108
[docs]
109class ChatClient:
110 """``POST {base_url}/chat/completions`` with tools. Pass ``http`` to reuse a client (tests pass a mocked one)."""
111
112 def __init__(
113 self,
114 base_url: str,
115 api_key: str,
116 model: str,
117 *,
118 reasoning: str | None = None,
119 max_tokens: int = 4000,
120 http: httpx.AsyncClient | None = None,
121 ) -> None:
122 self.model = model
123 self._url = f"{base_url.rstrip('/')}/chat/completions"
124 self._headers = {"Authorization": f"Bearer {api_key}"}
125 self._reasoning = reasoning
126 self._max_tokens = max_tokens
127 self._owns_http = http is None
128 self._http = http or httpx.AsyncClient(timeout=60.0)
129
[docs]
130 async def aclose(self) -> None:
131 """Close the HTTP client if this instance created it."""
132 if self._owns_http:
133 await self._http.aclose()
134
135 async def _post(self, body: dict[str, Any]) -> httpx.Response:
136 """POST ``body``, waiting and retrying when rate limited (429), up to ``RATE_LIMIT_RETRIES`` times."""
137 retries_left = RATE_LIMIT_RETRIES
138 while True:
139 try:
140 response = await self._http.post(self._url, json=body, headers=self._headers)
141 except httpx.HTTPError as exc:
142 msg = f"model API unreachable: {exc}"
143 raise LLMError(msg) from exc
144 if response.status_code != httpx.codes.TOO_MANY_REQUESTS or retries_left == 0:
145 return response
146 retries_left -= 1
147 await asyncio.sleep(_retry_after(response))
148
[docs]
149 async def complete(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None) -> Reply:
150 """One model turn over ``messages``, offering ``tools`` if any."""
151 body: dict[str, Any] = {"model": self.model, "messages": messages, "max_tokens": self._max_tokens}
152 if tools:
153 body["tools"] = tools
154 if self._reasoning:
155 body["reasoning"] = {"effort": self._reasoning}
156 response = await self._post(body)
157 if response.is_error:
158 msg = f"model API answered {response.status_code}: {response.text[:300]}"
159 raise LLMError(msg)
160 try:
161 completion = _Completion.model_validate_json(response.content)
162 except ValidationError as exc:
163 msg = "model API sent something that isn't a chat completion"
164 raise LLMError(msg) from exc
165 message = completion.choices[0].message
166 calls = message.tool_calls or []
167 history_message: dict[str, Any] = {"role": "assistant", "content": message.content or ""}
168 if calls:
169 history_message["tool_calls"] = [
170 {
171 "id": call.id,
172 "type": "function",
173 "function": {"name": call.function.name, "arguments": call.function.arguments},
174 }
175 for call in calls
176 ]
177 if message.reasoning_details:
178 history_message["reasoning_details"] = message.reasoning_details
179 usage = completion.usage or _Usage()
180 return Reply(
181 message=history_message,
182 text=(message.content or "").strip(),
183 tool_calls=[
184 ToolCall(id=call.id, name=call.function.name, arguments=_parse_arguments(call.function.arguments))
185 for call in calls
186 ],
187 usage=Usage(usage.prompt_tokens, usage.completion_tokens, usage.cost),
188 )