Write batch_outputs to a file or upload to a URL. path_or_url: The path or URL to write batch_outputs to. batch_outputs: The list of batch outputs to write. output_tmp_dir: The directory to store the output file before uploading it to the output URL.
(path_or_url: str, batch_outputs: list[BatchRequestOutput], output_tmp_dir: str)
| 232 | |
| 233 | |
| 234 | async def write_file(path_or_url: str, batch_outputs: list[BatchRequestOutput], output_tmp_dir: str) -> None: |
| 235 | """ |
| 236 | Write batch_outputs to a file or upload to a URL. |
| 237 | path_or_url: The path or URL to write batch_outputs to. |
| 238 | batch_outputs: The list of batch outputs to write. |
| 239 | output_tmp_dir: The directory to store the output file before uploading it |
| 240 | to the output URL. |
| 241 | """ |
| 242 | if path_or_url.startswith("http://") or path_or_url.startswith("https://"): |
| 243 | if output_tmp_dir is None: |
| 244 | console_logger.info("Writing outputs to memory buffer") |
| 245 | output_buffer = StringIO() |
| 246 | for o in batch_outputs: |
| 247 | print(o.model_dump_json(), file=output_buffer) |
| 248 | output_buffer.seek(0) |
| 249 | console_logger.info("Uploading outputs to %s", path_or_url) |
| 250 | await upload_data( |
| 251 | path_or_url, |
| 252 | output_buffer.read().strip().encode("utf-8"), |
| 253 | from_file=False, |
| 254 | ) |
| 255 | else: |
| 256 | # Write responses to a temporary file and then upload it to the URL. |
| 257 | with tempfile.NamedTemporaryFile( |
| 258 | mode="w", |
| 259 | encoding="utf-8", |
| 260 | dir=output_tmp_dir, |
| 261 | prefix="tmp_batch_output_", |
| 262 | suffix=".jsonl", |
| 263 | ) as f: |
| 264 | console_logger.info("Writing outputs to temporary local file %s", f.name) |
| 265 | await write_local_file(f.name, batch_outputs) |
| 266 | console_logger.info("Uploading outputs to %s", path_or_url) |
| 267 | await upload_data(path_or_url, f.name, from_file=True) |
| 268 | else: |
| 269 | console_logger.info("Writing outputs to local file %s", path_or_url) |
| 270 | await write_local_file(path_or_url, batch_outputs) |
| 271 | |
| 272 | |
| 273 | def random_uuid() -> str: |