batch-inference
БесплатноБез исполняемых скриптовНе проверенBatch RAG for high-volume ingest and bulk query scenarios. Covers OpenAI Batch API (50% discount, 24h SLA), Anthropic Message Batches API, Voyage AI and…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Batch Inference for RAG
Batch APIs cut cost 50% and unlock much higher throughput than the real-time path. Use them wherever a 24-hour SLA is acceptable: initial ingest, re-embed after model swap, bulk metadata extraction, nightly eval runs, large-scale query replay.
When to Batch vs Stream
| Workload | Batch? |
|---|---|
| Initial corpus embedding (millions of chunks) | Yes |
| Re-embed after model swap | Yes |
| Nightly eval run on golden set | Yes |
| Extracting entities/summaries/keywords during ingest | Yes |
| User-facing chat query | No |
| Real-time retrieval embedding (single query) | No |
| Sub-100 ms reranker call | No |
OpenAI Batch API (50% Discount, 24h SLA)
Works for /v1/chat/completions, /v1/embeddings, /v1/completions. Input is a JSONL file where each line is a self-contained request.
from openai import OpenAI
import json, pathlib
client = OpenAI()
# 1. Prepare JSONL
requests = [
{
"custom_id": f"chunk-{i}",
"method": "POST",
"url": "/v1/embeddings",
"body": {"model": "text-embedding-3-small", "input": chunk, "dimensions": 512},
}
for i, chunk in enumerate(chunks)
]
pathlib.Path("batch.jsonl").write_text("\n".join(json.dumps(r) for r in requests))
# 2. Upload file
fobj = client.files.create(file=open("batch.jsonl", "rb"), purpose="batch")
# 3. Create batch job
batch = client.batches.create(
input_file_id=fobj.id,
endpoint="/v1/embeddings",
completion_window="24h",
metadata={"project": "kb_v2_embed"},
)
print(batch.id, batch.status)
Poll:
while batch.status in {"validating", "in_progress", "finalizing"}:
time.sleep(60)
batch = client.batches.retrieve(batch.id)
print(batch.status, batch.request_counts)
Download + parse:
out = client.files.content(batch.output_file_id).text
for line in out.splitlines():
row = json.loads(line)
vec = row["response"]["body"]["data"][0]["embedding"]
upsert(row["custom_id"], vec)
Limits: max 50k requests per batch, max 200 MB per file, max 50 queued batches per account. Split big jobs into chunks and upload in parallel.
Anthropic Message Batches API (50% Discount, 24h SLA)
import anthropic
client = anthropic.Anthropic()
requests = [
{
"custom_id": f"summarize-{i}",
"params": {
"model": "claude-sonnet-4-5",
"max_tokens": 512,
"messages": [{"role": "user", "content": f"Summarize:\n{doc}"}],
},
}
for i, doc in enumerate(docs)
]
batch = client.messages.batches.create(requests=requests)
print(batch.id, batch.processing_status)
# Poll
while batch.processing_status in {"in_progress"}:
time.sleep(60)
batch = client.messages.batches.retrieve(batch.id)
for result in client.messages.batches.results(batch.id):
if result.result.type == "succeeded":
text = result.result.message.content[0].text
store(result.custom_id, text)
Limits: 100k requests per batch, 256 MB file size. Works with prompt caching — cache prefixes still apply for 50% stacking with batch's 50%, effectively 75% off the prefix tokens.
Voyage AI Batch Embeddings
Voyage supports batched calls in real-time (no separate batch endpoint), but the per-call batch size is high (128 inputs):
import voyageai
vo = voyageai.Client()
def embed_batch(texts, model="voyage-3"):
# 128-input batches optimal on API
out = []
for i in range(0, len(texts), 128):
r = vo.embed(texts[i:i+128], model=model, input_type="document")
out.extend(r.embeddings)
return out
Cohere Embed Jobs (Async Bulk)
import cohere
co = cohere.ClientV2()
job = co.embed_jobs.create(
dataset_id="my-dataset-id",
model="embed-v4.0",
input_type="search_document",
)
# Poll status, then download dataset with vectors attached
Good for datasets already in Cohere's dataset store; less useful if you're not in that ecosystem.
Query-Time vs Ingest-Time
- Ingest-time batch: huge wins. You have all inputs up front; 50% discount + parallelism; eventual consistency fine.
- Query-time batch: only viable if you micro-batch multiple near-simultaneous user queries (50–200 ms window). Usually not worth the complexity for chat UX.
Parallel Embedding with asyncio
Real-time path where you want pipeline parallelism without hitting a batch API:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
sem = asyncio.Semaphore(16) # cap concurrent API calls
async def embed_one(batch):
async with sem:
r = await client.embeddings.create(model="text-embedding-3-small", input=batch)
return [d.embedding for d in r.data]
async def embed_all(chunks, batch_size=64):
tasks = [embed_one(chunks[i:i+batch_size]) for i in range(0, len(chunks), batch_size)]
return [v for sub in await asyncio.gather(*tasks) for v in sub]
vecs = asyncio.run(embed_all(all_chunks))
R
Установить batch-inference в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл batch-inference?
Batch RAG for high-volume ingest and bulk query scenarios. Covers OpenAI Batch API (50% discount, 24h SLA), Anthropic Message Batches API, Voyage AI and Cohere batch embeddings, ingestion-time vs query-time batching, async/Ray parallelism, parallel writes to vector DBs, and rate-limit coordination across workers. USE WHEN: user mentions "batch API", "OpenAI batch", "Anthropic batches", "bulk embedding", "Ray embeddings", "parallel ingest", "batch RAG" DO NOT USE FOR: streaming single-query latency - use `rag-production`; cost-dashboards - use `cost-allocation`; LLM gateway routing - use `llm-gateway`
Как установить скилл batch-inference?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл batch-inference запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic