Appearance
POST /v1/batches 是 Kimi Batch API 的入口接口,用于提交批量推理任务。需先上传 purpose=batch 的 JSONL 文件,再用返回的 file_id 创建批任务,指定处理时间窗口(12h~7d)。本文含完整参数说明和 Python/TS 代码示例。
创建批处理任务
接口信息
POST https://api.moonshot.cn/v1/batches
Authorization: Bearer {MOONSHOT_API_KEY}
Content-Type: application/json详细使用流程参考 Batch API 完整指南
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
input_file_id | string | ✅ | 上传 JSONL 文件后返回的文件 ID |
endpoint | string | ✅ | 目前仅支持 "/v1/chat/completions" |
completion_window | string | ✅ | 任务处理时间窗口,支持 12h、1d、3d,最小 12h,最大 7d |
metadata | object | ❌ | 自定义键值对,最多 16 个,key ≤ 64 字符,value ≤ 512 字符 |
请求示例
typescript
const response = await fetch("https://api.moonshot.cn/v1/batches", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOONSHOT_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
input_file_id: "file-abc123",
endpoint: "/v1/chat/completions",
completion_window: "24h",
metadata: {
job_name: "daily-analysis",
environment: "production",
},
}),
});
const batch = await response.json();
console.log("批任务 ID:", batch.id);
console.log("状态:", batch.status);python
import os
import requests
response = requests.post(
"https://api.moonshot.cn/v1/batches",
headers={
"Authorization": f"Bearer {os.environ['MOONSHOT_API_KEY']}",
"Content-Type": "application/json",
},
json={
"input_file_id": "file-abc123",
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
},
)
batch = response.json()
print(f"批任务 ID: {batch['id']}, 状态: {batch['status']}")响应(BatchObject)
| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 批任务唯一 ID |
object | string | 固定值 "batch" |
status | string | 任务状态,见下表 |
input_file_id | string | 输入文件 ID |
output_file_id | string | 结果文件 ID(完成后可用) |
error_file_id | string | 失败请求的错误文件 ID |
request_counts | object | {completed, failed, total} |
created_at | int | 创建时间(Unix 时间戳) |
任务状态:
| 状态 | 说明 |
|---|---|
validating | 校验输入文件中 |
in_progress | 正在执行 |
finalizing | 准备结果中 |
completed | 已完成,可下载结果 |
failed | 校验失败 |
expired | 超出 completion_window 时间 |
cancelling | 取消中 |
cancelled | 已取消 |
常见问题
Q: JSONL 输入文件格式是什么?
A: 每行一个 JSON 对象,包含 custom_id(自定义标识)和 body(完整的 chat completions 请求体)。详见 Batch API 指南。
Q: completion_window 填写多少合适?
A: 批处理任务使用低优先级队列,通常比在线 API 慢。建议给出至少 2 倍于预估执行时间的余量,常规任务用 24h,大批量任务用 3d。
Q: 创建后可以修改 completion_window 吗?
A: 不可以。如需调整,只能取消后重新创建任务。