Retrieve and parse results from a completed batch. Args: client: An initialized OpenAI client. batch_info: A BatchJobInfo from a completed batch. Returns: List of BatchResult objects, one per request, ordered by their custom_id.
(
client: OpenAI,
batch_info: BatchJobInfo,
)
| 248 | |
| 249 | |
| 250 | def retrieve_batch_results( |
| 251 | client: OpenAI, |
| 252 | batch_info: BatchJobInfo, |
| 253 | ) -> List[BatchResult]: |
| 254 | """Retrieve and parse results from a completed batch. |
| 255 | |
| 256 | Args: |
| 257 | client: An initialized OpenAI client. |
| 258 | batch_info: A BatchJobInfo from a completed batch. |
| 259 | |
| 260 | Returns: |
| 261 | List of BatchResult objects, one per request, |
| 262 | ordered by their custom_id. |
| 263 | """ |
| 264 | if not batch_info.output_file_id: |
| 265 | raise ValueError( |
| 266 | f"Batch {batch_info.batch_id} has no output file. " |
| 267 | f"Status: {batch_info.status}" |
| 268 | ) |
| 269 | |
| 270 | logger.info(f"Downloading results from {batch_info.output_file_id}...") |
| 271 | |
| 272 | output_content = client.files.content(batch_info.output_file_id).text |
| 273 | results = [] |
| 274 | |
| 275 | for line in output_content.strip().split("\n"): |
| 276 | if not line: |
| 277 | continue |
| 278 | |
| 279 | response_data = json.loads(line) |
| 280 | custom_id = response_data["custom_id"] |
| 281 | |
| 282 | error = response_data.get("error") |
| 283 | if error: |
| 284 | results.append(BatchResult( |
| 285 | custom_id=custom_id, |
| 286 | error=json.dumps(error), |
| 287 | )) |
| 288 | continue |
| 289 | |
| 290 | body = response_data.get("response", {}).get("body", {}) |
| 291 | choices = body.get("choices", []) |
| 292 | |
| 293 | if choices: |
| 294 | content = choices[0].get("message", {}).get("content", "") |
| 295 | usage = body.get("usage") |
| 296 | results.append(BatchResult( |
| 297 | custom_id=custom_id, |
| 298 | content=content, |
| 299 | usage=usage, |
| 300 | )) |
| 301 | else: |
| 302 | results.append(BatchResult( |
| 303 | custom_id=custom_id, |
| 304 | error="No choices returned in response", |
| 305 | )) |
| 306 | |
| 307 | # Sort by custom_id to maintain order |