批量請求

Batch API 允许你提交大量請求並进行異步處理。这非常適合不需要立即響應的任務,例如數據處理、評測和向量嵌入生成。

工作原理

  1. 創建批量任務 — 上傳包含請求的 JSONL 文件
  2. 提交批量任務 — 開始處理
  3. 監控进度 — 檢查状態直到完成
  4. 获取結果 — 下載輸出文件

創建批量輸入文件

準備一個 JSONL 文件,其中每一行都是一個合法的請求對象:

{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "deepseek/deepseek-v4-pro", "messages": [{"role": "user", "content": "Hello!"}]}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "deepseek/deepseek-v4-pro", "messages": [{"role": "user", "content": "How are you?"}]}}
{"custom_id": "request-3", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "z-ai/glm-5.1", "messages": [{"role": "user", "content": "Translate to French: Hello"}]}}

請求格式

字段類型說明
custom_idstring你自定義的标識符,用於跟蹤该請求
methodstringHTTP 方法(POST
urlstringAPI 端點路徑(例如 /v1/chat/completions
bodyobject請求載荷(與同步 API 相同)

上傳並創建批量任務

# Step 1: Upload the input file
curl https://api.linkastra.ai/v1/files \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "purpose=batch" \
  -F "file=@batch_input.jsonl"

# Step 2: Create the batch
curl https://api.linkastra.ai/v1/batches \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input_file_id": "file-abc123",
    "endpoint": "/v1/chat/completions",
    "completion_window": "24h"
  }'

檢查批量任務状態

curl https://api.linkastra.ai/v1/batches/batch_abc123 \
  -H "Authorization: Bearer YOUR_API_KEY"

状態值

状態說明
validating正在校驗輸入文件
in_progress請求正在處理中
completed所有請求已完成
failed批量任務失败
expired批量任務超出了完成窗口

获取結果

批量任務完成後,下載輸出文件:

curl https://api.linkastra.ai/v1/files/file_output_abc123/content \
  -H "Authorization: Bearer YOUR_API_KEY" > batch_output.jsonl

輸出文件中的每一行對應一個輸入請求:

{"id": "batch_req_abc", "custom_id": "request-1", "response": {"status_code": 200, "body": {"id": "chatcmpl-abc", "choices": [{"message": {"content": "Hello! How can I help you?"}}]}}}

限制

限制項
每個批量任務的最大請求數50,000
最大輸入文件大小200 MB
完成窗口最長 24 小時
最大並發批量任務數10

使用場景

  • 數據集評測 — 在基準數據集上運行提示词
  • 批量向量嵌入 — 為大型文件語料庫生成向量嵌入
  • 內容生成 — 批量處理模板
  • 模型對比 — 在不同模型上運行相同的提示词

最佳實踐

  • 使用 custom_id 將輸出與你的輸入记录一一對應
  • 先用小批量任務驗證,再逐步擴大規模
  • 監控批量任務状態,並採用指數退避策略进行輪询
  • 將超大的工作負載拆分為多個批量任務

相關文件