summaryrefslogtreecommitdiff
path: root/src/judge/batch_providers.py
blob: 1a6ca27cfc0beb72a25ffba046adf763b96c79f4 (plain)
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
"""
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:
    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


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