prompture 0.0.40.dev1__py3-none-any.whl → 0.0.43.dev1__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.
@@ -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-3.5-turbo"):
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
- data["response_format"] = {"type": "json_object"}
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(
@@ -0,0 +1,303 @@
1
+ """Async Z.ai (Zhipu AI) driver using httpx.
2
+
3
+ All pricing comes from models.dev (provider: "zai") — no hardcoded pricing.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ from collections.abc import AsyncIterator
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ from ..async_driver import AsyncDriver
16
+ from ..cost_mixin import CostMixin, prepare_strict_schema
17
+ from .zai_driver import ZaiDriver
18
+
19
+
20
+ class AsyncZaiDriver(CostMixin, AsyncDriver):
21
+ supports_json_mode = True
22
+ supports_json_schema = True
23
+ supports_tool_use = True
24
+ supports_streaming = True
25
+ supports_vision = True
26
+
27
+ MODEL_PRICING = ZaiDriver.MODEL_PRICING
28
+
29
+ def __init__(
30
+ self,
31
+ api_key: str | None = None,
32
+ model: str = "glm-4.7",
33
+ endpoint: str = "https://api.z.ai/api/paas/v4",
34
+ ):
35
+ self.api_key = api_key or os.getenv("ZHIPU_API_KEY")
36
+ if not self.api_key:
37
+ raise ValueError("Zhipu API key not found. Set ZHIPU_API_KEY env var.")
38
+ self.model = model
39
+ self.base_url = endpoint.rstrip("/")
40
+ self.headers = {
41
+ "Authorization": f"Bearer {self.api_key}",
42
+ "Content-Type": "application/json",
43
+ }
44
+
45
+ supports_messages = True
46
+
47
+ def _prepare_messages(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
48
+ from .vision_helpers import _prepare_openai_vision_messages
49
+
50
+ return _prepare_openai_vision_messages(messages)
51
+
52
+ async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
53
+ messages = [{"role": "user", "content": prompt}]
54
+ return await self._do_generate(messages, options)
55
+
56
+ async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
57
+ return await self._do_generate(self._prepare_messages(messages), options)
58
+
59
+ async def _do_generate(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
60
+ model = options.get("model", self.model)
61
+
62
+ model_config = self._get_model_config("zai", model)
63
+ tokens_param = model_config["tokens_param"]
64
+ supports_temperature = model_config["supports_temperature"]
65
+
66
+ self._validate_model_capabilities(
67
+ "zai",
68
+ model,
69
+ using_json_schema=bool(options.get("json_schema")),
70
+ )
71
+
72
+ opts = {"temperature": 1.0, "max_tokens": 512, **options}
73
+
74
+ data: dict[str, Any] = {
75
+ "model": model,
76
+ "messages": messages,
77
+ }
78
+ data[tokens_param] = opts.get("max_tokens", 512)
79
+
80
+ if supports_temperature and "temperature" in opts:
81
+ data["temperature"] = opts["temperature"]
82
+
83
+ if options.get("json_mode"):
84
+ json_schema = options.get("json_schema")
85
+ if json_schema:
86
+ schema_copy = prepare_strict_schema(json_schema)
87
+ data["response_format"] = {
88
+ "type": "json_schema",
89
+ "json_schema": {
90
+ "name": "extraction",
91
+ "strict": True,
92
+ "schema": schema_copy,
93
+ },
94
+ }
95
+ else:
96
+ data["response_format"] = {"type": "json_object"}
97
+
98
+ async with httpx.AsyncClient() as client:
99
+ try:
100
+ response = await client.post(
101
+ f"{self.base_url}/chat/completions",
102
+ headers=self.headers,
103
+ json=data,
104
+ timeout=120,
105
+ )
106
+ response.raise_for_status()
107
+ resp = response.json()
108
+ except httpx.HTTPStatusError as e:
109
+ error_msg = f"Z.ai API request failed: {e!s}"
110
+ raise RuntimeError(error_msg) from e
111
+ except Exception as e:
112
+ raise RuntimeError(f"Z.ai API request failed: {e!s}") from e
113
+
114
+ usage = resp.get("usage", {})
115
+ prompt_tokens = usage.get("prompt_tokens", 0)
116
+ completion_tokens = usage.get("completion_tokens", 0)
117
+ total_tokens = usage.get("total_tokens", 0)
118
+
119
+ total_cost = self._calculate_cost("zai", model, prompt_tokens, completion_tokens)
120
+
121
+ meta = {
122
+ "prompt_tokens": prompt_tokens,
123
+ "completion_tokens": completion_tokens,
124
+ "total_tokens": total_tokens,
125
+ "cost": round(total_cost, 6),
126
+ "raw_response": resp,
127
+ "model_name": model,
128
+ }
129
+
130
+ text = resp["choices"][0]["message"]["content"]
131
+ return {"text": text, "meta": meta}
132
+
133
+ # ------------------------------------------------------------------
134
+ # Tool use
135
+ # ------------------------------------------------------------------
136
+
137
+ async def generate_messages_with_tools(
138
+ self,
139
+ messages: list[dict[str, Any]],
140
+ tools: list[dict[str, Any]],
141
+ options: dict[str, Any],
142
+ ) -> dict[str, Any]:
143
+ """Generate a response that may include tool calls."""
144
+ model = options.get("model", self.model)
145
+ model_config = self._get_model_config("zai", model)
146
+ tokens_param = model_config["tokens_param"]
147
+ supports_temperature = model_config["supports_temperature"]
148
+
149
+ self._validate_model_capabilities("zai", model, using_tool_use=True)
150
+
151
+ opts = {"temperature": 1.0, "max_tokens": 512, **options}
152
+
153
+ data: dict[str, Any] = {
154
+ "model": model,
155
+ "messages": messages,
156
+ "tools": tools,
157
+ }
158
+ data[tokens_param] = opts.get("max_tokens", 512)
159
+
160
+ if supports_temperature and "temperature" in opts:
161
+ data["temperature"] = opts["temperature"]
162
+
163
+ if "tool_choice" in options:
164
+ data["tool_choice"] = options["tool_choice"]
165
+
166
+ async with httpx.AsyncClient() as client:
167
+ try:
168
+ response = await client.post(
169
+ f"{self.base_url}/chat/completions",
170
+ headers=self.headers,
171
+ json=data,
172
+ timeout=120,
173
+ )
174
+ response.raise_for_status()
175
+ resp = response.json()
176
+ except httpx.HTTPStatusError as e:
177
+ error_msg = f"Z.ai API request failed: {e!s}"
178
+ raise RuntimeError(error_msg) from e
179
+ except Exception as e:
180
+ raise RuntimeError(f"Z.ai API request failed: {e!s}") from e
181
+
182
+ usage = resp.get("usage", {})
183
+ prompt_tokens = usage.get("prompt_tokens", 0)
184
+ completion_tokens = usage.get("completion_tokens", 0)
185
+ total_tokens = usage.get("total_tokens", 0)
186
+ total_cost = self._calculate_cost("zai", model, prompt_tokens, completion_tokens)
187
+
188
+ meta = {
189
+ "prompt_tokens": prompt_tokens,
190
+ "completion_tokens": completion_tokens,
191
+ "total_tokens": total_tokens,
192
+ "cost": round(total_cost, 6),
193
+ "raw_response": resp,
194
+ "model_name": model,
195
+ }
196
+
197
+ choice = resp["choices"][0]
198
+ text = choice["message"].get("content") or ""
199
+ stop_reason = choice.get("finish_reason")
200
+
201
+ tool_calls_out: list[dict[str, Any]] = []
202
+ for tc in choice["message"].get("tool_calls", []):
203
+ try:
204
+ args = json.loads(tc["function"]["arguments"])
205
+ except (json.JSONDecodeError, TypeError):
206
+ args = {}
207
+ tool_calls_out.append(
208
+ {
209
+ "id": tc["id"],
210
+ "name": tc["function"]["name"],
211
+ "arguments": args,
212
+ }
213
+ )
214
+
215
+ return {
216
+ "text": text,
217
+ "meta": meta,
218
+ "tool_calls": tool_calls_out,
219
+ "stop_reason": stop_reason,
220
+ }
221
+
222
+ # ------------------------------------------------------------------
223
+ # Streaming
224
+ # ------------------------------------------------------------------
225
+
226
+ async def generate_messages_stream(
227
+ self,
228
+ messages: list[dict[str, Any]],
229
+ options: dict[str, Any],
230
+ ) -> AsyncIterator[dict[str, Any]]:
231
+ """Yield response chunks via Z.ai streaming API."""
232
+ model = options.get("model", self.model)
233
+ model_config = self._get_model_config("zai", model)
234
+ tokens_param = model_config["tokens_param"]
235
+ supports_temperature = model_config["supports_temperature"]
236
+
237
+ opts = {"temperature": 1.0, "max_tokens": 512, **options}
238
+
239
+ data: dict[str, Any] = {
240
+ "model": model,
241
+ "messages": messages,
242
+ "stream": True,
243
+ "stream_options": {"include_usage": True},
244
+ }
245
+ data[tokens_param] = opts.get("max_tokens", 512)
246
+
247
+ if supports_temperature and "temperature" in opts:
248
+ data["temperature"] = opts["temperature"]
249
+
250
+ full_text = ""
251
+ prompt_tokens = 0
252
+ completion_tokens = 0
253
+
254
+ async with (
255
+ httpx.AsyncClient() as client,
256
+ client.stream(
257
+ "POST",
258
+ f"{self.base_url}/chat/completions",
259
+ headers=self.headers,
260
+ json=data,
261
+ timeout=120,
262
+ ) as response,
263
+ ):
264
+ response.raise_for_status()
265
+ async for line in response.aiter_lines():
266
+ if not line or not line.startswith("data: "):
267
+ continue
268
+ payload = line[len("data: ") :]
269
+ if payload.strip() == "[DONE]":
270
+ break
271
+ try:
272
+ chunk = json.loads(payload)
273
+ except json.JSONDecodeError:
274
+ continue
275
+
276
+ usage = chunk.get("usage")
277
+ if usage:
278
+ prompt_tokens = usage.get("prompt_tokens", 0)
279
+ completion_tokens = usage.get("completion_tokens", 0)
280
+
281
+ choices = chunk.get("choices", [])
282
+ if choices:
283
+ delta = choices[0].get("delta", {})
284
+ content = delta.get("content", "")
285
+ if content:
286
+ full_text += content
287
+ yield {"type": "delta", "text": content}
288
+
289
+ total_tokens = prompt_tokens + completion_tokens
290
+ total_cost = self._calculate_cost("zai", model, prompt_tokens, completion_tokens)
291
+
292
+ yield {
293
+ "type": "done",
294
+ "text": full_text,
295
+ "meta": {
296
+ "prompt_tokens": prompt_tokens,
297
+ "completion_tokens": completion_tokens,
298
+ "total_tokens": total_tokens,
299
+ "cost": round(total_cost, 6),
300
+ "raw_response": {},
301
+ "model_name": model,
302
+ },
303
+ }
@@ -10,7 +10,7 @@ try:
10
10
  except Exception:
11
11
  AzureOpenAI = None
12
12
 
13
- from ..cost_mixin import CostMixin
13
+ from ..cost_mixin import CostMixin, prepare_strict_schema
14
14
  from ..driver import Driver
15
15
 
16
16
 
@@ -128,12 +128,13 @@ class AzureDriver(CostMixin, Driver):
128
128
  if options.get("json_mode"):
129
129
  json_schema = options.get("json_schema")
130
130
  if json_schema:
131
+ schema_copy = prepare_strict_schema(json_schema)
131
132
  kwargs["response_format"] = {
132
133
  "type": "json_schema",
133
134
  "json_schema": {
134
135
  "name": "extraction",
135
136
  "strict": True,
136
- "schema": json_schema,
137
+ "schema": schema_copy,
137
138
  },
138
139
  }
139
140
  else: