prompture 0.0.40.dev1__py3-none-any.whl → 0.0.42__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prompture/_version.py +2 -2
- prompture/agent.py +11 -11
- prompture/async_agent.py +11 -11
- prompture/async_groups.py +63 -0
- prompture/cost_mixin.py +25 -0
- prompture/drivers/__init__.py +39 -0
- prompture/drivers/async_azure_driver.py +3 -2
- prompture/drivers/async_modelscope_driver.py +286 -0
- prompture/drivers/async_moonshot_driver.py +312 -0
- prompture/drivers/async_openai_driver.py +3 -2
- prompture/drivers/async_openrouter_driver.py +192 -3
- prompture/drivers/async_registry.py +30 -0
- prompture/drivers/async_zai_driver.py +303 -0
- prompture/drivers/azure_driver.py +3 -2
- prompture/drivers/modelscope_driver.py +303 -0
- prompture/drivers/moonshot_driver.py +342 -0
- prompture/drivers/openai_driver.py +3 -2
- prompture/drivers/openrouter_driver.py +244 -40
- prompture/drivers/zai_driver.py +318 -0
- prompture/groups.py +42 -0
- prompture/model_rates.py +2 -0
- prompture/settings.py +16 -1
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/METADATA +1 -1
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/RECORD +28 -22
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/WHEEL +0 -0
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/entry_points.txt +0 -0
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/licenses/LICENSE +0 -0
- {prompture-0.0.40.dev1.dist-info → prompture-0.0.42.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Async Moonshot AI (Kimi) driver using httpx.
|
|
2
|
+
|
|
3
|
+
All pricing comes from models.dev (provider: "moonshotai") — no hardcoded pricing.
|
|
4
|
+
|
|
5
|
+
Moonshot-specific constraints:
|
|
6
|
+
- Temperature clamped to [0, 1] (OpenAI allows [0, 2])
|
|
7
|
+
- tool_choice: "required" not supported — only "auto" or "none"
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from collections.abc import AsyncIterator
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from ..async_driver import AsyncDriver
|
|
20
|
+
from ..cost_mixin import CostMixin, prepare_strict_schema
|
|
21
|
+
from .moonshot_driver import MoonshotDriver
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AsyncMoonshotDriver(CostMixin, AsyncDriver):
|
|
25
|
+
supports_json_mode = True
|
|
26
|
+
supports_json_schema = True
|
|
27
|
+
supports_tool_use = True
|
|
28
|
+
supports_streaming = True
|
|
29
|
+
supports_vision = True
|
|
30
|
+
|
|
31
|
+
MODEL_PRICING = MoonshotDriver.MODEL_PRICING
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
api_key: str | None = None,
|
|
36
|
+
model: str = "kimi-k2-0905-preview",
|
|
37
|
+
endpoint: str = "https://api.moonshot.ai/v1",
|
|
38
|
+
):
|
|
39
|
+
self.api_key = api_key or os.getenv("MOONSHOT_API_KEY")
|
|
40
|
+
if not self.api_key:
|
|
41
|
+
raise ValueError("Moonshot API key not found. Set MOONSHOT_API_KEY env var.")
|
|
42
|
+
self.model = model
|
|
43
|
+
self.base_url = endpoint.rstrip("/")
|
|
44
|
+
self.headers = {
|
|
45
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
46
|
+
"Content-Type": "application/json",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
supports_messages = True
|
|
50
|
+
|
|
51
|
+
def _prepare_messages(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
52
|
+
from .vision_helpers import _prepare_openai_vision_messages
|
|
53
|
+
|
|
54
|
+
return _prepare_openai_vision_messages(messages)
|
|
55
|
+
|
|
56
|
+
async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
|
|
57
|
+
messages = [{"role": "user", "content": prompt}]
|
|
58
|
+
return await self._do_generate(messages, options)
|
|
59
|
+
|
|
60
|
+
async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
|
|
61
|
+
return await self._do_generate(self._prepare_messages(messages), options)
|
|
62
|
+
|
|
63
|
+
async def _do_generate(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
|
|
64
|
+
model = options.get("model", self.model)
|
|
65
|
+
|
|
66
|
+
model_config = self._get_model_config("moonshot", model)
|
|
67
|
+
tokens_param = model_config["tokens_param"]
|
|
68
|
+
supports_temperature = model_config["supports_temperature"]
|
|
69
|
+
|
|
70
|
+
self._validate_model_capabilities(
|
|
71
|
+
"moonshot",
|
|
72
|
+
model,
|
|
73
|
+
using_json_schema=bool(options.get("json_schema")),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
77
|
+
MoonshotDriver._clamp_temperature(opts)
|
|
78
|
+
|
|
79
|
+
data: dict[str, Any] = {
|
|
80
|
+
"model": model,
|
|
81
|
+
"messages": messages,
|
|
82
|
+
}
|
|
83
|
+
data[tokens_param] = opts.get("max_tokens", 512)
|
|
84
|
+
|
|
85
|
+
if supports_temperature and "temperature" in opts:
|
|
86
|
+
data["temperature"] = opts["temperature"]
|
|
87
|
+
|
|
88
|
+
if options.get("json_mode"):
|
|
89
|
+
json_schema = options.get("json_schema")
|
|
90
|
+
if json_schema:
|
|
91
|
+
schema_copy = prepare_strict_schema(json_schema)
|
|
92
|
+
data["response_format"] = {
|
|
93
|
+
"type": "json_schema",
|
|
94
|
+
"json_schema": {
|
|
95
|
+
"name": "extraction",
|
|
96
|
+
"strict": True,
|
|
97
|
+
"schema": schema_copy,
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
else:
|
|
101
|
+
data["response_format"] = {"type": "json_object"}
|
|
102
|
+
|
|
103
|
+
async with httpx.AsyncClient() as client:
|
|
104
|
+
try:
|
|
105
|
+
response = await client.post(
|
|
106
|
+
f"{self.base_url}/chat/completions",
|
|
107
|
+
headers=self.headers,
|
|
108
|
+
json=data,
|
|
109
|
+
timeout=120,
|
|
110
|
+
)
|
|
111
|
+
response.raise_for_status()
|
|
112
|
+
resp = response.json()
|
|
113
|
+
except httpx.HTTPStatusError as e:
|
|
114
|
+
error_msg = f"Moonshot API request failed: {e!s}"
|
|
115
|
+
raise RuntimeError(error_msg) from e
|
|
116
|
+
except Exception as e:
|
|
117
|
+
raise RuntimeError(f"Moonshot API request failed: {e!s}") from e
|
|
118
|
+
|
|
119
|
+
usage = resp.get("usage", {})
|
|
120
|
+
prompt_tokens = usage.get("prompt_tokens", 0)
|
|
121
|
+
completion_tokens = usage.get("completion_tokens", 0)
|
|
122
|
+
total_tokens = usage.get("total_tokens", 0)
|
|
123
|
+
|
|
124
|
+
total_cost = self._calculate_cost("moonshot", model, prompt_tokens, completion_tokens)
|
|
125
|
+
|
|
126
|
+
meta = {
|
|
127
|
+
"prompt_tokens": prompt_tokens,
|
|
128
|
+
"completion_tokens": completion_tokens,
|
|
129
|
+
"total_tokens": total_tokens,
|
|
130
|
+
"cost": round(total_cost, 6),
|
|
131
|
+
"raw_response": resp,
|
|
132
|
+
"model_name": model,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
text = resp["choices"][0]["message"]["content"]
|
|
136
|
+
return {"text": text, "meta": meta}
|
|
137
|
+
|
|
138
|
+
# ------------------------------------------------------------------
|
|
139
|
+
# Tool use
|
|
140
|
+
# ------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
async def generate_messages_with_tools(
|
|
143
|
+
self,
|
|
144
|
+
messages: list[dict[str, Any]],
|
|
145
|
+
tools: list[dict[str, Any]],
|
|
146
|
+
options: dict[str, Any],
|
|
147
|
+
) -> dict[str, Any]:
|
|
148
|
+
"""Generate a response that may include tool calls."""
|
|
149
|
+
model = options.get("model", self.model)
|
|
150
|
+
model_config = self._get_model_config("moonshot", model)
|
|
151
|
+
tokens_param = model_config["tokens_param"]
|
|
152
|
+
supports_temperature = model_config["supports_temperature"]
|
|
153
|
+
|
|
154
|
+
self._validate_model_capabilities("moonshot", model, using_tool_use=True)
|
|
155
|
+
|
|
156
|
+
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
157
|
+
MoonshotDriver._clamp_temperature(opts)
|
|
158
|
+
|
|
159
|
+
data: dict[str, Any] = {
|
|
160
|
+
"model": model,
|
|
161
|
+
"messages": messages,
|
|
162
|
+
"tools": tools,
|
|
163
|
+
}
|
|
164
|
+
data[tokens_param] = opts.get("max_tokens", 512)
|
|
165
|
+
|
|
166
|
+
if supports_temperature and "temperature" in opts:
|
|
167
|
+
data["temperature"] = opts["temperature"]
|
|
168
|
+
|
|
169
|
+
if "tool_choice" in options:
|
|
170
|
+
data["tool_choice"] = options["tool_choice"]
|
|
171
|
+
|
|
172
|
+
MoonshotDriver._sanitize_tool_choice(data)
|
|
173
|
+
|
|
174
|
+
async with httpx.AsyncClient() as client:
|
|
175
|
+
try:
|
|
176
|
+
response = await client.post(
|
|
177
|
+
f"{self.base_url}/chat/completions",
|
|
178
|
+
headers=self.headers,
|
|
179
|
+
json=data,
|
|
180
|
+
timeout=120,
|
|
181
|
+
)
|
|
182
|
+
response.raise_for_status()
|
|
183
|
+
resp = response.json()
|
|
184
|
+
except httpx.HTTPStatusError as e:
|
|
185
|
+
error_msg = f"Moonshot API request failed: {e!s}"
|
|
186
|
+
raise RuntimeError(error_msg) from e
|
|
187
|
+
except Exception as e:
|
|
188
|
+
raise RuntimeError(f"Moonshot API request failed: {e!s}") from e
|
|
189
|
+
|
|
190
|
+
usage = resp.get("usage", {})
|
|
191
|
+
prompt_tokens = usage.get("prompt_tokens", 0)
|
|
192
|
+
completion_tokens = usage.get("completion_tokens", 0)
|
|
193
|
+
total_tokens = usage.get("total_tokens", 0)
|
|
194
|
+
total_cost = self._calculate_cost("moonshot", model, prompt_tokens, completion_tokens)
|
|
195
|
+
|
|
196
|
+
meta = {
|
|
197
|
+
"prompt_tokens": prompt_tokens,
|
|
198
|
+
"completion_tokens": completion_tokens,
|
|
199
|
+
"total_tokens": total_tokens,
|
|
200
|
+
"cost": round(total_cost, 6),
|
|
201
|
+
"raw_response": resp,
|
|
202
|
+
"model_name": model,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
choice = resp["choices"][0]
|
|
206
|
+
text = choice["message"].get("content") or ""
|
|
207
|
+
stop_reason = choice.get("finish_reason")
|
|
208
|
+
|
|
209
|
+
tool_calls_out: list[dict[str, Any]] = []
|
|
210
|
+
for tc in choice["message"].get("tool_calls", []):
|
|
211
|
+
try:
|
|
212
|
+
args = json.loads(tc["function"]["arguments"])
|
|
213
|
+
except (json.JSONDecodeError, TypeError):
|
|
214
|
+
args = {}
|
|
215
|
+
tool_calls_out.append(
|
|
216
|
+
{
|
|
217
|
+
"id": tc["id"],
|
|
218
|
+
"name": tc["function"]["name"],
|
|
219
|
+
"arguments": args,
|
|
220
|
+
}
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
"text": text,
|
|
225
|
+
"meta": meta,
|
|
226
|
+
"tool_calls": tool_calls_out,
|
|
227
|
+
"stop_reason": stop_reason,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
# ------------------------------------------------------------------
|
|
231
|
+
# Streaming
|
|
232
|
+
# ------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
async def generate_messages_stream(
|
|
235
|
+
self,
|
|
236
|
+
messages: list[dict[str, Any]],
|
|
237
|
+
options: dict[str, Any],
|
|
238
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
239
|
+
"""Yield response chunks via Moonshot streaming API."""
|
|
240
|
+
model = options.get("model", self.model)
|
|
241
|
+
model_config = self._get_model_config("moonshot", model)
|
|
242
|
+
tokens_param = model_config["tokens_param"]
|
|
243
|
+
supports_temperature = model_config["supports_temperature"]
|
|
244
|
+
|
|
245
|
+
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
246
|
+
MoonshotDriver._clamp_temperature(opts)
|
|
247
|
+
|
|
248
|
+
data: dict[str, Any] = {
|
|
249
|
+
"model": model,
|
|
250
|
+
"messages": messages,
|
|
251
|
+
"stream": True,
|
|
252
|
+
"stream_options": {"include_usage": True},
|
|
253
|
+
}
|
|
254
|
+
data[tokens_param] = opts.get("max_tokens", 512)
|
|
255
|
+
|
|
256
|
+
if supports_temperature and "temperature" in opts:
|
|
257
|
+
data["temperature"] = opts["temperature"]
|
|
258
|
+
|
|
259
|
+
full_text = ""
|
|
260
|
+
prompt_tokens = 0
|
|
261
|
+
completion_tokens = 0
|
|
262
|
+
|
|
263
|
+
async with (
|
|
264
|
+
httpx.AsyncClient() as client,
|
|
265
|
+
client.stream(
|
|
266
|
+
"POST",
|
|
267
|
+
f"{self.base_url}/chat/completions",
|
|
268
|
+
headers=self.headers,
|
|
269
|
+
json=data,
|
|
270
|
+
timeout=120,
|
|
271
|
+
) as response,
|
|
272
|
+
):
|
|
273
|
+
response.raise_for_status()
|
|
274
|
+
async for line in response.aiter_lines():
|
|
275
|
+
if not line or not line.startswith("data: "):
|
|
276
|
+
continue
|
|
277
|
+
payload = line[len("data: ") :]
|
|
278
|
+
if payload.strip() == "[DONE]":
|
|
279
|
+
break
|
|
280
|
+
try:
|
|
281
|
+
chunk = json.loads(payload)
|
|
282
|
+
except json.JSONDecodeError:
|
|
283
|
+
continue
|
|
284
|
+
|
|
285
|
+
usage = chunk.get("usage")
|
|
286
|
+
if usage:
|
|
287
|
+
prompt_tokens = usage.get("prompt_tokens", 0)
|
|
288
|
+
completion_tokens = usage.get("completion_tokens", 0)
|
|
289
|
+
|
|
290
|
+
choices = chunk.get("choices", [])
|
|
291
|
+
if choices:
|
|
292
|
+
delta = choices[0].get("delta", {})
|
|
293
|
+
content = delta.get("content", "")
|
|
294
|
+
if content:
|
|
295
|
+
full_text += content
|
|
296
|
+
yield {"type": "delta", "text": content}
|
|
297
|
+
|
|
298
|
+
total_tokens = prompt_tokens + completion_tokens
|
|
299
|
+
total_cost = self._calculate_cost("moonshot", model, prompt_tokens, completion_tokens)
|
|
300
|
+
|
|
301
|
+
yield {
|
|
302
|
+
"type": "done",
|
|
303
|
+
"text": full_text,
|
|
304
|
+
"meta": {
|
|
305
|
+
"prompt_tokens": prompt_tokens,
|
|
306
|
+
"completion_tokens": completion_tokens,
|
|
307
|
+
"total_tokens": total_tokens,
|
|
308
|
+
"cost": round(total_cost, 6),
|
|
309
|
+
"raw_response": {},
|
|
310
|
+
"model_name": model,
|
|
311
|
+
},
|
|
312
|
+
}
|
|
@@ -13,7 +13,7 @@ except Exception:
|
|
|
13
13
|
AsyncOpenAI = None
|
|
14
14
|
|
|
15
15
|
from ..async_driver import AsyncDriver
|
|
16
|
-
from ..cost_mixin import CostMixin
|
|
16
|
+
from ..cost_mixin import CostMixin, prepare_strict_schema
|
|
17
17
|
from .openai_driver import OpenAIDriver
|
|
18
18
|
|
|
19
19
|
|
|
@@ -80,12 +80,13 @@ class AsyncOpenAIDriver(CostMixin, AsyncDriver):
|
|
|
80
80
|
if options.get("json_mode"):
|
|
81
81
|
json_schema = options.get("json_schema")
|
|
82
82
|
if json_schema:
|
|
83
|
+
schema_copy = prepare_strict_schema(json_schema)
|
|
83
84
|
kwargs["response_format"] = {
|
|
84
85
|
"type": "json_schema",
|
|
85
86
|
"json_schema": {
|
|
86
87
|
"name": "extraction",
|
|
87
88
|
"strict": True,
|
|
88
|
-
"schema":
|
|
89
|
+
"schema": schema_copy,
|
|
89
90
|
},
|
|
90
91
|
}
|
|
91
92
|
else:
|
|
@@ -2,23 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
import os
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
6
8
|
from typing import Any
|
|
7
9
|
|
|
8
10
|
import httpx
|
|
9
11
|
|
|
10
12
|
from ..async_driver import AsyncDriver
|
|
11
|
-
from ..cost_mixin import CostMixin
|
|
13
|
+
from ..cost_mixin import CostMixin, prepare_strict_schema
|
|
12
14
|
from .openrouter_driver import OpenRouterDriver
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
class AsyncOpenRouterDriver(CostMixin, AsyncDriver):
|
|
16
18
|
supports_json_mode = True
|
|
19
|
+
supports_json_schema = True
|
|
20
|
+
supports_tool_use = True
|
|
21
|
+
supports_streaming = True
|
|
17
22
|
supports_vision = True
|
|
18
23
|
|
|
19
24
|
MODEL_PRICING = OpenRouterDriver.MODEL_PRICING
|
|
20
25
|
|
|
21
|
-
def __init__(self, api_key: str | None = None, model: str = "openai/gpt-
|
|
26
|
+
def __init__(self, api_key: str | None = None, model: str = "openai/gpt-4o-mini"):
|
|
22
27
|
self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")
|
|
23
28
|
if not self.api_key:
|
|
24
29
|
raise ValueError("OpenRouter API key not found. Set OPENROUTER_API_KEY env var.")
|
|
@@ -51,6 +56,13 @@ class AsyncOpenRouterDriver(CostMixin, AsyncDriver):
|
|
|
51
56
|
tokens_param = model_config["tokens_param"]
|
|
52
57
|
supports_temperature = model_config["supports_temperature"]
|
|
53
58
|
|
|
59
|
+
# Validate capabilities against models.dev metadata
|
|
60
|
+
self._validate_model_capabilities(
|
|
61
|
+
"openrouter",
|
|
62
|
+
model,
|
|
63
|
+
using_json_schema=bool(options.get("json_schema")),
|
|
64
|
+
)
|
|
65
|
+
|
|
54
66
|
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
55
67
|
|
|
56
68
|
data = {
|
|
@@ -64,7 +76,19 @@ class AsyncOpenRouterDriver(CostMixin, AsyncDriver):
|
|
|
64
76
|
|
|
65
77
|
# Native JSON mode support
|
|
66
78
|
if options.get("json_mode"):
|
|
67
|
-
|
|
79
|
+
json_schema = options.get("json_schema")
|
|
80
|
+
if json_schema:
|
|
81
|
+
schema_copy = prepare_strict_schema(json_schema)
|
|
82
|
+
data["response_format"] = {
|
|
83
|
+
"type": "json_schema",
|
|
84
|
+
"json_schema": {
|
|
85
|
+
"name": "extraction",
|
|
86
|
+
"strict": True,
|
|
87
|
+
"schema": schema_copy,
|
|
88
|
+
},
|
|
89
|
+
}
|
|
90
|
+
else:
|
|
91
|
+
data["response_format"] = {"type": "json_object"}
|
|
68
92
|
|
|
69
93
|
async with httpx.AsyncClient() as client:
|
|
70
94
|
try:
|
|
@@ -100,3 +124,168 @@ class AsyncOpenRouterDriver(CostMixin, AsyncDriver):
|
|
|
100
124
|
|
|
101
125
|
text = resp["choices"][0]["message"]["content"]
|
|
102
126
|
return {"text": text, "meta": meta}
|
|
127
|
+
|
|
128
|
+
# ------------------------------------------------------------------
|
|
129
|
+
# Tool use
|
|
130
|
+
# ------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
async def generate_messages_with_tools(
|
|
133
|
+
self,
|
|
134
|
+
messages: list[dict[str, Any]],
|
|
135
|
+
tools: list[dict[str, Any]],
|
|
136
|
+
options: dict[str, Any],
|
|
137
|
+
) -> dict[str, Any]:
|
|
138
|
+
"""Generate a response that may include tool calls."""
|
|
139
|
+
model = options.get("model", self.model)
|
|
140
|
+
model_config = self._get_model_config("openrouter", model)
|
|
141
|
+
tokens_param = model_config["tokens_param"]
|
|
142
|
+
supports_temperature = model_config["supports_temperature"]
|
|
143
|
+
|
|
144
|
+
self._validate_model_capabilities("openrouter", model, using_tool_use=True)
|
|
145
|
+
|
|
146
|
+
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
147
|
+
|
|
148
|
+
data: dict[str, Any] = {
|
|
149
|
+
"model": model,
|
|
150
|
+
"messages": messages,
|
|
151
|
+
"tools": tools,
|
|
152
|
+
}
|
|
153
|
+
data[tokens_param] = opts.get("max_tokens", 512)
|
|
154
|
+
|
|
155
|
+
if supports_temperature and "temperature" in opts:
|
|
156
|
+
data["temperature"] = opts["temperature"]
|
|
157
|
+
|
|
158
|
+
async with httpx.AsyncClient() as client:
|
|
159
|
+
try:
|
|
160
|
+
response = await client.post(
|
|
161
|
+
f"{self.base_url}/chat/completions",
|
|
162
|
+
headers=self.headers,
|
|
163
|
+
json=data,
|
|
164
|
+
timeout=120,
|
|
165
|
+
)
|
|
166
|
+
response.raise_for_status()
|
|
167
|
+
resp = response.json()
|
|
168
|
+
except httpx.HTTPStatusError as e:
|
|
169
|
+
error_msg = f"OpenRouter API request failed: {e!s}"
|
|
170
|
+
raise RuntimeError(error_msg) from e
|
|
171
|
+
except Exception as e:
|
|
172
|
+
raise RuntimeError(f"OpenRouter API request failed: {e!s}") from e
|
|
173
|
+
|
|
174
|
+
usage = resp.get("usage", {})
|
|
175
|
+
prompt_tokens = usage.get("prompt_tokens", 0)
|
|
176
|
+
completion_tokens = usage.get("completion_tokens", 0)
|
|
177
|
+
total_tokens = usage.get("total_tokens", 0)
|
|
178
|
+
total_cost = self._calculate_cost("openrouter", model, prompt_tokens, completion_tokens)
|
|
179
|
+
|
|
180
|
+
meta = {
|
|
181
|
+
"prompt_tokens": prompt_tokens,
|
|
182
|
+
"completion_tokens": completion_tokens,
|
|
183
|
+
"total_tokens": total_tokens,
|
|
184
|
+
"cost": round(total_cost, 6),
|
|
185
|
+
"raw_response": resp,
|
|
186
|
+
"model_name": model,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
choice = resp["choices"][0]
|
|
190
|
+
text = choice["message"].get("content") or ""
|
|
191
|
+
stop_reason = choice.get("finish_reason")
|
|
192
|
+
|
|
193
|
+
tool_calls_out: list[dict[str, Any]] = []
|
|
194
|
+
for tc in choice["message"].get("tool_calls", []):
|
|
195
|
+
try:
|
|
196
|
+
args = json.loads(tc["function"]["arguments"])
|
|
197
|
+
except (json.JSONDecodeError, TypeError):
|
|
198
|
+
args = {}
|
|
199
|
+
tool_calls_out.append({
|
|
200
|
+
"id": tc["id"],
|
|
201
|
+
"name": tc["function"]["name"],
|
|
202
|
+
"arguments": args,
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
"text": text,
|
|
207
|
+
"meta": meta,
|
|
208
|
+
"tool_calls": tool_calls_out,
|
|
209
|
+
"stop_reason": stop_reason,
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
# ------------------------------------------------------------------
|
|
213
|
+
# Streaming
|
|
214
|
+
# ------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
async def generate_messages_stream(
|
|
217
|
+
self,
|
|
218
|
+
messages: list[dict[str, Any]],
|
|
219
|
+
options: dict[str, Any],
|
|
220
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
221
|
+
"""Yield response chunks via OpenRouter streaming API."""
|
|
222
|
+
model = options.get("model", self.model)
|
|
223
|
+
model_config = self._get_model_config("openrouter", model)
|
|
224
|
+
tokens_param = model_config["tokens_param"]
|
|
225
|
+
supports_temperature = model_config["supports_temperature"]
|
|
226
|
+
|
|
227
|
+
opts = {"temperature": 1.0, "max_tokens": 512, **options}
|
|
228
|
+
|
|
229
|
+
data: dict[str, Any] = {
|
|
230
|
+
"model": model,
|
|
231
|
+
"messages": messages,
|
|
232
|
+
"stream": True,
|
|
233
|
+
"stream_options": {"include_usage": True},
|
|
234
|
+
}
|
|
235
|
+
data[tokens_param] = opts.get("max_tokens", 512)
|
|
236
|
+
|
|
237
|
+
if supports_temperature and "temperature" in opts:
|
|
238
|
+
data["temperature"] = opts["temperature"]
|
|
239
|
+
|
|
240
|
+
full_text = ""
|
|
241
|
+
prompt_tokens = 0
|
|
242
|
+
completion_tokens = 0
|
|
243
|
+
|
|
244
|
+
async with httpx.AsyncClient() as client, client.stream(
|
|
245
|
+
"POST",
|
|
246
|
+
f"{self.base_url}/chat/completions",
|
|
247
|
+
headers=self.headers,
|
|
248
|
+
json=data,
|
|
249
|
+
timeout=120,
|
|
250
|
+
) as response:
|
|
251
|
+
response.raise_for_status()
|
|
252
|
+
async for line in response.aiter_lines():
|
|
253
|
+
if not line or not line.startswith("data: "):
|
|
254
|
+
continue
|
|
255
|
+
payload = line[len("data: "):]
|
|
256
|
+
if payload.strip() == "[DONE]":
|
|
257
|
+
break
|
|
258
|
+
try:
|
|
259
|
+
chunk = json.loads(payload)
|
|
260
|
+
except json.JSONDecodeError:
|
|
261
|
+
continue
|
|
262
|
+
|
|
263
|
+
# Usage comes in the final chunk
|
|
264
|
+
usage = chunk.get("usage")
|
|
265
|
+
if usage:
|
|
266
|
+
prompt_tokens = usage.get("prompt_tokens", 0)
|
|
267
|
+
completion_tokens = usage.get("completion_tokens", 0)
|
|
268
|
+
|
|
269
|
+
choices = chunk.get("choices", [])
|
|
270
|
+
if choices:
|
|
271
|
+
delta = choices[0].get("delta", {})
|
|
272
|
+
content = delta.get("content", "")
|
|
273
|
+
if content:
|
|
274
|
+
full_text += content
|
|
275
|
+
yield {"type": "delta", "text": content}
|
|
276
|
+
|
|
277
|
+
total_tokens = prompt_tokens + completion_tokens
|
|
278
|
+
total_cost = self._calculate_cost("openrouter", model, prompt_tokens, completion_tokens)
|
|
279
|
+
|
|
280
|
+
yield {
|
|
281
|
+
"type": "done",
|
|
282
|
+
"text": full_text,
|
|
283
|
+
"meta": {
|
|
284
|
+
"prompt_tokens": prompt_tokens,
|
|
285
|
+
"completion_tokens": completion_tokens,
|
|
286
|
+
"total_tokens": total_tokens,
|
|
287
|
+
"cost": round(total_cost, 6),
|
|
288
|
+
"raw_response": {},
|
|
289
|
+
"model_name": model,
|
|
290
|
+
},
|
|
291
|
+
}
|
|
@@ -22,9 +22,12 @@ from .async_grok_driver import AsyncGrokDriver
|
|
|
22
22
|
from .async_groq_driver import AsyncGroqDriver
|
|
23
23
|
from .async_lmstudio_driver import AsyncLMStudioDriver
|
|
24
24
|
from .async_local_http_driver import AsyncLocalHTTPDriver
|
|
25
|
+
from .async_modelscope_driver import AsyncModelScopeDriver
|
|
26
|
+
from .async_moonshot_driver import AsyncMoonshotDriver
|
|
25
27
|
from .async_ollama_driver import AsyncOllamaDriver
|
|
26
28
|
from .async_openai_driver import AsyncOpenAIDriver
|
|
27
29
|
from .async_openrouter_driver import AsyncOpenRouterDriver
|
|
30
|
+
from .async_zai_driver import AsyncZaiDriver
|
|
28
31
|
from .registry import (
|
|
29
32
|
_get_async_registry,
|
|
30
33
|
get_async_driver_factory,
|
|
@@ -90,6 +93,33 @@ register_async_driver(
|
|
|
90
93
|
lambda model=None: AsyncGrokDriver(api_key=settings.grok_api_key, model=model or settings.grok_model),
|
|
91
94
|
overwrite=True,
|
|
92
95
|
)
|
|
96
|
+
register_async_driver(
|
|
97
|
+
"moonshot",
|
|
98
|
+
lambda model=None: AsyncMoonshotDriver(
|
|
99
|
+
api_key=settings.moonshot_api_key,
|
|
100
|
+
model=model or settings.moonshot_model,
|
|
101
|
+
endpoint=settings.moonshot_endpoint,
|
|
102
|
+
),
|
|
103
|
+
overwrite=True,
|
|
104
|
+
)
|
|
105
|
+
register_async_driver(
|
|
106
|
+
"modelscope",
|
|
107
|
+
lambda model=None: AsyncModelScopeDriver(
|
|
108
|
+
api_key=settings.modelscope_api_key,
|
|
109
|
+
model=model or settings.modelscope_model,
|
|
110
|
+
endpoint=settings.modelscope_endpoint,
|
|
111
|
+
),
|
|
112
|
+
overwrite=True,
|
|
113
|
+
)
|
|
114
|
+
register_async_driver(
|
|
115
|
+
"zai",
|
|
116
|
+
lambda model=None: AsyncZaiDriver(
|
|
117
|
+
api_key=settings.zhipu_api_key,
|
|
118
|
+
model=model or settings.zhipu_model,
|
|
119
|
+
endpoint=settings.zhipu_endpoint,
|
|
120
|
+
),
|
|
121
|
+
overwrite=True,
|
|
122
|
+
)
|
|
93
123
|
register_async_driver(
|
|
94
124
|
"airllm",
|
|
95
125
|
lambda model=None: AsyncAirLLMDriver(
|