翻篇收录说明
翻篇网页快照

Batch processing: LLMBatchOperator — apache-airflow-providers-common-ai Documentation

https://airflow.apache.org/docs/apache-airflow-providers-common-ai/stable/operators/llm_batch.html

最近抓取:2026-12-04 17:30:38(北京时间)

最近内容变化:2026-12-02 04:28:59(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

正文摘录

Home Operators and decorators Batch processing: LLMBatchOperator ↑↓ Navigate ⏎ Select Esc Close Batch processing: LLMBatchOperator¶ Use LLMBatchOperator to run many prompts through a provider’s batch API instead of one synchronous call per prompt: roughly half the per-token cost of LLMOperator, in exchange for up to a 24-hour turnaround. The "<provider>:<model>" prefix of model_id selects the OpenAI or Anthropic adapter; llm_conn_id must be a pydanticai connection. See also Connection configuration Results never go to XCom¶ This is the most important way LLMBatchOperator differs from LLMOperator: results are written as JSONL to result_path (an object storage directory), and the XCom value is a small manifest describing where to find them and how many requests landed in each outcome bucket. A batch can have up to 100,000 results, far too much to push through XCom. airflow/providers/common/ai/example_dags/example_llm_batch.py[source] @dag(tags=["example"]) def example_llm_batch_operator(): classify = LLMBatchOperator( task_id="classify_reviews", requests=[f"Review: {review!r}" for review in REVIEWS], result_path=f"{RESULT_ROOT}/classify", llm_conn_id="pydanticai_default", model_id="openai:gpt-5-mini", system_prompt="Classify the sentiment of this product review.", output_type=Sentiment, deferrable=True, ) summarize_manifest(classify.output) The manifest¶ The XCom value is a JSON object with a stable shape (schema_version: 1): Key Meaning result_uri The JSONL file, {result_path}/{custom_id_prefix}.jsonl. request_count How many requests were submitted. Always equals the sum of counts. counts succeeded, errored (the provider rejected the request), invalid_output (the model answered but not in the requested schema), expired, cancelled and missing (the provider never reported an outcome for the request). terminal_reason succeeded when every request succeeded, expired if any request expired, cancelled if any was cancelled, otherwise partial. rejoin_key / ordered Always "index" and false: rows arrive in provider order, and each row’s index is the position of its input in requests. batch_id, adapter, llm_conn_id, model_id, output_type_ref, structured, submitted_at, completed_at Provenance for the run. duplicate_result_count, out_of_range_result_count Anomalies the provider stream contained and the merge dropped. Normally zero. The result rows¶ Every request gets exactly one JSONL row with the same keys: {"custom_id": "3f9c...-0", "index": 0, "status": "success", "output": {"label": "positive", "confidence": 0.93}, "raw_output": null, "error": null, "model": "gpt-5", "usage": {"input_tokens": 41, "output_tokens": 12}, "finish_reason": "stop"} status is one of success, error, invalid_output, expired, cancelled or missing. output is set only for success; raw_output preserves what the model returned when validation failed; error carries the provider’s type, message and code for provider-side failures. The manifest’s counts keys use the past tense (succeeded, errored) while row statuses use the bare word; the other buckets spell the same. A downstream task reads the rows back from result_uri with ObjectStoragePath and rejoins them to its inputs on index: airflow/providers/common/ai/example_dags/example_llm_batch.py[source] @task def summarize_manifest(manifest: dict) -> dict[str, int]: """Read the landed JSONL rows back; the XCom value is only the manifest.""" rows = [ json.loads(line) for line in ObjectStoragePath(manifest["result_uri"]).read_text().splitlines() if line ] by_label: dict[str, int] = {} for row in rows: if row["status"] == "success": by_label[row["output"]["label"]] = by_label.get(row["output"]["label"], 0) + 1 else: # ``error`` (provider-side failure) or ``invalid_output`` (schema mismatch, # original text kept in ``raw_output``); the manifest's ``counts`` has the totals. print(f"request {row['index']} -> {row['status']}: {row['error'] or row['raw_output']}") return by_label Structured output¶ Set output_type to a Pydantic BaseModel subclass (or another type TypeAdapter supports, such as int or list[str]). OpenAI requests use response_format; Anthropic requests use a single forced tool call. Both providers require the schema root to be an object, so a non-object output_type is wrapped as {"response": ...} on the way out and unwrapped again before validation; the JSONL output holds the plain value. A model occasionally returns something that does not match the schema. That is not a task failure: the row gets status: "invalid_output" with the original text preserved in raw_output, and counts.invalid_output is separate from counts.errored so you can tell “the model produced output that doesn’t match the schema” apart from “the request never even succeeded”. A response with no content at all (a refusal, or a reasoning model that spent its whole max_tokens budget before producing visible output) is also invalid_output, for output_type=str too. airflow/providers/common/ai/example_dags/example_llm_batch.py[source] class Sentiment(BaseModel): """Structured output requested from every request in the batch.""" label: Literal["positive", "negative", "neutral"] confidence: float = Field(ge=0, le=1) reason: str @task.llm_batch¶ The TaskFlow decorator wraps a callable that returns the batch’s inputs (a list[str] or a list of {"prompt": ..., "model": ..., ...} dicts) instead of a single prompt string: airflow/providers/common/ai/example_dags/example_llm_batch.py[source] @dag(tags=["example"]) def example_llm_batch_decorator(): @task.llm_batch( llm_conn_id="pydanticai_default", model_id="anthropic:claude-sonnet-5", result_path=f"{RESULT_ROOT}/classify", system_prompt="Classify the sentiment of this product review.", output_type=Sentiment, deferrable=True, ) def build_review_prompts(reviews: list[str]) -> list[str]: return [f"Review: {review!r}" for review in reviews] summarize_manifest(build_review_prompts(REVIEWS)) The decorated callable must be deterministic across attempts: its return value feeds the fingerprint that decides whether a retry re-attaches to the batch already submitted. A callable that embeds something that changes between attempts (a wall-clock timestamp, say) looks like “the input changed” on every retry and pays for a new batch each time. Unlike @task.llm, the returned prompts are not rendered as Jinja templates. Batch inputs are usually bulk text the Dag author did not write, where a stray {{ or {% would either fail the whole batch or resolve var/conn accessors against Airflow secrets. Put anything dynamic in the callable, which receives the task context. result_path and the other operator parameters are templated as usual; keep result_path stable across attempts of the same task instance ({{ run_id }} is fine, {{ ts }} is not), or a retry looks for its recorded state at a location the previous attempt never wrote to. Provider-specific parameters¶ The operator builds each request body from the prompt, the system prompt, the model, the token cap and (for structured output) the schema directive, and translates those per provider: max_tokens is sent as max_completion_tokens to OpenAI and as max_tokens to Anthropic, and output_type becomes response_format on OpenAI and a forced tool on Anthropic. Everything else the provider’s chat endpoint accepts goes through request_params, which is merged into every request body as-is. For an openai: model that means OpenAI chat-completions keys (temperature, reasoning_effort, user, seed, …); for an anthropic: model it means Anthropic Messages keys (temperature, top_k, metadata, thinking, …). The operator does not validate these; an unknown key surfaces as a per-request error row from the provider, or as a failed batch when the provider rejects the whole input file. request_params is templated: every string inside the dict is rendered, so a value can come from a Variable, a param or an upstream XCom. Jinja hands back a string, so a numeric parameter written as a template needs render_template_as_native_obj=True on the Dag. The rendered values feed the re-attach fingerprint, so the same rule as result_path applies: a value that changes between attempts of one task instance makes a retry pay for a new batch. airflow/providers/common/ai/example_dags/example_llm_batch.py[source] @dag(tags=["example"]) def example_llm_batch_provider_params(): # ``request_params`` is merged into every request body as-is, so any parameter # the provider's chat endpoint accepts can go here: OpenAI chat-completions keys # for an ``openai:`` model, Anthropic Messages keys for an ``anthropic:`` model. # ``max_tokens`` is translated per provider (``max_completion_tokens`` on OpenAI). LLMBatchOperator( task_id="extract_keywords_openai", requests=[f"Review: {review!r}" for review in REVIEWS], result_path=f"{RESULT_ROOT}/keywords-openai", llm_conn_id="pydanticai_default", model_id="openai:gpt-5-mini", system_prompt="Extract up to three keywords from the review.", output_type=list[str], max_tokens=2048, request_params={"reasoning_effort": "low", "user": "reviews-pipeline"}, fail_on_partial_error=True, deferrable=True, ) LLMBatchOperator( task_id="extract_keywords_anthropic", requests=[f"Review: {review!r}" for review in REVIEWS], result_path=f"{RESULT_ROOT}/keywords-anthropic", llm_conn_id="pydanticai_default", model_id="anthropic:claude-sonnet-5", system_prompt="Extract up to three keywords from the review.", output_type=list[str], request_params={"temperature": 0.2, "metadata": {"user_id": "reviews-pipeline"}}, deferrable=True, ) Operator parameter OpenAI request body Anthropic request body system_prompt First messages entry with role: system system max_tokens max_completion_tokens (max_tokens is dropped) max_tokens output_type response_format of type json_schema (strict: false) tools + tool_choice forcing one tool whose input schema is the type request_params / params Merged as-is, managed keys win Merged as-is, managed keys win completion_window Batch-level completion_window ("24h") Ignored Per-re