1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
"""
Batch providers for the judge system.
Supports Anthropic and xAI batch APIs.
"""
import os
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, Iterator, List, Optional
import anthropic
try:
import openai
except ImportError:
openai = None
try:
from xai_sdk import Client as XAIClient
except ImportError:
XAIClient = None
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
@dataclass
class BatchRequest:
custom_id: str
params: Dict[str, Any]
@dataclass
class BatchResult:
custom_id: str
text: str
error: Optional[str] = None
usage: Optional[Dict[str, int]] = None
latency_ms: Optional[int] = None
model: Optional[str] = None
class BatchProvider(ABC):
@abstractmethod
def submit_batch(self, requests: List[BatchRequest]) -> str:
pass
@abstractmethod
def poll_batch(self, batch_id: str, poll_interval: int = 30) -> None:
pass
@abstractmethod
def collect_results(self, batch_id: str) -> Iterator[BatchResult]:
pass
@abstractmethod
def build_request(
self,
custom_id: str,
prompt: str,
model: str,
temperature: float,
max_tokens: int = 4096,
) -> BatchRequest:
pass
class AnthropicBatchProvider(BatchProvider):
def __init__(self, api_key: Optional[str] = None):
key = api_key or os.environ.get("ANTHROPIC_API_KEY")
if not key:
raise ValueError("ANTHROPIC_API_KEY not set")
self.client = anthropic.Anthropic(api_key=key)
def build_request(
self,
custom_id: str,
prompt: str,
model: str,
temperature: float,
max_tokens: int = 4096,
) -> BatchRequest:
return BatchRequest(
custom_id=custom_id,
params={
"model": model,
"max_tokens": max_tokens,
"temperature": temperature,
"messages": [{"role": "user", "content": prompt}],
},
)
def submit_batch(self, requests: List[BatchRequest]) -> str:
anthropic_requests = [
{
"custom_id": r.custom_id,
"params": r.params,
}
for r in requests
]
response = self.client.messages.batches.create(requests=anthropic_requests)
return response.id
def poll_batch(self, batch_id: str, poll_interval: int = 30) -> None:
while True:
batch = self.client.messages.batches.retrieve(batch_id)
status = batch.processing_status
counts = batch.request_counts
print(
f" Batch {batch_id}: {status} "
f"(succeeded={counts.succeeded}, "
f"processing={counts.processing}, "
f"errored={counts.errored})"
)
if status == "ended":
return
time.sleep(poll_interval)
def collect_results(self, batch_id: str) -> Iterator[BatchResult]:
for result in self.client.messages.batches.results(batch_id):
custom_id = result.custom_id
if result.result.type == "succeeded":
content = result.result.message.content
if hasattr(content, "__iter__") and not isinstance(content, str):
for block in content:
if hasattr(block, "text"):
text = block.text
break
else:
text = ""
else:
text = str(content)
yield BatchResult(custom_id=custom_id, text=text)
else:
yield BatchResult(
custom_id=custom_id, text="", error=f"ERROR: {result.result.type}"
)
class XAIBatchProvider(BatchProvider):
def __init__(self, api_key: Optional[str] = None):
if XAIClient is None:
raise ImportError("xai-sdk not installed. Run: uv add xai-sdk")
key = api_key or os.environ.get("XAI_API_KEY")
if not key:
raise ValueError("XAI_API_KEY not set")
self.client = XAIClient(api_key=key)
def build_request(
self,
custom_id: str,
prompt: str,
model: str,
temperature: float,
max_tokens: int = 4096,
) -> BatchRequest:
return BatchRequest(
custom_id=custom_id,
params={
"model": model,
"max_tokens": max_tokens,
"temperature": temperature,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt},
],
},
)
def submit_batch(self, requests: List[BatchRequest]) -> str:
from xai_sdk.chat import system as xai_system, user as xai_user
batch = self.client.batch.create(batch_name=f"judge_batch_{int(time.time())}")
batch_requests = []
for req in requests:
chat = self.client.chat.create(
model=req.params["model"],
batch_request_id=req.custom_id,
)
for msg in req.params["messages"]:
if msg["role"] == "system":
chat.append(xai_system(msg["content"]))
else:
chat.append(xai_user(msg["content"]))
batch_requests.append(chat)
self.client.batch.add(batch_id=batch.batch_id, batch_requests=batch_requests)
return batch.batch_id
def poll_batch(self, batch_id: str, poll_interval: int = 30) -> None:
while True:
batch = self.client.batch.get(batch_id=batch_id)
state = batch.state
print(
f" Batch {batch_id}: "
f"(pending={state.num_pending}, "
f"success={state.num_success}, "
f"error={state.num_error})"
)
if state.num_pending == 0:
return
time.sleep(poll_interval)
def collect_results(self, batch_id: str) -> Iterator[BatchResult]:
pagination_token = None
while True:
page = self.client.batch.list_batch_results(
batch_id=batch_id,
limit=100,
pagination_token=pagination_token,
)
for result in page.succeeded:
rid = result.batch_request_id
text = result.response.content
yield BatchResult(custom_id=rid, text=text)
for result in page.failed:
yield BatchResult(
custom_id=result.batch_request_id,
text="",
error=result.error_message,
)
if page.pagination_token is None:
break
pagination_token = page.pagination_token
class OpenAIBatchProvider(BatchProvider):
def __init__(self, api_key: Optional[str] = None):
if openai is None:
raise ImportError("openai not installed. Run: uv add openai")
key = api_key or os.environ.get("OPENAI_API_KEY")
if not key:
raise ValueError("OPENAI_API_KEY not set")
self.client = openai.OpenAI(api_key=key)
def build_request(
self,
custom_id: str,
prompt: str,
model: str,
temperature: float,
max_tokens: int = 4096,
) -> BatchRequest:
return BatchRequest(
custom_id=custom_id,
params={
"model": model,
"max_tokens": max_tokens,
"temperature": temperature,
"messages": [{"role": "user", "content": prompt}],
},
)
def submit_batch(self, requests: List[BatchRequest]) -> str:
openai_requests = [
{
"custom_id": r.custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": r.params["model"],
"max_tokens": r.params["max_tokens"],
"temperature": r.params["temperature"],
"messages": r.params["messages"],
},
}
for r in requests
]
response = self.client.batches.create(
input_file_id=self._upload_requests(openai_requests),
endpoint="/v1/chat/completions",
completion_window="24h",
)
return response.id
def _upload_requests(self, requests: List[Dict]) -> str:
import json
content = "\n".join(json.dumps(req) for req in requests)
import io
file_obj = io.BytesIO(content.encode("utf-8"))
upload = self.client.files.create(file=file_obj, purpose="batch")
return upload.id
def poll_batch(self, batch_id: str, poll_interval: int = 30) -> None:
while True:
batch = self.client.batches.retrieve(batch_id)
status = batch.status
counts = batch.request_counts
print(
f" Batch {batch_id}: {status} "
f"(completed={counts.completed}, "
f"failed={counts.failed}, "
f"total={counts.total})"
)
if status in ["completed", "failed", "expired"]:
return
time.sleep(poll_interval)
def collect_results(self, batch_id: str) -> Iterator[BatchResult]:
batch = self.client.batches.retrieve(batch_id)
if not batch.output_file_id:
return
response = self.client.files.content(batch.output_file_id)
import json
for line in response.text.strip().split("\n"):
if not line:
continue
data = json.loads(line)
custom_id = data.get("custom_id", "")
if data.get("error"):
yield BatchResult(
custom_id=custom_id,
text="",
error=data["error"].get("message", "Unknown error"),
)
else:
body = data["response"]["body"]
msg = body["choices"][0]["message"]
text = msg.get("content", "")
usage = body.get("usage", {})
yield BatchResult(
custom_id=custom_id,
text=text,
usage=usage,
model=body.get("model", ""),
)
|