This is an automated email from the ASF dual-hosted git repository.
kaxil pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new c74edfd4929 Run `@task.llm_batch` OpenAI batches through pydantic-ai
(#76975)
c74edfd4929 is described below
commit c74edfd49292646285d7051e262726008c7bc5dc
Author: Kaxil Naik <[email protected]>
AuthorDate: Sat Nov 21 00:08:16 2026 +0000
Run `@task.llm_batch` OpenAI batches through pydantic-ai (#76975)
Runs Anthropic batches through pydantic-ai's public Model.batch_* methods
instead of a hand-written adapter, and adds Gemini batch (google:<model>,
Gemini Developer API). The operator, trigger, state machine and the
BatchAdapter extension point stay as they are; third-party adapters keep
working. Raises the pydantic-ai-slim floor to 2.66.0.
---
providers/common/ai/docs/changelog.rst | 65 +-
providers/common/ai/docs/index.rst | 2 +-
providers/common/ai/docs/operators/llm_batch.rst | 112 ++--
providers/common/ai/pyproject.toml | 17 +-
.../src/airflow/providers/common/ai/batch/base.py | 2 +-
.../airflow/providers/common/ai/batch/dispatch.py | 12 +-
.../airflow/providers/common/ai/batch/openai.py | 459 --------------
.../common/ai/batch/pydantic_ai_backend.py | 318 +++++++++-
.../common/ai/example_dags/example_llm_batch.py | 9 +-
.../providers/common/ai/operators/llm_batch.py | 25 +-
.../ai/tests/unit/common/ai/batch/test_dispatch.py | 74 ++-
.../ai/tests/unit/common/ai/batch/test_openai.py | 524 ----------------
.../common/ai/batch/test_pydantic_ai_backend.py | 679 ++++++++++++++++++++-
uv.lock | 4 +-
14 files changed, 1163 insertions(+), 1139 deletions(-)
diff --git a/providers/common/ai/docs/changelog.rst
b/providers/common/ai/docs/changelog.rst
index 95ce8972e90..8af3c038618 100644
--- a/providers/common/ai/docs/changelog.rst
+++ b/providers/common/ai/docs/changelog.rst
@@ -26,40 +26,57 @@ Changelog
---------
.. note::
- ``@task.llm_batch`` now runs Anthropic batches through pydantic-ai's
``Model.batch_*`` methods and
- adds a Gemini adapter (``google:<model>``, Gemini Developer API only; a
Vertex ``google-cloud:``
- model id is refused with the fix in the message). This raises the
``pydantic-ai-slim`` floor to
- 2.66.0 and the ``anthropic`` extra's ``anthropic`` floor to 1.15.0, and adds
``google-genai`` to the
- ``google`` extra.
+ ``@task.llm_batch`` now runs OpenAI and Anthropic batches through
pydantic-ai's ``Model.batch_*``
+ methods and adds a Gemini adapter (``google:<model>``, Gemini Developer API
only; a Vertex
+ ``google-cloud:`` model id is refused with the fix in the message). This
raises the
+ ``pydantic-ai-slim`` floor to 2.66.0, the ``openai`` extra's ``openai``
floor to 3.31.0 and the
+ ``anthropic`` extra's ``anthropic`` floor to 1.15.0, and adds
``google-genai`` to the ``google``
+ extra.
- What changes for an existing Anthropic task:
+ What changes for an existing task:
- ``request_params`` and a request's ``params`` keep working. The sampling
settings (``temperature``,
- ``top_p``, ``top_k``, ``stop_sequences``) and ``anthropic_*`` settings are
typed, and every other
- key is still sent as a Messages field. A setting the model would silently
drop, such as ``seed``,
- now fails before submission, and a key the operator manages (``model``,
``messages``, ...) is
- ignored with a warning.
- - Structured output uses the model's native JSON-schema output instead of a
forced tool call, except
- for models without it and for schemas Anthropic's strict mode refuses
(more than 24 optional fields,
- more than 16 union-typed fields, or a recursive type), which still go
through a forced tool call.
+ ``top_p``, ...) and the provider-prefixed settings (``openai_*``,
+ ``anthropic_*``) are typed, and every other key is still sent as a request
field. A setting the
+ model would silently drop (``seed`` on Anthropic; ``seed``, ``top_k``,
``frequency_penalty``,
+ ``presence_penalty``, ``logit_bias`` and ``stop_sequences`` on OpenAI) now
fails before
+ submission, and a key the operator manages (``model``, ``messages``,
``input``, ...) is ignored
+ with a warning. A Chat Completions key has to be written the Responses way
on OpenAI, for example
+ ``openai_reasoning_effort`` instead of ``reasoning_effort``;
``reasoning_effort``, ``verbosity``
+ and ``logprobs`` fail before submission with the setting to use.
+ - OpenAI batches run on the Responses API (``/v1/responses``) instead of
Chat Completions, because
+ pydantic-ai batches only its Responses model. An ``openai-chat:`` model id
is built as
+ ``openai:`` and logged. A gateway that implements batches only for
``/v1/chat/completions`` stops
+ working; whether LiteLLM implements them for ``/v1/responses`` has not
been verified. Azure OpenAI
+ still has no adapter.
+ - Structured output uses the model's native JSON-schema output instead of a
forced tool call or
+ ``response_format``, except for models without it and, on Anthropic, for
schemas its strict mode
+ refuses (more than 24 optional fields, more than 16 union-typed fields, or
a recursive type), which
+ still go through a forced tool call.
- Creating a batch is not retried by the SDK: pydantic-ai sends it with
``max_retries=0`` because
- creating a batch is not idempotent, where the earlier adapter used the
SDK's default of two retries.
+ creating a batch is not idempotent, where the earlier adapters used the
SDK's default of two retries.
A 429 or 529 on create now fails the attempt, so it costs an Airflow task
retry, or raises
``LLMBatchOrphanedIntentError`` with ``on_orphaned_intent='fail'``.
- A cancelled batch is recognized from its landed results, because Anthropic
reports it as ended.
- - The state file records pydantic-ai's batch handle (state version 2). A
batch that an earlier
- version of this provider submitted and is still running is re-attached;
its state file is left as it is. An
- outdated batch from an earlier version that was recorded under a different
connection cannot be
- cancelled automatically; the task log says so, and the batch can be
cancelled at the provider.
- - Anthropic results are streamed, so landing a batch holds only a small
buffer of responses in
- memory. Gemini results are still read through pydantic-ai, which downloads
a batch's results in
- one call, so a Gemini batch holds all of its response bodies in memory at
once. Rows are still written one at a time. For a large Gemini batch,
- size workers for it or split the input across mapped task instances with
``.expand()``.
+ - OpenAI no longer recovers a batch whose submit response was never recorded
by reading the batch's
+ metadata. Like Anthropic and Gemini, it falls through to
``on_orphaned_intent``, whose default
+ ``"resubmit"`` submits a new batch.
+ - ``completion_window`` is ignored by every built-in adapter, and a value
other than ``"24h"`` now logs
+ a warning.
+ - The state file records pydantic-ai's batch handle (state version 2). An
Anthropic batch that an
+ earlier version of this provider submitted and is still running is
re-attached; its state file is
+ left as it is. An OpenAI batch from an earlier version cannot be: it was
created against Chat
+ Completions and its results cannot be read. The task fails with
``LLMBatchStateReadError``
+ naming the batch; let it finish or cancel it at OpenAI, delete the task's
state file and retry.
+ An outdated batch from an earlier version that was recorded under a
different connection cannot
+ be cancelled automatically; the task log says so, and the batch can be
cancelled at the provider.
+ - Anthropic and OpenAI results are streamed, so landing a batch holds only a
small buffer of
+ responses in memory. Gemini results are still read through pydantic-ai,
which downloads a batch's
+ results in one call, so a Gemini batch holds all of its response bodies in
memory at once. Rows are still written one at a time. For a large
+ Gemini batch, size workers for it or split the input across mapped task
instances with ``.expand()``.
- A task that was deferred by an earlier version of this provider and is
still waiting when you
upgrade cannot poll its batch: the trigger reports an error naming the
cause, and the task's retry
re-attaches to the batch.
- - ``completion_window`` is ignored by Anthropic and Gemini, and a value
other than ``"24h"`` now logs a
- warning.
A ``BatchAdapter`` written for the earlier contract keeps working: the new
members have defaults.
diff --git a/providers/common/ai/docs/index.rst
b/providers/common/ai/docs/index.rst
index 2d4f4379f1f..4e3a2c2a576 100644
--- a/providers/common/ai/docs/index.rst
+++ b/providers/common/ai/docs/index.rst
@@ -230,7 +230,7 @@ Extra Dependencies
``anthropic`` ``pydantic-ai-slim[anthropic]>=2.66.0``,
``anthropic>=1.15.0,<2``
``bedrock`` ``pydantic-ai-slim[bedrock]>=2.46.0``
``google`` ``pydantic-ai-slim[google]>=2.66.0``,
``google-genai>=2.30.0``
-``openai`` ``pydantic-ai-slim[openai]>=2.46.0``, ``openai>=2.47.0``
+``openai`` ``pydantic-ai-slim[openai]>=2.66.0``, ``openai>=3.31.0``
``typesafe`` ``typesafe-sdk>=0.6.0``
``mcp`` ``pydantic-ai-slim[mcp]>=2.46.0``
``modal`` ``apache-airflow-providers-modal``, ``modal>=1.5.2``
diff --git a/providers/common/ai/docs/operators/llm_batch.rst
b/providers/common/ai/docs/operators/llm_batch.rst
index 2a82992b04d..cc1661b96c6 100644
--- a/providers/common/ai/docs/operators/llm_batch.rst
+++ b/providers/common/ai/docs/operators/llm_batch.rst
@@ -26,7 +26,7 @@ roughly half the per-token cost of
:class:`~airflow.providers.common.ai.operator
in exchange for up to a 24-hour turnaround. The ``"<provider>:<model>"``
prefix of ``model_id``
selects the OpenAI, Anthropic or Gemini adapter; ``llm_conn_id`` must be a
``pydanticai`` connection.
-The Anthropic and Gemini adapters drive the ``batch_*`` methods of
pydantic-ai's ``Model``, so the
+The OpenAI, Anthropic and Gemini adapters drive the ``batch_*`` methods of
pydantic-ai's ``Model``, so the
credentials and endpoint come from the connection the same way they do for
``@task.llm``. They use static
credentials only: an API key, not a token callback or workload identity. They
use the connection's
primary model and ignore any fallback connections it lists.
@@ -47,12 +47,11 @@ batch can have up to 100,000 results, far too much to push
through XCom.
:start-after: [START howto_operator_llm_batch_basic]
:end-before: [END howto_operator_llm_batch_basic]
-Rows are written one at a time, and Anthropic's results are read as a stream,
so landing a batch holds
-only a small buffer of responses in the worker's memory. Gemini results are
still read through
-pydantic-ai, which downloads a batch's results in one call, so landing a
Gemini batch holds every
-response body of that batch in memory at once. For a
-Gemini batch of tens of thousands of long responses, size the worker for it,
or split the input across
-mapped task instances with ``.expand()`` so each instance lands one slice.
+Rows are written one at a time, and Anthropic and OpenAI results are read as a
stream, so landing a
+batch holds only a small buffer of responses in the worker's memory. Gemini
results are still read
+through pydantic-ai, which downloads a batch's results in one call, so landing
a Gemini batch holds every
+response body of that batch in memory at once. For a Gemini batch of tens of
thousands of long responses, size the worker for it, or split the
+input across mapped task instances with ``.expand()`` so each instance lands
one slice.
The manifest
^^^^^^^^^^^^
@@ -114,9 +113,8 @@ 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 and
-Gemini requests use the model's native JSON-schema output; for an Anthropic
model without it
-(Claude 3.5 Haiku, for example) the request uses a single forced tool call
instead. Every provider
+supports, such as ``int`` or ``list[str]``). Requests use the model's native
JSON-schema output; for a
+model without it (Claude 3.5 Haiku, for example) the request uses a single
forced tool call instead. Every provider
requires 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.
@@ -163,13 +161,20 @@ Provider-specific parameters
The operator builds each request from the prompt, the system prompt, the
model, the token
cap and (for structured output) the schema, and translates those per provider:
-``max_tokens`` is sent as ``max_completion_tokens`` to OpenAI and as
``max_tokens`` to Anthropic and
-Gemini, and ``output_type`` becomes ``response_format`` on OpenAI and the
model's native JSON-schema
-output on Anthropic and Gemini.
-
-Everything else the provider accepts goes through ``request_params``. For an
``openai:`` model that
-means OpenAI chat-completions keys (``temperature``, ``reasoning_effort``,
``user``, ``seed``, ...),
-merged into every request body as-is.
+``max_tokens`` is sent as ``max_output_tokens`` to OpenAI, as ``max_tokens``
to Anthropic and as
+``maxOutputTokens`` to Gemini, and ``output_type`` becomes the model's native
JSON-schema output.
+
+Everything else the provider accepts goes through ``request_params``. For an
``openai:`` model the
+sampling settings (``temperature``, ``top_p``, ...) and pydantic-ai's
``openai_*``
+settings (``openai_reasoning_effort``, ``openai_user``, ...) are typed
settings. Every other key
+(``user``, ``metadata``, ...) is an OpenAI Responses field and is merged into
the request body as-is.
+Batches use the Responses API, so a Chat Completions key has to be written the
Responses way:
+``openai_reasoning_effort`` or ``reasoning={"effort": ...}``, not
``reasoning_effort``.
+``reasoning_effort``, ``verbosity`` and ``logprobs`` fail validation before
anything is submitted,
+with the setting to use instead. A setting the Responses API does not support
+(``seed``, ``top_k``, ``frequency_penalty``, ``presence_penalty``,
``logit_bias`` and
+``stop_sequences``) fails validation before anything is submitted, because
pydantic-ai would
+otherwise drop it without a warning.
For an ``anthropic:`` model the sampling settings (``temperature``, ``top_p``,
``top_k``,
``stop_sequences``) and pydantic-ai's ``anthropic_*`` settings are typed
@@ -183,9 +188,8 @@ For a ``google:`` model only the sampling settings
(``temperature``, ``top_p``,
accepted. The Gemini batch API has no way to pass other request fields
through, so any other key
fails validation before anything is submitted.
-For OpenAI the operator does not validate the keys; 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.
+OpenAI validates the raw fields when it reads the input file, so an unknown
key surfaces as a
+per-request ``error`` row, or as a failed batch when the provider rejects the
whole 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
@@ -207,23 +211,23 @@ between attempts of one task instance makes a retry pay
for a new batch.
- Anthropic request body
- Gemini request
* - ``system_prompt``
- - First ``messages`` entry with ``role: system``
+ - A system message in ``input``
- ``system``
- The request's system instruction
* - ``max_tokens``
- - ``max_completion_tokens`` (``max_tokens`` is dropped)
+ - ``max_output_tokens``
- ``max_tokens``
- ``generationConfig.maxOutputTokens``
* - ``output_type``
- - ``response_format`` of type ``json_schema`` (``strict: false``)
+ - ``text.format`` of type ``json_schema``
- ``output_config.format`` of type ``json_schema`` (a forced tool on
models without it)
- ``generationConfig.responseJsonSchema``
* - ``request_params`` / ``params``
- - Merged as-is, managed keys win
+ - Typed settings, other keys merged as-is, managed keys ignored
- Typed settings, other keys merged as-is, managed keys ignored
- Typed settings only
* - ``completion_window``
- - Batch-level ``completion_window`` (``"24h"``)
+ - Ignored, with a warning for any other value
- Ignored, with a warning for any other value
- Ignored, with a warning for any other value
@@ -243,8 +247,8 @@ resolve to the same model and the operator rejects a mixed
batch before submitti
:end-before: [END howto_operator_llm_batch_per_request]
``request_params`` and a request's ``params`` cannot override the keys the
operator manages
-(the model, the messages, the token cap and the structured-output directive).
On Anthropic and
-Gemini a managed key is ignored with a warning in the task log.
+(the model, the messages, the token cap and the structured-output directive).
A managed key is
+ignored with a warning in the task log.
Results are read back with the batch-level settings, so a per-request
``params`` entry that changes
how a response is parsed is not supported.
@@ -306,15 +310,13 @@ Recovering from a crash between submit and recording it
---------------------------------------------------------
The operator records its intent to submit before the paid call, so a crash
after the provider
-accepted the batch but before the response was recorded leaves a trace. The
next attempt asks
-the provider for a matching batch, by the recorded identity key **and** a
fingerprint of the
-exact input, so it can never recover an unrelated submission. For OpenAI this
works: the adapter
-records both values in the batch's own ``metadata`` at submit time. If that
lookup itself fails
-(the provider is unreachable), the attempt raises
``LLMBatchOrphanLookupError`` rather than
-guess; the retry checks again.
-
-**Anthropic and Gemini offer no such lookup.** Neither batch-create call takes
``metadata`` and
-batches cannot be listed by ``custom_id``, so an orphan falls through to
+accepted the batch but before the response was recorded leaves a trace. An
adapter whose
+``find_orphaned_batch`` can look a batch up on the provider uses it on the
next attempt, matching the
+recorded identity key **and** a fingerprint of the exact input, so it can
never recover an unrelated
+submission.
+
+**None of the built-in adapters can do that lookup.** pydantic-ai's
batch-create call takes no
+``metadata`` and batches cannot be listed by ``custom_id``, so an orphan falls
through to
``on_orphaned_intent``: ``"resubmit"`` (default) submits a new batch, which
pays for both if the
original request did reach the provider; ``"fail"`` raises so you can
reconcile against the
provider's own batch listing first.
@@ -362,18 +364,40 @@ cancelled or expired job lands whatever results it wrote
and reports the rest as
``expired``, and a failed job raises ``LLMBatchJobError`` with Gemini's
reason. A
``PARTIALLY_SUCCEEDED`` job is a completed batch whose failed requests are
``error`` rows.
+.. _llm-batch-openai:
+
+OpenAI
+------
+
+OpenAI batches run on the Responses API: pydantic-ai batches only its
``OpenAIResponsesModel``, so the
+requests are ``/v1/responses`` bodies and the batch is created against that
endpoint. An
+``openai-chat:<model>`` model id is built as ``openai:<model>`` and the task
log says so when it validates
+and submits the batch. ``openai-responses:<model>`` selects the same adapter.
Every request
+in a batch must use the same model, because OpenAI's batch is tied to one, and
the operator rejects a
+mixed batch before submitting it. Azure OpenAI (a ``pydanticai_azure``
connection) has no adapter.
+
+The batch's input is uploaded as a file. pydantic-ai deletes that file only
inside its own result
+collection, which the operator does not use because it streams OpenAI results
instead, so OpenAI keeps
+the input file for its 30-day retention. The earlier OpenAI adapter did not
delete it either, so this
+is unchanged.
+
+An OpenAI job reports one ended state for every outcome, so the operator reads
the job's own status: an
+expired or cancelled job lands whatever results it wrote and reports the rest
as ``expired`` or
+``cancelled``, and a job OpenAI rejected before running it raises
``LLMBatchJobError`` with the
+validation errors.
+
Reaching the batch API through a gateway
------------------------------------------
-The OpenAI adapter reads ``base_url`` from the connection's host, so a
``pydanticai`` connection
-pointed at an OpenAI-compatible gateway that exposes ``/v1/files`` and
``/v1/batches`` (LiteLLM
-does, and routes to Azure OpenAI, Vertex and Bedrock batch behind it) runs the
whole batch
-through that gateway with ``model_id="openai:<gateway-model-name>"``.
``openai-chat:`` selects
-the same adapter, and a connection whose Default Model Provider is set (see
+The OpenAI adapter reads ``base_url`` from the connection's host, so a
``pydanticai`` connection pointed
+at a gateway runs the whole batch through it with
``model_id="openai:<gateway-model-name>"``. Batches
+use ``/v1/files`` and ``/v1/batches`` with the batch endpoint
``/v1/responses``, so the gateway has to
+implement batches for that endpoint; one that implements them only for
``/v1/chat/completions`` does
+not work. Whether LiteLLM accepts ``/v1/responses`` batches has not been
verified, so test your gateway
+with a small batch first. A connection whose Default Model Provider is set (see
:ref:`conn-example-openai-compatible-gateway`) takes the gateway's bare model
names, both in
-``model_id`` and in a request's ``model``. That is the path to take
-today for a provider ``@task.llm_batch`` has no adapter for yet; the error
message for a
-``pydanticai_azure``, ``pydanticai_bedrock`` or ``pydanticai_vertex``
connection says so.
+``model_id`` and in a request's ``model``. The error message for a
``pydanticai_azure``,
+``pydanticai_bedrock`` or ``pydanticai_vertex`` connection names this option.
``LLMBatchOperator`` or the vendor batch operators?
-----------------------------------------------------
diff --git a/providers/common/ai/pyproject.toml
b/providers/common/ai/pyproject.toml
index a9dc0e30b46..f7eed5450e2 100644
--- a/providers/common/ai/pyproject.toml
+++ b/providers/common/ai/pyproject.toml
@@ -88,19 +88,16 @@ dependencies = [
# The optional dependencies should be modified in place in the generated file
# Any change in the dependencies is preserved when the file is regenerated
[project.optional-dependencies]
-# @task.llm_batch drives the Anthropic and Gemini batch APIs through
pydantic-ai's Model.batch_*
-# methods, so the anthropic floor is 1.15.0, the one
pydantic-ai-slim[anthropic] 2.66 asks for.
-# The OpenAI adapter still talks to its SDK directly. openai 2.47.0 is the
first release that
-# accepts the httpx2 client pydantic-ai-slim>=2.33 hands it (2.45 and 2.46
raise TypeError on it);
-# pydantic-ai-slim[openai]>=2.33.0 itself asks for openai>=3, so this floor
only matters to an
-# install that overrides that requirement.
+# @task.llm_batch drives the OpenAI, Anthropic and Gemini batch APIs through
pydantic-ai's
+# Model.batch_* methods, so the anthropic and openai floors (1.15.0 and
3.31.0) are the ones
+# pydantic-ai-slim[anthropic] and pydantic-ai-slim[openai] 2.66 ask for.
# anthropic is capped below 2 because pydantic-ai's Anthropic model (up to
2.59.0) calls
# BetaMessageParam(...), which anthropic 2 turned into a Union that cannot be
instantiated.
"anthropic" = ["pydantic-ai-slim[anthropic]>=2.66.0", "anthropic>=1.15.0,<2"]
"bedrock" = ["pydantic-ai-slim[bedrock]>=2.46.0"]
# google-genai 2.30.0 is the floor pydantic-ai-slim[google] 2.66 asks for;
Gemini batch mode needs it.
"google" = ["pydantic-ai-slim[google]>=2.66.0", "google-genai>=2.30.0"]
-"openai" = ["pydantic-ai-slim[openai]>=2.46.0", "openai>=2.47.0"]
+"openai" = ["pydantic-ai-slim[openai]>=2.66.0", "openai>=3.31.0"]
# TypeSafe Jev: answers typed questions (pick one of N, a bounded score, a
yes/no
# probability) and cannot emit text, so it fits a branch or a classification
but not a
# summary. It arrives through pydantic-ai's own ``typesafe:`` provider, so the
hook needs
@@ -211,8 +208,10 @@ dev = [
"pydantic-ai-skills>=1.2.0,<2",
"apache-airflow-providers-common-sql[datafusion]",
"langchain>=1.0.0",
- # @task.llm_batch's OpenAI adapter calls its SDK directly, and the
Anthropic and Gemini adapters
- # build real pydantic-ai models on them. The dev group needs them so those
tests run instead of skipping.
+ # @task.llm_batch's adapters build real pydantic-ai models on these SDKs.
+ # The dev group needs them so those tests run instead of skipping.
+ # Not raised to the extra's 3.31.0 floor: the llamaindex extra caps openai
below 3 (see the conflicts
+ # declared in the root pyproject.toml), and the dev group is resolved with
it.
"openai>=2.47.0",
"anthropic>=1.15.0,<2",
"google-genai>=2.30.0",
diff --git a/providers/common/ai/src/airflow/providers/common/ai/batch/base.py
b/providers/common/ai/src/airflow/providers/common/ai/batch/base.py
index 84b8a1bf0e4..c51a90c1a9d 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/batch/base.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/batch/base.py
@@ -258,7 +258,7 @@ class BatchAdapter(ABC):
"""
Upload/submit the batch and return the provider's batch id.
- Where the provider offers batch-level metadata (OpenAI), record both
+ Where the provider offers batch-level metadata, record both
``idempotency_key`` and ``input_fingerprint`` there so
:meth:`find_orphaned_batch` can read them back. The key alone
identifies
the task instance, not this submission of it: it is stable across a
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/batch/dispatch.py
b/providers/common/ai/src/airflow/providers/common/ai/batch/dispatch.py
index 6e920c1e058..6d692048a51 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/batch/dispatch.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/batch/dispatch.py
@@ -28,7 +28,7 @@ This is a separate decision from
have a batch API".
Adapters are imported lazily, only once a request is dispatched to them, so
-importing this module never requires ``openai``/``anthropic`` to be installed.
+importing this module never requires ``openai``/``anthropic``/``google-genai``
to be installed.
Another package can add an adapter in two ways: call :func:`register_adapter`
at import time, or declare an entry point in the
``airflow.providers.common.ai.batch_adapters`` group whose name is the model
@@ -56,14 +56,16 @@ ENTRY_POINT_GROUP =
"airflow.providers.common.ai.batch_adapters"
#: adapter name -> (module path, class name), resolved lazily by
:func:`import_adapter_class`.
_ADAPTER_MODULES: dict[str, tuple[str, str]] = {
- "openai": ("airflow.providers.common.ai.batch.openai",
"OpenAIBatchAdapter"),
+ "openai": ("airflow.providers.common.ai.batch.pydantic_ai_backend",
"OpenAIBatchAdapter"),
"anthropic": ("airflow.providers.common.ai.batch.pydantic_ai_backend",
"AnthropicBatchAdapter"),
"google": ("airflow.providers.common.ai.batch.pydantic_ai_backend",
"GoogleBatchAdapter"),
}
#: model_id prefix -> the adapter that serves it under another name.
``openai-chat`` is
-#: pydantic-ai's Chat Completions prefix, and Chat Completions is what the
``openai`` adapter submits.
-_ADAPTER_ALIASES: dict[str, str] = {"openai-chat": "openai"}
+#: pydantic-ai's Chat Completions prefix; the ``openai`` adapter batches on
the Responses API
+#: instead and builds the ``openai:`` model of the same name.
``openai-responses`` is pydantic-ai's
+#: own name for that Responses model.
+_ADAPTER_ALIASES: dict[str, str] = {"openai-chat": "openai",
"openai-responses": "openai"}
#: model_id prefixes that name a platform whose batch API has no adapter, with
the fix to offer.
_GEMINI_PLATFORM_REFUSAL = (
@@ -169,7 +171,7 @@ def get_adapter_class(conn_type: str | None, model_id: str
| None) -> type[Batch
f"accepts {sorted(adapter_cls.conn_types)}. Azure OpenAI, Bedrock
and Vertex batch "
"need their own adapters (deployment-scoped or object-storage
based APIs). Until "
"one exists, point a 'pydanticai' connection at the public
endpoint, or route "
- "through an OpenAI-compatible gateway that exposes /v1/files and
/v1/batches."
+ "through a gateway that exposes /v1/files and /v1/batches for
/v1/responses."
)
return adapter_cls
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/batch/openai.py
b/providers/common/ai/src/airflow/providers/common/ai/batch/openai.py
deleted file mode 100644
index 323ff9062f5..00000000000
--- a/providers/common/ai/src/airflow/providers/common/ai/batch/openai.py
+++ /dev/null
@@ -1,459 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-"""
-OpenAI batch adapter.
-
-Talks to the ``openai`` SDK directly rather than through
-``apache-airflow-providers-openai``: that provider's hook has no batch listing
-or file-download methods, so reusing it would add a hard dependency without
-the capabilities this needs. The SDK import is deferred to
-:func:`_build_client` so importing this module never requires ``openai``.
-"""
-
-from __future__ import annotations
-
-import json
-import math
-from collections.abc import Iterator
-from datetime import datetime
-from typing import TYPE_CHECKING, Any
-
-from airflow.providers.common.ai.batch.base import (
- BatchAdapter,
- BatchState,
- BatchStatus,
- ExtractedOutput,
- RawResultItem,
- SubmitResult,
-)
-from airflow.providers.common.ai.exceptions import LLMBatchLimitExceededError,
LLMBatchModelMismatchError
-from airflow.providers.common.ai.utils.task_logger import get_task_logger
-from airflow.providers.common.compat.sdk import
AirflowOptionalProviderFeatureException
-
-log = get_task_logger()
-
-if TYPE_CHECKING:
- from airflow.providers.common.ai.batch.base import BatchRequest
- from airflow.providers.common.ai.batch.output_schema import OutputSpec
-
-_ENDPOINT = "/v1/chat/completions"
-
-#: Cap on how many batches ``find_orphaned_batch`` scans looking for a
metadata match. OpenAI's
-#: list API has no server-side metadata filter, so the scan is client-side;
the cap bounds the
-#: worst case against an account with a very long batch history.
-_ORPHAN_SCAN_LIMIT = 500
-
-#: ``Batch.created_at`` is whole seconds while the intent record's write time
carries
-#: microseconds, so a batch created in the same second as the intent write
could otherwise be
-#: excluded by the ``not_before`` filter. The identity guarantee is the key
plus fingerprint
-#: match; ``not_before`` only trims how far back the scan looks.
-_CLOCK_SKEW_SLACK_SECONDS = 300
-
-#: OpenAI's batch-job statuses collapsed to the small set ``BatchState`` uses.
-_STATUS_MAP: dict[str, BatchStatus] = {
- "validating": "in_progress",
- "in_progress": "in_progress",
- "finalizing": "in_progress",
- "cancelling": "in_progress",
- "completed": "completed",
- "failed": "failed",
- "expired": "expired",
- "cancelled": "cancelled",
-}
-
-#: Error-file ``error.code`` values OpenAI writes for requests it never ran,
mapped to the
-#: per-item status they mean. Anything else in the error file is a real
per-request failure.
-_ERROR_CODE_TO_PROVIDER_STATUS: dict[str, str] = {
- "batch_expired": "expired",
- "batch_cancelled": "cancelled",
-}
-
-
-def _build_client(api_key: str | None, base_url: str | None) -> Any:
- try:
- from openai import OpenAI
- except ImportError as e:
- raise AirflowOptionalProviderFeatureException(
- "OpenAI batch requires the openai SDK. Install with: "
- "pip install 'apache-airflow-providers-common-ai[openai]'"
- ) from e
- kwargs: dict[str, Any] = {}
- if api_key:
- kwargs["api_key"] = api_key
- if base_url:
- kwargs["base_url"] = base_url
- return OpenAI(**kwargs)
-
-
-class OpenAIBatchAdapter(BatchAdapter):
- """
- Batch adapter for OpenAI's Batch API (``/v1/chat/completions``).
-
- .. note::
-
- Experimental: this can change or be removed in a minor release of this
provider.
- See :ref:`howto/stability`.
-
- :param api_key: Passed straight to the ``openai.OpenAI`` client. ``None``
- falls back to the SDK's own env-var resolution (``OPENAI_API_KEY``).
- :param base_url: Passed straight to the ``openai.OpenAI`` client. Pointing
- it at an OpenAI-compatible gateway that exposes ``/v1/files`` and
- ``/v1/batches`` routes the batch through that gateway.
- :param client: Inject a pre-built client (or a test double) instead of
- constructing one from ``api_key``/``base_url``.
- """
-
- name = "openai"
- max_requests = 50_000
- max_payload_bytes = 200_000_000
- allows_per_request_model = False
-
- def __init__(
- self,
- *,
- api_key: str | None = None,
- base_url: str | None = None,
- client: Any | None = None,
- ) -> None:
- self._client = client if client is not None else
_build_client(api_key, base_url)
-
- def _iter_lines(
- self,
- requests: list[BatchRequest],
- *,
- model: str,
- idempotency_key: str,
- directive: dict[str, Any],
- system_prompt: str,
- max_tokens: int,
- request_params: dict[str, Any] | None,
- ) -> Iterator[dict[str, Any]]:
- """Yield one JSONL line per request; a generator so validation and
submit never hold every line at once."""
- for index, request in enumerate(requests):
- messages = []
- effective_system_prompt = request.get("system_prompt") or
system_prompt
- if effective_system_prompt:
- messages.append({"role": "system", "content":
effective_system_prompt})
- messages.append({"role": "user", "content": request["prompt"]})
- resolved_model = self.resolve_request_model(
- request.get("model"), default_bare_model=model,
request_index=index
- )
- # User params first, then the keys this adapter manages, so a
stray "model" or
- # "messages" in request_params cannot bypass the model check or
replace the prompt.
- # ``max_completion_tokens`` is the cap every current chat model
accepts; ``max_tokens``
- # is deprecated and rejected by reasoning models such as gpt-5.
- body: dict[str, Any] = {
- **(request_params or {}),
- **(request.get("params") or {}),
- "model": resolved_model,
- "messages": messages,
- "max_completion_tokens": request.get("max_tokens") or
max_tokens,
- **directive,
- }
- body.pop("max_tokens", None)
- yield {
- # "-" rather than ":" so both adapters share a separator that
fits Anthropic's
- # ``^[a-zA-Z0-9_-]{1,64}$`` custom_id rule.
- "custom_id": f"{idempotency_key}-{index}",
- "method": "POST",
- "url": _ENDPOINT,
- "body": body,
- }
-
- def build_output_directive(self, spec: OutputSpec) -> dict[str, Any]:
- if not spec.is_structured:
- return {}
- # strict=False: strict mode requires rewriting the user's schema
(every property
- # required, additionalProperties false), changing its meaning, and has
no Anthropic
- # equivalent. Schema mismatches land as invalid_output rows on both
providers alike.
- return {
- "response_format": {
- "type": "json_schema",
- "json_schema": {
- "name": spec.schema_name,
- "schema": spec.json_schema,
- "strict": False,
- },
- }
- }
-
- def validate_requests(
- self,
- requests: list[BatchRequest],
- *,
- model: str,
- output_spec: OutputSpec,
- idempotency_key: str,
- system_prompt: str = "",
- max_tokens: int = 1024,
- request_params: dict[str, Any] | None = None,
- **kwargs: Any,
- ) -> None:
- self.check_custom_id_length(idempotency_key, len(requests))
-
- if len(requests) > self.max_requests:
- raise LLMBatchLimitExceededError(
- f"OpenAI batch accepts at most {self.max_requests} requests
per batch; got "
- f"{len(requests)}. Split the input across mapped task
instances with .expand() "
- f"so each instance submits at most {self.max_requests}
requests."
- )
-
- # Resolve (and reject a foreign-provider override) before checking
uniformity, so two
- # requests naming the same other provider's model cannot pass as
"uniform".
- distinct_models = {
- self.resolve_request_model(r.get("model"),
default_bare_model=model, request_index=i)
- for i, r in enumerate(requests)
- }
- if len(distinct_models) > 1:
- raise LLMBatchModelMismatchError(
- "OpenAI requires every request in a batch to use the same
model; got "
- f"{len(distinct_models)} distinct models
({sorted(distinct_models)!r}). "
- "Per-request model overrides are supported by Anthropic only."
- )
-
- directive = self.build_output_directive(output_spec)
- directive_bytes = len(json.dumps(directive))
- total_bytes = 0
- lines = self._iter_lines(
- requests,
- model=model,
- idempotency_key="0" * 16,
- directive=directive,
- system_prompt=system_prompt,
- max_tokens=max_tokens,
- request_params=request_params,
- )
- for index, line in enumerate(lines):
- total_bytes += len(json.dumps(line).encode()) + 1
- if total_bytes > self.max_payload_bytes:
- raise LLMBatchLimitExceededError(
- f"OpenAI batch accepts a payload of at most
{self.max_payload_bytes} bytes; "
- f"this input reached {total_bytes} bytes at request {index
+ 1} of "
- f"{len(requests)} (the output_type schema adds
~{directive_bytes} bytes to "
- "every request). Split the input with .expand()."
- )
-
- def submit(
- self,
- requests: list[BatchRequest],
- *,
- model: str,
- idempotency_key: str,
- input_fingerprint: str,
- output_spec: OutputSpec,
- system_prompt: str = "",
- max_tokens: int = 1024,
- request_params: dict[str, Any] | None = None,
- completion_window: str = "24h",
- **kwargs: Any,
- ) -> SubmitResult:
- directive = self.build_output_directive(output_spec)
- lines = self._iter_lines(
- requests,
- model=model,
- idempotency_key=idempotency_key,
- directive=directive,
- system_prompt=system_prompt,
- max_tokens=max_tokens,
- request_params=request_params,
- )
- # Encode each line once, straight into the upload buffer: no
intermediate list of dicts
- # and no intermediate str of the whole file.
- jsonl_bytes = b"".join(json.dumps(line).encode() + b"\n" for line in
lines)
- uploaded = self._client.files.create(file=(f"{idempotency_key}.jsonl",
jsonl_bytes), purpose="batch")
- batch = self._client.batches.create(
- input_file_id=uploaded.id,
- endpoint=_ENDPOINT,
- completion_window=completion_window,
- # Both values let find_orphaned_batch tell "this task instance"
(idempotency_key,
- # stable across a clear) apart from "this exact input"
(input_fingerprint). The
- # fingerprint is truncated to 16 hex characters; OpenAI caps
metadata values at 512
- # characters, so the full digest would fit, but 16 is ample for a
cross-check.
- metadata={"idempotency_key": idempotency_key, "input_fingerprint":
input_fingerprint[:16]},
- )
- return SubmitResult(batch_id=batch.id, provider_input_ref=uploaded.id)
-
- def get_batch(self, batch_id: str) -> BatchState:
- batch = self._client.batches.retrieve(batch_id)
- counts = None
- request_counts = batch.request_counts
- if request_counts is not None:
- # OpenAI's breakdown is {completed, failed, total}: progress
counters, not a
- # success/error split. Once the job has expired or been cancelled,
whatever was
- # neither completed nor failed was never processed, so the
remainder is attributed
- # to the job's own terminal status.
- remainder = max(request_counts.total - request_counts.completed -
request_counts.failed, 0)
- counts = {
- "succeeded": request_counts.completed,
- "errored": request_counts.failed,
- "expired": remainder if batch.status == "expired" else 0,
- "cancelled": remainder if batch.status == "cancelled" else 0,
- }
- return BatchState(
- status=_STATUS_MAP.get(batch.status, "in_progress"),
- counts=counts,
- error_message=_format_batch_errors(batch.errors),
- )
-
- def cancel_batch(self, batch_id: str) -> None:
- self._client.batches.cancel(batch_id)
-
- def find_orphaned_batch(
- self, idempotency_key: str, input_fingerprint: str, not_before: str
- ) -> str | None:
- """
- Look for a batch whose metadata carries both identifiers, created at
or after ``not_before``.
-
- :meth:`submit` records ``idempotency_key`` and ``input_fingerprint`` in
- the batch's metadata, so a batch whose submit response never made it
- back can be found and re-attached to. No server-side metadata filter
- exists, so this walks up to ``_ORPHAN_SCAN_LIMIT`` batches client-side;
- among every match the most recently created one wins.
- """
- not_before_epoch = (
- math.floor(datetime.fromisoformat(not_before).timestamp()) -
_CLOCK_SKEW_SLACK_SECONDS
- if not_before
- else 0.0
- )
- best = None
- scanned = 0
- for batch in self._client.batches.list(limit=100):
- if scanned >= _ORPHAN_SCAN_LIMIT:
- log.warning(
- "Stopped scanning for an orphaned batch after the scan
limit; a matching batch may exist",
- scan_limit=_ORPHAN_SCAN_LIMIT,
- idempotency_key=idempotency_key,
- )
- break
- scanned += 1
- metadata = batch.metadata or {}
- if metadata.get("idempotency_key") != idempotency_key:
- continue
- if metadata.get("input_fingerprint") != input_fingerprint[:16]:
- continue
- if batch.created_at < not_before_epoch:
- continue
- if best is None or batch.created_at > best.created_at:
- best = batch
- return best.id if best is not None else None
-
- def iter_results(self, batch_id: str) -> Iterator[RawResultItem]:
- batch = self._client.batches.retrieve(batch_id)
- return self._iter_result_files(batch_id, batch.output_file_id,
batch.error_file_id)
-
- def _iter_result_files(
- self, batch_id: str, output_file_id: str | None, error_file_id: str |
None
- ) -> Iterator[RawResultItem]:
- # Stream the output file, then the error file, so both files' contents
are never resident.
- if output_file_id:
- yield from self._iter_file_lines(batch_id, output_file_id)
- if error_file_id:
- yield from self._iter_file_lines(batch_id, error_file_id)
-
- def _iter_file_lines(self, batch_id: str, file_id: str) ->
Iterator[RawResultItem]:
- # ``with_streaming_response`` is what makes the SDK stream the body; a
plain
- # ``files.content()`` reads the whole file into memory before
``iter_lines`` runs.
- with self._client.files.with_streaming_response.content(file_id) as
response:
- for line in response.iter_lines():
- if not line:
- continue
- try:
- yield self._parse_result_line(json.loads(line))
- except (KeyError, IndexError, ValueError, AttributeError,
TypeError) as e:
- # One malformed line must not abort the whole stream: the
provider returns
- # the same line on every retry, so the manifest could
never be produced.
- # results.py counts the index as "missing" once it is
absent from ``seen``.
- log.warning(
- "Skipping unparsable result line for batch",
- batch_id=batch_id,
- file_id=file_id,
- line=line[:200],
- error=str(e),
- )
-
- @staticmethod
- def _parse_result_line(payload: dict[str, Any]) -> RawResultItem:
- custom_id = payload["custom_id"]
- index = int(custom_id.rsplit("-", 1)[1])
- error = payload.get("error")
- response = payload.get("response") or {}
- body = response.get("body") or {}
-
- if error is not None or response.get("status_code") != 200:
- error_dict: dict[str, Any] = error if isinstance(error, dict) else
{}
- raw_body_error = body.get("error")
- body_error: dict[str, Any] = raw_body_error if
isinstance(raw_body_error, dict) else {}
- message = (
- error_dict.get("message")
- or body_error.get("message")
- or (str(error) if error is not None else f"HTTP
{response.get('status_code')}")
- )
- code = error_dict.get("code") or body_error.get("code")
- provider_status = _ERROR_CODE_TO_PROVIDER_STATUS.get(str(code),
"errored")
- return RawResultItem(
- custom_id=custom_id,
- index=index,
- provider_status=provider_status, # type: ignore[arg-type]
- model=body.get("model"),
- usage=None,
- finish_reason=None,
- error={
- "type": "provider_error" if provider_status == "errored"
else provider_status,
- "message": message,
- "provider_code": str(code)
- if code is not None
- else str(response.get("status_code") or "") or None,
- "stage": "provider",
- },
- raw=None,
- )
-
- choice = (body.get("choices") or [{}])[0]
- message_content = (choice.get("message") or {}).get("content")
- usage = body.get("usage") or {}
- return RawResultItem(
- custom_id=custom_id,
- index=index,
- provider_status="success",
- model=body.get("model"),
- usage={
- "input_tokens": usage.get("prompt_tokens", 0),
- "output_tokens": usage.get("completion_tokens", 0),
- },
- finish_reason=choice.get("finish_reason"),
- error=None,
- raw=message_content,
- )
-
- def extract_output(self, raw: RawResultItem, spec: OutputSpec) ->
ExtractedOutput:
- if raw.raw is None:
- # A refusal, or a reasoning model that spent its whole token
budget before emitting
- # visible output. Either way there is no content to hand back as a
success.
- return ExtractedOutput(kind="absent")
- if not spec.is_structured:
- return ExtractedOutput(kind="text", text=raw.raw)
- return ExtractedOutput(kind="json_text", text=raw.raw)
-
-
-def _format_batch_errors(errors: Any) -> str | None:
- """Render OpenAI's ``Batch.errors`` as ``code: message`` pairs instead of
a pydantic repr."""
- data = getattr(errors, "data", None) or []
- rendered = "; ".join(
- f"{getattr(e, 'code', None) or 'error'}: {getattr(e, 'message', None)
or ''}".rstrip(": ")
- for e in data
- )
- return rendered or None
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/batch/pydantic_ai_backend.py
b/providers/common/ai/src/airflow/providers/common/ai/batch/pydantic_ai_backend.py
index c866c82c766..6872e7e53d5 100644
---
a/providers/common/ai/src/airflow/providers/common/ai/batch/pydantic_ai_backend.py
+++
b/providers/common/ai/src/airflow/providers/common/ai/batch/pydantic_ai_backend.py
@@ -44,7 +44,7 @@ from contextlib import AsyncExitStack, aclosing,
asynccontextmanager, closing, s
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypeVar, cast
-from pydantic import TypeAdapter
+from pydantic import BaseModel, JsonValue, TypeAdapter
from pydantic_ai.exceptions import (
ModelAPIError,
ModelHTTPError,
@@ -73,6 +73,7 @@ from pydantic_ai.models.batch import (
from pydantic_ai.output import OutputObjectDefinition
from pydantic_ai.settings import ModelSettings
from pydantic_ai.tools import ToolDefinition
+from pydantic_core import to_json
from airflow.providers.common.ai.batch.base import (
BatchAdapter,
@@ -95,14 +96,16 @@ from airflow.providers.common.ai.utils.task_logger import
get_task_logger
if TYPE_CHECKING:
from pydantic_ai.models import Model
+ from pydantic_ai.models.openai import OpenAIResponsesModel
- from airflow.providers.common.ai.batch.base import BatchRequest
+ from airflow.providers.common.ai.batch.base import BatchRequest,
BatchStatus
from airflow.providers.common.ai.batch.output_schema import OutputSpec
from airflow.sdk import Connection
log = get_task_logger()
T = TypeVar("T")
+L = TypeVar("L", bound=BaseModel)
_BATCH_ADAPTER: TypeAdapter[Batch] = TypeAdapter(Batch)
@@ -147,6 +150,13 @@ _MANAGED_KEYS = frozenset(
#: pydantic-ai's status for a request that never ran, as this provider names
it.
_UNRUN_STATUS: dict[str, Literal["cancelled", "expired"]] = {"canceled":
"cancelled", "expired": "expired"}
+#: The error codes of a request an OpenAI batch ended before running, and the
status pydantic-ai gives each.
+#: Mirrors ``_UNRUN_STATUSES`` in pydantic-ai's OpenAI batch module.
+_OPENAI_UNRUN_STATUSES: dict[str, Literal["expired", "canceled"]] = {
+ "batch_expired": "expired",
+ "batch_cancelled": "canceled",
+}
+
#: Gemini documents no request limit, and the ABC wants an int.
_NO_REQUEST_LIMIT = 2**63 - 1
@@ -170,6 +180,99 @@ class _ResultsContext:
parameters: ModelRequestParameters
+class _OpenAILineResponse(BaseModel):
+ status_code: int
+ body: JsonValue
+
+
+class _OpenAILineError(BaseModel):
+ code: str | None = None
+ message: str | None = None
+
+
+class _OpenAIOutputLine(BaseModel):
+ """A line of an OpenAI batch's output or error file."""
+
+ custom_id: str
+ response: _OpenAILineResponse | None = None
+ error: _OpenAILineError | None = None
+
+
+class _OpenAIInputLine(BaseModel):
+ custom_id: str
+
+
+def _openai_result(line: _OpenAIOutputLine) -> BatchResult:
+ """Mirror of ``_to_result`` in pydantic-ai's OpenAI batch module."""
+ if (response := line.response) is not None:
+ if 200 <= response.status_code < 300:
+ return BatchResult(
+ custom_id=line.custom_id, status="succeeded",
body=to_json(response.body).decode()
+ )
+ return BatchResult(custom_id=line.custom_id, status="errored",
body=response.model_dump_json())
+ error = line.error or _OpenAILineError()
+ if status := _OPENAI_UNRUN_STATUSES.get(error.code or ""):
+ return BatchResult(custom_id=line.custom_id, status=status)
+ body = _OpenAILineResponse(status_code=500, body={"error":
error.model_dump(mode="json")})
+ return BatchResult(custom_id=line.custom_id, status="errored",
body=body.model_dump_json())
+
+
+def _openai_unrun_result(details: Mapping[str, Any], custom_id: str,
line_number: int) -> BatchResult:
+ """Mirror of ``_unrun_result`` in pydantic-ai's OpenAI batch module."""
+ if details["status"] == "failed":
+ # The input file failed validation, so the batch ran none of its
requests. A request gets the errors of its
+ # own line and those of no line; when they're all about other lines,
it gets them all, which name them.
+ errors = details.get("errors", [])
+ own = [
+ error
+ for error in errors
+ if not isinstance(error, Mapping) or error.get("line") in
(line_number, None)
+ ]
+ body = _OpenAILineResponse(status_code=400, body={"errors": own or
errors})
+ return BatchResult(custom_id=custom_id, status="errored",
body=body.model_dump_json())
+ return BatchResult(
+ custom_id=custom_id, status="expired" if details["status"] ==
"expired" else "canceled"
+ )
+
+
+async def _split_lines(chunks: AsyncIterator[bytes]) -> AsyncGenerator[bytes,
None]:
+ r"""
+ Yield the lines of a byte stream, split on ``\n`` only.
+
+ ``str.splitlines`` also splits on U+2028, U+0085 and the like, which JSON
allows unescaped inside
+ a string, so it can cut a result line in two. A partial line is kept until
the rest of it arrives.
+ """
+ pending = b""
+ async for chunk in chunks:
+ pending += chunk
+ *lines, pending = pending.split(b"\n")
+ for line in lines:
+ yield line
+ if pending:
+ yield pending
+
+
+def _parse_line(line_type: type[L], raw: bytes, *, file_id: str, line_number:
int) -> L | None:
+ """
+ Return the parsed line, or ``None`` for one that is blank or unreadable.
+
+ The provider serves the same bytes on every retry, so a line that cannot
be parsed would fail the
+ landing every time. Skipping it leaves the request missing from the merge,
which counts it.
+ """
+ try:
+ if not raw.strip():
+ raise ValueError("the line is blank")
+ return line_type.model_validate_json(raw.decode())
+ except ValueError as e:
+ log.warning(
+ "Skipping unreadable line of an OpenAI batch file",
+ file_id=file_id,
+ line_number=line_number,
+ error=str(e),
+ )
+ return None
+
+
def _stream(source: AsyncGenerator[T, None]) -> Generator[T, None, None]:
"""
Read an async generator from synchronous code without collecting it first.
@@ -255,10 +358,17 @@ def _typed_settings(settings_type: type) ->
frozenset[str]:
def _error_body(error: ModelHTTPError) -> Mapping[str, Any]:
- """Return the ``error`` object of an HTTP error's body, which carries the
provider's own type and message."""
+ """
+ Return the object of an HTTP error's body that carries the provider's own
type, code and message.
+
+ Anthropic and Gemini nest it under ``error``. OpenAI's batch decoder has
already unwrapped it, so
+ the body is the object itself.
+ """
body = error.body
- inner = body.get("error") if isinstance(body, Mapping) else None
- return inner if isinstance(inner, Mapping) else {}
+ if not isinstance(body, Mapping):
+ return {}
+ inner = body.get("error")
+ return inner if isinstance(inner, Mapping) else body
def _reason(error: ModelHTTPError) -> str:
@@ -266,6 +376,12 @@ def _reason(error: ModelHTTPError) -> str:
return str(_error_body(error).get("message") or error.message)
+def _error_code(error: ModelHTTPError) -> str | int:
+ """Return the provider's own code for an HTTP error, or its status when
the provider sent none."""
+ body = _error_body(error)
+ return error.provider_error_code or body.get("type") or body.get("code")
or error.status_code
+
+
def _error_info(status: str, message: str, provider_code: str | int | None =
None) -> dict[str, Any]:
return {"type": status, "message": message, "provider_code":
provider_code, "stage": "provider"}
@@ -312,6 +428,8 @@ class PydanticAIBatchAdapter(BatchAdapter):
conn_types = frozenset({"pydanticai"})
#: ``True`` when a key that is not a typed setting is passed to the
provider as a raw request field.
accepts_raw_params: ClassVar[bool] = True
+ #: The key of the batch's ``provider_details`` that names the uploaded
input file.
+ input_file_key: ClassVar[str] = "input_file"
# pydantic-ai fixes the completion window of the provider batch APIs it
drives.
supports_completion_window = False
@@ -670,7 +788,7 @@ class PydanticAIBatchAdapter(BatchAdapter):
self._handle = _BATCH_ADAPTER.dump_json(batch).decode()
return SubmitResult(
batch_id=batch.id,
- provider_input_ref=(batch.provider_details or
{}).get("input_file"),
+ provider_input_ref=(batch.provider_details or
{}).get(self.input_file_key),
handle=self._handle,
)
@@ -778,10 +896,11 @@ class PydanticAIBatchAdapter(BatchAdapter):
PydanticAIBatchRequest(custom_id=custom_id, messages=[],
model_request_parameters=parameters),
)
except ModelAPIError as e:
- provider_code = None
if isinstance(e, ModelHTTPError):
- provider_code = _error_body(e).get("type") or e.status_code
- return _failed(custom_id, index, "errored",
_error_info(result.status, e.message, provider_code))
+ info = _error_info(result.status, _reason(e), _error_code(e))
+ else:
+ info = _error_info(result.status, e.message)
+ return _failed(custom_id, index, "errored", info)
details = response.provider_details or {}
return RawResultItem(
custom_id=custom_id,
@@ -809,6 +928,187 @@ class PydanticAIBatchAdapter(BatchAdapter):
return ExtractedOutput(kind="absent")
+class OpenAIBatchAdapter(PydanticAIBatchAdapter):
+ """
+ Batch adapter for OpenAI's Batch API, on the Responses API
(``/v1/responses``).
+
+ pydantic-ai batches only its Responses model, so an ``openai-chat:`` model
id is built as the
+ ``openai:`` model of the same name and logged. Azure OpenAI has no
adapter. A batch's group
+ includes the model, so every request must use the same one. Raw Responses
fields in
+ ``request_params`` (``user``, ``metadata``, ...) go through
``extra_body``, so use Responses
+ names: ``openai_reasoning_effort`` or ``reasoning={"effort": ...}``, not
``reasoning_effort``.
+ A Chat Completions parameter that has a Responses equivalent fails before
submission.
+
+ A batch gateway that implements ``/v1/files`` and ``/v1/batches`` for
``/v1/responses`` works
+ through the connection's ``host``; one that implements those only for
``/v1/chat/completions``
+ does not.
+ """
+
+ name = "openai"
+ #: OpenAI's documented limit: 50,000 requests or 200 MB, whichever is
reached first.
+ max_requests = 50_000
+ max_payload_bytes = 200_000_000
+ allows_per_request_model = False
+ input_file_key = "input_file_id"
+
+ #: Job statuses that end a batch, as the status this provider reports. A
job that expired or was
+ #: cancelled still yields a row per request, and those rows carry the
counts.
+ _ENDED_STATUSES: ClassVar[dict[str, BatchStatus]] = {
+ "failed": "failed",
+ "expired": "expired",
+ "cancelled": "cancelled",
+ }
+
+ #: Chat Completions parameters the Responses API does not take, with the
typed setting that
+ #: does the same. Sent as raw fields, they would fail every request of the
batch at OpenAI.
+ _CHAT_COMPLETIONS_RENAMES: ClassVar[dict[str, str]] = {
+ "reasoning_effort": "openai_reasoning_effort",
+ "verbosity": "openai_text_verbosity",
+ "logprobs": "openai_logprobs",
+ }
+
+ @classmethod
+ def _settings_type(cls) -> type:
+ # Heavy third-party SDK: importing the OpenAI model module imports
``openai``.
+ from pydantic_ai.models.openai import OpenAIResponsesModelSettings
+
+ return OpenAIResponsesModelSettings
+
+ def _build_settings(
+ self,
+ model: Model,
+ *layers: Mapping[str, Any] | None,
+ max_tokens: int,
+ ) -> tuple[ModelSettings, set[str]]:
+ for layer in layers:
+ for key in sorted((layer or {}).keys() &
self._CHAT_COMPLETIONS_RENAMES.keys()):
+ raise LLMBatchInputError(
+ f"{key!r} is a Chat Completions parameter, and batches run
on the Responses API; "
+ f"use {self._CHAT_COMPLETIONS_RENAMES[key]!r}."
+ )
+ return super()._build_settings(model, *layers, max_tokens=max_tokens)
+
+ @staticmethod
+ def _responses_model_id(model_id: str) -> str:
+ """Return ``model_id`` with pydantic-ai's Chat Completions prefix
swapped for the Responses one."""
+ prefix, sep, bare = model_id.partition(":")
+ return f"openai:{bare}" if sep and prefix == "openai-chat" else
model_id
+
+ async def _amodel(self, model_id: str) -> Model:
+ return await super()._amodel(self._responses_model_id(model_id))
+
+ async def _encode(
+ self, stack: AsyncExitStack, requests: list[BatchRequest], **kwargs:
Any
+ ) -> tuple[Model, str, list[EncodedBatchRequest]]:
+ # Logged here, which only validating and submitting reach, not on
every poll, cancel and landing.
+ for model_id in sorted({self._model_id or "", *(request.get("model")
or "" for request in requests)}):
+ if (responses_id := self._responses_model_id(model_id)) !=
model_id:
+ log.info(
+ "Batches run on the OpenAI Responses API; using
openai:<model> in place of openai-chat:<model>",
+ model=responses_id.partition(":")[2],
+ )
+ return await super()._encode(stack, requests, **kwargs)
+
+ async def acancel_batch(self, batch_id: str) -> None:
+ if self._handle or not self._model_id:
+ await super().acancel_batch(batch_id)
+ return
+ # A batch an earlier version of this provider recorded has no handle,
but cancelling takes only its id.
+ async with await self._amodel(self._model_id) as model:
+ # Heavy third-party SDK: importing the OpenAI model module imports
``openai``.
+ from pydantic_ai.models.openai import OpenAIResponsesModel
+
+ if not isinstance(model, OpenAIResponsesModel):
+ await super().acancel_batch(batch_id)
+ return
+ await model.client.batches.cancel(batch_id)
+
+ async def _stream_results(self, model: Model, batch: Batch) ->
AsyncGenerator[BatchResult, None]:
+ # Heavy third-party SDK: importing the OpenAI model module imports
``openai``.
+ from pydantic_ai.models.openai import OpenAIResponsesModel
+
+ if not isinstance(model, OpenAIResponsesModel) or
model.batch_max_requests is None:
+ # Not a model pydantic-ai batches through: its collect raises the
right error.
+ async for collected in super()._stream_results(model, batch):
+ yield collected
+ return
+ # ``batch_status`` has already checked the credentials and the group,
as ``batch_results`` would.
+ # The handle of an ended batch names its final files, as it does for
pydantic-ai's own collect.
+ details = batch.provider_details or {}
+ # Only the ids seen are kept, to find the requests the batch never ran.
+ seen: set[str] = set()
+ for file_id in (details.get("output_file_id"),
details.get("error_file_id")):
+ if file_id:
+ async with aclosing(self._file_lines(model, file_id)) as lines:
+ line_number = 0
+ async for raw in lines:
+ line_number += 1
+ if (
+ line := _parse_line(
+ _OpenAIOutputLine, raw, file_id=file_id,
line_number=line_number
+ )
+ ) is None:
+ continue
+ result = _openai_result(line)
+ seen.add(result.custom_id)
+ yield result
+ if details["status"] != "completed":
+ # The output and error files have no line for a request the batch
didn't run, so the input file lists them.
+ input_file_id = details["input_file_id"]
+ async with aclosing(self._file_lines(model, input_file_id)) as
lines:
+ line_number = 0
+ async for raw in lines:
+ line_number += 1
+ input_line = _parse_line(
+ _OpenAIInputLine, raw, file_id=input_file_id,
line_number=line_number
+ )
+ if input_line is not None and input_line.custom_id not in
seen:
+ yield _openai_unrun_result(details,
input_line.custom_id, line_number)
+
+ @staticmethod
+ async def _file_lines(model: OpenAIResponsesModel, file_id: str) ->
AsyncGenerator[bytes, None]:
+ """Yield a file's lines as they arrive; the response is closed when
the iteration ends or is closed."""
+ async with model.client.files.with_streaming_response.content(file_id)
as response:
+ async with aclosing(_split_lines(response.iter_bytes())) as lines:
+ async for line in lines:
+ yield line
+
+ async def _unrecorded_batch(self, model: Model, batch_id: str) -> Batch:
+ """
+ Refuse a batch an earlier version of this provider submitted, which
cannot be read back.
+
+ That version created OpenAI batches against ``/v1/chat/completions``.
pydantic-ai decodes
+ only Responses output, so the results of such a batch cannot be read.
+ """
+ raise LLMBatchStateReadError(
+ f"Batch {batch_id!r} was submitted by an earlier version of this
provider to the Chat "
+ "Completions endpoint, and this version reads only Responses API
batches. Let it finish or "
+ "cancel it at OpenAI, then delete this task's batch state file
under the result path's "
+ "'_airflow_batch_state' directory so a retry submits a new batch."
+ )
+
+ async def _describe(self, model: Model, batch: Batch) -> BatchState:
+ # ``ended`` covers every terminal job status, so the outcome is in the
job's own status.
+ job_status = (batch.provider_details or {}).get("status")
+ if batch.status == "ended" and job_status in self._ENDED_STATUSES:
+ status = self._ENDED_STATUSES[job_status]
+ message = self._failure_message(batch) if status == "failed" else
None
+ return BatchState(status=status, counts=None,
error_message=message)
+ return await super()._describe(model, batch)
+
+ @staticmethod
+ def _failure_message(batch: Batch) -> str:
+ """Describe a job OpenAI rejected before running it, from the
validation errors on the handle."""
+ message = f"OpenAI batch {batch.id} failed before processing."
+ reasons = []
+ for error in (batch.provider_details or {}).get("errors", []):
+ if not isinstance(error, Mapping):
+ continue
+ where = f"line {error['line']}: " if error.get("line") is not None
else ""
+ reasons.append(f"{where}{error.get('message') or error.get('code')
or 'unknown error'}")
+ return f"{message} {'; '.join(reasons)}" if reasons else message
+
+
class AnthropicBatchAdapter(PydanticAIBatchAdapter):
"""
Batch adapter for Anthropic's Message Batches API.
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_llm_batch.py
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_llm_batch.py
index c3c50e5d24d..f0b5a23874a 100644
---
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_llm_batch.py
+++
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_llm_batch.py
@@ -126,10 +126,9 @@ example_llm_batch_decorator()
# [START howto_operator_llm_batch_provider_params]
@dag(tags=["example"])
def example_llm_batch_provider_params():
- # For an ``openai:`` model ``request_params`` is merged into every request
body as-is
- # (OpenAI chat-completions keys). For an ``anthropic:`` model, sampling
settings such as
- # ``temperature`` are typed settings and Messages fields such as
``metadata`` are merged
- # into the body. ``max_tokens`` is translated per provider
(``max_completion_tokens`` on OpenAI).
+ # Sampling settings such as ``temperature`` and ``openai_*`` /
``anthropic_*`` settings are typed
+ # settings. Any other key is a raw request field: ``user`` goes into the
OpenAI Responses body and
+ # ``metadata`` into the Anthropic Messages body. ``max_tokens`` is
translated per provider.
LLMBatchOperator(
task_id="extract_keywords_openai",
requests=[f"Review: {review!r}" for review in REVIEWS],
@@ -139,7 +138,7 @@ def example_llm_batch_provider_params():
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"},
+ request_params={"openai_reasoning_effort": "low", "user":
"reviews-pipeline"},
fail_on_partial_error=True,
deferrable=True,
)
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_batch.py
b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_batch.py
index 21c32faf1be..009b55e9fd5 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_batch.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_batch.py
@@ -96,7 +96,8 @@ class LLMBatchOperator(BaseOperator):
:param model_id: Model identifier as ``"<provider>:<model>"`` (e.g.
``"openai:gpt-6.1-sol"``). Falls back to the connection's Model field,
as
``LLMOperator`` does. A bare name takes the connection's Default
- Provider, and ``openai-chat:`` selects the OpenAI adapter.
+ Provider, and ``openai-chat:`` selects the OpenAI adapter, which runs
the
+ batch on the Responses API.
:param system_prompt: System-level instructions applied to every request
that does not set its own ``system_prompt`` override.
:param output_type: Expected output type. Default ``str``. Set to a
@@ -104,14 +105,14 @@ class LLMBatchOperator(BaseOperator):
supports) for structured output; every result row is plain JSON.
:param max_tokens: Output token cap for requests that do not set their
own. Sent as ``max_tokens`` to Anthropic and as
- ``max_completion_tokens`` to OpenAI.
+ ``max_output_tokens`` to OpenAI.
:param request_params: Extra parameters for every request
(e.g. ``{"temperature": 0.2}``); a request's own ``params`` wins on
conflicting keys. The keys the operator manages (``model``, the
messages, the token cap and the structured-output directive) cannot
- be overridden from here. OpenAI merges them into the request body
as-is.
- Anthropic takes sampling and ``anthropic_*`` keys as typed settings and
- merges every other key into the body. Gemini accepts typed settings
only.
+ be overridden from here. OpenAI and Anthropic take sampling and
provider-prefixed
+ (``openai_*``, ``anthropic_*``) keys as typed settings and merge every
other
+ key into the request body. Gemini accepts typed settings only.
Templated: every string inside the dict is rendered, and Jinja hands
back
a string, so a numeric parameter written as a template needs
``render_template_as_native_obj=True`` on the Dag.
@@ -146,12 +147,12 @@ class LLMBatchOperator(BaseOperator):
:param on_orphaned_intent: What to do when a previous attempt recorded
its intent to submit but no batch id, and the provider-side lookup
finds no matching batch: ``"resubmit"`` (default) submits a new
- batch; ``"fail"`` raises instead. Anthropic and Gemini offer no such
- lookup, so ``"resubmit"`` may pay twice there if the original request
- did reach the provider.
- :param completion_window: OpenAI-specific completion window. Only
- ``"24h"`` is offered by the API today. Ignored by Anthropic and
Gemini, which warn when it is
- set to anything else.
+ batch; ``"fail"`` raises instead. The built-in adapters offer no such
+ lookup, so ``"resubmit"`` may pay twice if the original request did
+ reach the provider.
+ :param completion_window: Completion window for an adapter that lets the
caller choose
+ one. Only ``"24h"`` is offered by the providers today, and the
built-in adapters
+ ignore it, warning when it is set to anything else.
"""
template_fields: Sequence[str] = (
@@ -388,7 +389,7 @@ class LLMBatchOperator(BaseOperator):
and not adapter.supports_completion_window
):
self.log.warning(
- "completion_window=%r is ignored: the %s batch API has no
such setting.",
+ "completion_window=%r is ignored: %s batches run on the
provider's default window.",
self.completion_window,
adapter_name,
)
diff --git a/providers/common/ai/tests/unit/common/ai/batch/test_dispatch.py
b/providers/common/ai/tests/unit/common/ai/batch/test_dispatch.py
index c057db919e7..8fbef599f20 100644
--- a/providers/common/ai/tests/unit/common/ai/batch/test_dispatch.py
+++ b/providers/common/ai/tests/unit/common/ai/batch/test_dispatch.py
@@ -25,10 +25,10 @@ import pytest
from airflow.providers.common.ai.batch import dispatch
from airflow.providers.common.ai.batch.base import BatchAdapter
-from airflow.providers.common.ai.batch.openai import OpenAIBatchAdapter
from airflow.providers.common.ai.batch.pydantic_ai_backend import (
AnthropicBatchAdapter,
GoogleBatchAdapter,
+ OpenAIBatchAdapter,
)
from airflow.providers.common.ai.exceptions import (
BatchProviderNotYetSupportedError,
@@ -90,9 +90,11 @@ class TestGetAdapterClass:
with pytest.raises(UnsupportedBatchProviderError, match="'groq' has no
batch adapter"):
dispatch.get_adapter_class("pydanticai", "groq:llama")
- def test_openai_chat_prefix_selects_the_openai_adapter(self):
- """pydantic-ai's Chat Completions prefix names the endpoint the OpenAI
adapter submits to."""
- assert dispatch.get_adapter_class("pydanticai", "openai-chat:gpt-5")
is OpenAIBatchAdapter
+ @pytest.mark.parametrize("prefix", ["openai-chat", "openai-responses"])
+ def
test_pydantic_ais_other_openai_prefixes_select_the_openai_adapter(self, prefix):
+ """Both are served by the OpenAI adapter, which runs the batch on the
Responses API."""
+ assert dispatch.get_adapter_class("pydanticai", f"{prefix}:gpt-5") is
OpenAIBatchAdapter
+ assert dispatch.resolve_adapter_name("pydanticai", f"{prefix}:gpt-5")
== "openai"
@pytest.mark.parametrize("model_id", ["google-cloud:gemini-2.5-flash",
"google-vertex:gemini-2.5-flash"])
def test_vertex_is_refused_with_the_fix(self, model_id):
@@ -132,52 +134,44 @@ class TestRegistration:
class TestBuildAdapter:
- def test_build_adapter_from_connection_maps_password_and_host(self):
- pytest.importorskip("openai")
- conn = Connection(
- conn_id="c", conn_type="pydanticai", password="sk-test",
host="https://gateway.example"
- )
-
- adapter = dispatch.build_adapter_from_connection("openai", conn)
+ @pytest.mark.parametrize(
+ ("name", "model_id", "adapter_cls"),
+ [
+ ("openai", "openai:gpt-5-mini", OpenAIBatchAdapter),
+ ("anthropic", "anthropic:claude-sonnet-4-5",
AnthropicBatchAdapter),
+ ("google", "google:gemini-2.5-flash", GoogleBatchAdapter),
+ ],
+ )
+ def test_a_built_in_adapter_is_built_from_the_connection_hook(self, name,
model_id, adapter_cls):
+ conn = Connection(conn_id="my_llm", conn_type="pydanticai",
password="sk-test")
+ hook = mock.create_autospec(PydanticAIHook, instance=True)
+ hook._get_fallback_conn_ids.return_value = []
+ with mock.patch.object(
+ PydanticAIHook, "get_hook_for_connection", autospec=True,
return_value=hook
+ ) as get_hook:
+ adapter = dispatch.build_adapter_from_connection(
+ name, conn, model_id=model_id, batch_handle='{"id": "b"}'
+ )
- assert isinstance(adapter, OpenAIBatchAdapter)
- assert adapter._client.api_key == "sk-test"
- assert str(adapter._client.base_url).rstrip("/") ==
"https://gateway.example"
- adapter.close()
+ get_hook.assert_called_once_with(conn, {"model_id": model_id})
+ assert isinstance(adapter, adapter_cls)
+ assert adapter._hook is hook
+ assert adapter._handle == '{"id": "b"}'
def test_build_adapter_fetches_the_connection_by_id(self):
- pytest.importorskip("openai")
conn = Connection(conn_id="c", conn_type="pydanticai",
password="sk-test", host=None)
- with mock.patch.object(
- dispatch.BaseHook, "get_connection", autospec=True,
return_value=conn
- ) as get_conn:
- adapter = dispatch.build_adapter("openai", llm_conn_id="my_openai")
-
- get_conn.assert_called_once_with("my_openai")
- assert isinstance(adapter, OpenAIBatchAdapter)
- adapter.close()
-
- def test_pydantic_ai_adapter_is_built_from_the_connection_hook(self):
- conn = Connection(conn_id="my_anthropic", conn_type="pydanticai",
password="sk-ant")
hook = mock.create_autospec(PydanticAIHook, instance=True)
hook._get_fallback_conn_ids.return_value = []
with (
- mock.patch.object(dispatch.BaseHook, "get_connection",
autospec=True, return_value=conn),
mock.patch.object(
- PydanticAIHook, "get_hook_for_connection", autospec=True,
return_value=hook
- ) as get_hook,
+ dispatch.BaseHook, "get_connection", autospec=True,
return_value=conn
+ ) as get_conn,
+ mock.patch.object(PydanticAIHook, "get_hook", autospec=True,
return_value=hook),
):
- adapter = dispatch.build_adapter(
- "anthropic",
- llm_conn_id="my_anthropic",
- model_id="anthropic:claude-sonnet-4-5",
- batch_handle='{"id": "b"}',
- )
+ adapter = dispatch.build_adapter("openai",
llm_conn_id="my_openai", model_id="openai:gpt-5")
- get_hook.assert_called_once_with(conn, {"model_id":
"anthropic:claude-sonnet-4-5"})
- assert isinstance(adapter, AnthropicBatchAdapter)
- assert adapter._hook is hook
- assert adapter._handle == '{"id": "b"}'
+ get_conn.assert_called_once_with("my_openai")
+ assert isinstance(adapter, OpenAIBatchAdapter)
class TestNoSdkImportAtDispatchTime:
diff --git a/providers/common/ai/tests/unit/common/ai/batch/test_openai.py
b/providers/common/ai/tests/unit/common/ai/batch/test_openai.py
deleted file mode 100644
index ff20fbaa9ca..00000000000
--- a/providers/common/ai/tests/unit/common/ai/batch/test_openai.py
+++ /dev/null
@@ -1,524 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-from __future__ import annotations
-
-import contextlib
-import json
-from dataclasses import dataclass
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-from pydantic import BaseModel, Field
-
-from airflow.providers.common.ai.batch.base import RawResultItem
-from airflow.providers.common.ai.batch.openai import OpenAIBatchAdapter
-from airflow.providers.common.ai.batch.output_schema import build_output_spec
-from airflow.providers.common.ai.exceptions import LLMBatchLimitExceededError,
LLMBatchModelMismatchError
-
-openai = pytest.importorskip("openai")
-
-from openai.types import Batch # noqa: E402
-
-KEY = "k" * 16
-
-
-def _batch(
- *,
- status: str = "completed",
- completed: int = 1,
- failed: int = 0,
- total: int = 1,
- errors: list[dict] | None = None,
- metadata: dict | None = None,
- created_at: int = 1_000_000,
- id_: str = "batch_123",
-) -> Batch:
- """A real SDK ``Batch`` so the adapter is exercised against the shape the
API returns."""
- return Batch.model_validate(
- {
- "id": id_,
- "object": "batch",
- "endpoint": "/v1/chat/completions",
- "input_file_id": "file-input-xyz",
- "completion_window": "24h",
- "status": status,
- "created_at": created_at,
- "output_file_id": "file-out",
- "error_file_id": "file-err",
- "request_counts": {"completed": completed, "failed": failed,
"total": total},
- "errors": {"object": "list", "data": errors} if errors is not None
else None,
- "metadata": metadata,
- }
- )
-
-
-@dataclass
-class _FakeUploadedFile:
- id: str = "file-input-xyz"
-
-
-class _FakeStreamingContent:
- def __init__(self, contents: dict[str, list[str]]):
- self._contents = contents
-
- @contextlib.contextmanager
- def content(self, file_id: str):
- lines = self._contents.get(file_id, [])
- yield SimpleNamespace(iter_lines=lambda: iter(lines))
-
-
-class _FakeFiles:
- """Fake for ``client.files``: records the upload and serves canned result
files through the streaming API."""
-
- def __init__(self):
- self.created: list[dict] = []
- self._contents: dict[str, list[str]] = {}
- self.with_streaming_response = _FakeStreamingContent(self._contents)
-
- def create(self, *, file, purpose):
- self.created.append({"file": file, "purpose": purpose})
- return _FakeUploadedFile()
-
- def set_content(self, file_id: str, lines: list[dict | str]):
- self._contents[file_id] = [line if isinstance(line, str) else
json.dumps(line) for line in lines]
-
-
-class _FakeBatches:
- def __init__(self):
- self.created: list[dict] = []
- self.cancelled: list[str] = []
- self._listing: list[Any] = []
- self.batch = _batch()
-
- def create(self, **kwargs):
- self.created.append(kwargs)
- return self.batch
-
- def retrieve(self, batch_id):
- return self.batch
-
- def cancel(self, batch_id):
- self.cancelled.append(batch_id)
- return self.batch
-
- def set_listing(self, batches: list[Any]) -> None:
- self._listing = batches
-
- def list(self, *, limit=100):
- return iter(self._listing)
-
-
-class _FakeOpenAIClient:
- def __init__(self):
- self.files = _FakeFiles()
- self.batches = _FakeBatches()
- self.closed = False
-
- def close(self):
- self.closed = True
-
-
[email protected]
-def client():
- return _FakeOpenAIClient()
-
-
[email protected]
-def adapter(client):
- return OpenAIBatchAdapter(client=client)
-
-
[email protected]
-def str_spec():
- return build_output_spec(str)
-
-
-class Diagnosis(BaseModel):
- age: int
-
-
-def _submit(adapter, requests, spec, **kwargs):
- return adapter.submit(
- requests, model="gpt-5", idempotency_key=KEY, input_fingerprint="fp" *
8, output_spec=spec, **kwargs
- )
-
-
-def _uploaded_lines(client) -> list[dict]:
- uploaded_bytes = client.files.created[0]["file"][1]
- return [json.loads(line) for line in uploaded_bytes.decode().splitlines()]
-
-
-def _success_line(index: int, content: str | None = "hello", *, finish_reason:
str = "stop") -> dict:
- return {
- "custom_id": f"{KEY}-{index}",
- "response": {
- "status_code": 200,
- "body": {
- "model": "gpt-5",
- "choices": [{"message": {"content": content}, "finish_reason":
finish_reason}],
- "usage": {"prompt_tokens": 3, "completion_tokens": 1},
- },
- },
- }
-
-
-class TestClientConstruction:
- def test_builds_the_sdk_client_from_api_key_and_base_url(self):
- adapter = OpenAIBatchAdapter(api_key="sk-test",
base_url="https://gateway.example/v1")
- try:
- assert isinstance(adapter._client, openai.OpenAI)
- assert adapter._client.api_key == "sk-test"
- assert str(adapter._client.base_url).rstrip("/") ==
"https://gateway.example/v1"
- finally:
- adapter.close()
-
- def test_close_closes_the_client(self, adapter, client):
- adapter.close()
- assert client.closed is True
-
-
-class TestSubmitRequestShape:
- def test_custom_id_is_key16_dash_index(self, adapter, client, str_spec):
- _submit(adapter, [{"prompt": "a"}, {"prompt": "b"}], str_spec)
- assert [line["custom_id"] for line in _uploaded_lines(client)] ==
[f"{KEY}-0", f"{KEY}-1"]
-
- def test_upload_is_newline_terminated_jsonl(self, adapter, client,
str_spec):
- _submit(adapter, [{"prompt": "a"}, {"prompt": "b"}], str_spec)
- name, uploaded_bytes = client.files.created[0]["file"]
- assert name == f"{KEY}.jsonl"
- assert uploaded_bytes.endswith(b"\n")
- assert uploaded_bytes.count(b"\n") == 2
- assert client.files.created[0]["purpose"] == "batch"
-
- def test_body_uses_max_completion_tokens_never_max_tokens(self, adapter,
client, str_spec):
- """``max_tokens`` is deprecated and rejected by reasoning models such
as gpt-5."""
- _submit(adapter, [{"prompt": "a"}, {"prompt": "b", "max_tokens": 7}],
str_spec, max_tokens=99)
- bodies = [line["body"] for line in _uploaded_lines(client)]
- assert bodies[0]["max_completion_tokens"] == 99
- assert bodies[1]["max_completion_tokens"] == 7
- assert all("max_tokens" not in body for body in bodies)
-
- def test_request_params_cannot_override_the_managed_keys(self, adapter,
client, str_spec):
- _submit(
- adapter,
- [{"prompt": "a", "params": {"messages": [{"role": "user",
"content": "CLOBBER"}]}}],
- str_spec,
- request_params={"model": "someone-elses-model", "temperature":
0.2, "max_tokens": 5},
- )
- body = _uploaded_lines(client)[0]["body"]
- assert body["model"] == "gpt-5"
- assert body["messages"] == [{"role": "user", "content": "a"}]
- assert body["max_completion_tokens"] == 1024
- assert "max_tokens" not in body
- assert body["temperature"] == 0.2
-
- def test_submit_records_idempotency_key_and_fingerprint_in_metadata(self,
adapter, client, str_spec):
- adapter.submit(
- [{"prompt": "a"}],
- model="gpt-5",
- idempotency_key="a1b2c3d4e5f60718",
- input_fingerprint="0123456789abcdef" +
"extra-material-hashed-away",
- output_spec=str_spec,
- )
- metadata = client.batches.created[0]["metadata"]
- assert metadata == {"idempotency_key": "a1b2c3d4e5f60718",
"input_fingerprint": "0123456789abcdef"}
-
- def test_response_format_is_merged_inside_body_not_alongside_it(self,
adapter, client):
- spec = build_output_spec(Diagnosis)
- _submit(adapter, [{"prompt": "a"}], spec)
- line = _uploaded_lines(client)[0]
- assert "response_format" not in line
- assert line["body"]["response_format"]["json_schema"]["name"] ==
"Diagnosis"
- assert
line["body"]["response_format"]["json_schema"]["schema"]["type"] == "object"
- assert line["body"]["messages"][-1] == {"role": "user", "content": "a"}
-
- def test_submit_returns_batch_id_and_input_file_ref(self, adapter,
str_spec):
- result = _submit(adapter, [{"prompt": "a"}], str_spec)
- assert result.batch_id == "batch_123"
- assert result.provider_input_ref == "file-input-xyz"
-
-
-class TestValidateRequests:
- def test_over_limit_request_count_rejected(self, adapter, str_spec):
- adapter.max_requests = 2
- with pytest.raises(LLMBatchLimitExceededError, match="at most 2
requests"):
- adapter.validate_requests(
- [{"prompt": "a"}, {"prompt": "b"}, {"prompt": "c"}],
- model="gpt-5",
- idempotency_key=KEY,
- output_spec=str_spec,
- )
-
- def test_mixed_per_request_models_rejected(self, adapter, str_spec):
- with pytest.raises(LLMBatchModelMismatchError, match="Per-request
model overrides"):
- adapter.validate_requests(
- [{"prompt": "a", "model": "openai:gpt-5-mini"}, {"prompt":
"b"}],
- model="gpt-5",
- idempotency_key=KEY,
- output_spec=str_spec,
- )
-
- def test_uniform_models_pass(self, adapter, str_spec):
- adapter.validate_requests(
- [{"prompt": "a", "model": "openai:gpt-5"}, {"prompt": "b"}],
- model="gpt-5",
- idempotency_key=KEY,
- output_spec=str_spec,
- )
-
- def test_foreign_provider_per_request_model_rejected(self, adapter,
str_spec):
- with pytest.raises(LLMBatchModelMismatchError, match="Request 0"):
- adapter.validate_requests(
- [{"prompt": "a", "model": "anthropic:claude-3-opus"}],
- model="gpt-5",
- idempotency_key=KEY,
- output_spec=str_spec,
- )
-
- def test_payload_size_estimate_includes_output_directive(self, adapter):
- class Big(BaseModel):
- field: str = Field(description="x" * 5000)
-
- adapter.max_payload_bytes = 100
- with pytest.raises(LLMBatchLimitExceededError, match="output_type
schema adds"):
- adapter.validate_requests(
- [{"prompt": "a"}], model="gpt-5", idempotency_key=KEY,
output_spec=build_output_spec(Big)
- )
-
- def test_payload_size_estimate_matches_the_uploaded_bytes(self, adapter,
client, str_spec):
- requests = [{"prompt": "a" * 50}, {"prompt": "b" * 70}]
- _submit(adapter, requests, str_spec)
- uploaded = len(client.files.created[0]["file"][1])
- adapter.max_payload_bytes = uploaded
- adapter.validate_requests(requests, model="gpt-5",
idempotency_key=KEY, output_spec=str_spec)
- adapter.max_payload_bytes = uploaded - 1
- with pytest.raises(LLMBatchLimitExceededError):
- adapter.validate_requests(requests, model="gpt-5",
idempotency_key=KEY, output_spec=str_spec)
-
- def test_over_length_custom_id_rejected(self, adapter, str_spec):
- with pytest.raises(LLMBatchLimitExceededError, match="custom_id"):
- adapter.validate_requests(
- [{"prompt": "a"}] * 100_000, model="gpt-5",
idempotency_key="k" * 60, output_spec=str_spec
- )
-
-
-class TestFindOrphanedBatch:
- _FP = "f" * 16
-
- def _batch(self, id_, *, key="the-key", fp=None, created_at=1_000_000):
- return _batch(
- id_=id_,
- created_at=created_at,
- metadata={"idempotency_key": key, "input_fingerprint": fp if fp is
not None else self._FP},
- )
-
- def test_finds_batch_with_matching_metadata(self, adapter, client):
- client.batches.set_listing([self._batch("batch_other",
key="other-key"), self._batch("batch_match")])
- assert adapter.find_orphaned_batch("the-key", self._FP,
"1970-01-01T00:00:00+00:00") == "batch_match"
-
- def test_returns_none_when_no_batch_matches(self, adapter, client):
- client.batches.set_listing([self._batch("batch_other", key="x")])
- assert adapter.find_orphaned_batch("the-key", self._FP,
"1970-01-01T00:00:00+00:00") is None
-
- def test_returns_none_when_metadata_is_missing(self, adapter, client):
- client.batches.set_listing([_batch(id_="batch_other", metadata=None,
created_at=0)])
- assert adapter.find_orphaned_batch("the-key", self._FP,
"1970-01-01T00:00:00+00:00") is None
-
- def test_fingerprint_mismatch_is_not_recovered(self, adapter, client):
- """The key alone is stable across a ``clear`` with different prompts;
only the fingerprint ties a batch to this input."""
- client.batches.set_listing([self._batch("batch_stale",
fp="stale-fingerprint")])
- assert adapter.find_orphaned_batch("the-key", self._FP,
"1970-01-01T00:00:00+00:00") is None
-
- def test_candidate_created_well_before_not_before_is_rejected(self,
adapter, client):
- not_before = "1970-01-12T13:46:50+00:00" # epoch 1_000_010
- client.batches.set_listing([self._batch("batch_too_old",
created_at=999_000)])
- assert adapter.find_orphaned_batch("the-key", self._FP, not_before) is
None
-
- def
test_candidate_created_within_clock_skew_slack_is_still_recovered(self,
adapter, client):
- """``created_at`` is whole seconds while ``not_before`` carries
microseconds."""
- not_before = "1970-01-12T13:46:50.500000+00:00" # epoch 1_000_010.5
- client.batches.set_listing([self._batch("batch_same_second",
created_at=1_000_010)])
- assert adapter.find_orphaned_batch("the-key", self._FP, not_before) ==
"batch_same_second"
-
- def test_candidate_created_120s_before_not_before_is_still_recovered(self,
adapter, client):
- not_before = "1970-01-12T13:46:50+00:00"
- client.batches.set_listing([self._batch("batch_120s_early",
created_at=1_000_010 - 120)])
- assert adapter.find_orphaned_batch("the-key", self._FP, not_before) ==
"batch_120s_early"
-
- def test_most_recently_created_match_wins_among_ties(self, adapter,
client):
- client.batches.set_listing(
- [
- self._batch("batch_older", created_at=1_000_000),
- self._batch("batch_newer", created_at=2_000_000),
- ]
- )
- assert adapter.find_orphaned_batch("the-key", self._FP,
"1970-01-01T00:00:00+00:00") == "batch_newer"
-
-
-class TestGetBatchAndCancel:
- def test_get_batch_maps_completed_status(self, adapter):
- state = adapter.get_batch("batch_123")
- assert state.status == "completed"
- assert state.counts == {"succeeded": 1, "errored": 0, "expired": 0,
"cancelled": 0}
- assert state.error_message is None
-
- def test_cancel_batch_calls_sdk_cancel(self, adapter, client):
- adapter.cancel_batch("batch_123")
- assert client.batches.cancelled == ["batch_123"]
-
- def test_expired_batch_attributes_remainder_to_expired(self, adapter,
client):
- client.batches.batch = _batch(status="expired", completed=2, failed=1,
total=10)
- assert adapter.get_batch("batch_123").counts == {
- "succeeded": 2,
- "errored": 1,
- "expired": 7,
- "cancelled": 0,
- }
-
- def test_cancelled_batch_attributes_remainder_to_cancelled(self, adapter,
client):
- client.batches.batch = _batch(status="cancelled", completed=3,
failed=0, total=5)
- assert adapter.get_batch("batch_123").counts == {
- "succeeded": 3,
- "errored": 0,
- "expired": 0,
- "cancelled": 2,
- }
-
- def test_failed_batch_renders_the_providers_errors_as_text(self, adapter,
client):
- client.batches.batch = _batch(
- status="failed",
- completed=0,
- total=0,
- errors=[
- {
- "code": "token_limit_exceeded",
- "message": "Enqueued token limit reached",
- "line": None,
- "param": None,
- }
- ],
- )
- state = adapter.get_batch("batch_123")
- assert state.status == "failed"
- assert state.error_message == "token_limit_exceeded: Enqueued token
limit reached"
-
- def test_empty_errors_list_is_no_message(self, adapter, client):
- client.batches.batch = _batch(errors=[])
- assert adapter.get_batch("batch_123").error_message is None
-
-
-class TestIterResults:
- def test_success_and_error_files_both_yielded(self, adapter, client):
- client.files.set_content("file-out", [_success_line(0)])
- client.files.set_content(
- "file-err", [{"custom_id": f"{KEY}-1", "error": {"message": "rate
limited"}, "response": None}]
- )
- items = list(adapter.iter_results("batch_123"))
- assert [item.index for item in items] == [0, 1]
- assert items[0].provider_status == "success"
- assert items[0].raw == "hello"
- assert items[1].provider_status == "errored"
- assert items[1].error["message"] == "rate limited"
-
- def test_batch_expired_error_lines_are_expired_not_errored(self, adapter,
client):
- """OpenAI writes requests it never ran to the error file with code
``batch_expired``."""
- client.files.set_content("file-out", [_success_line(0)])
- client.files.set_content(
- "file-err",
- [
- {
- "custom_id": f"{KEY}-1",
- "response": None,
- "error": {
- "code": "batch_expired",
- "message": "This request could not be executed before
the completion window expired.",
- },
- }
- ],
- )
- items = list(adapter.iter_results("batch_123"))
- assert items[1].provider_status == "expired"
- assert items[1].error["type"] == "expired"
- assert items[1].error["provider_code"] == "batch_expired"
-
- def test_per_request_http_error_uses_the_body_error_message(self, adapter,
client):
- client.files.set_content(
- "file-err",
- [
- {
- "custom_id": f"{KEY}-0",
- "error": None,
- "response": {
- "status_code": 400,
- "request_id": "req_x",
- "body": {
- "error": {
- "message": "Unsupported parameter:
'max_tokens'",
- "code": "unsupported_parameter",
- }
- },
- },
- }
- ],
- )
- client.files.set_content("file-out", [])
- (item,) = adapter.iter_results("batch_123")
- assert item.provider_status == "errored"
- assert item.error["message"] == "Unsupported parameter: 'max_tokens'"
- assert item.error["provider_code"] == "unsupported_parameter"
-
- def test_a_malformed_line_is_skipped_and_the_stream_continues(self,
adapter, client):
- client.files.set_content(
- "file-out", ["<html>502 Bad Gateway</html>", _success_line(1),
json.dumps({"custom_id": None})]
- )
- items = list(adapter.iter_results("batch_123"))
- assert [item.index for item in items] == [1]
-
- def test_files_are_read_through_the_streaming_response(self, adapter,
client):
- """A plain ``files.content()`` reads the whole file into memory; the
streaming form must be used."""
- assert not hasattr(client.files, "content")
- client.files.set_content("file-out", [_success_line(0)])
- assert len(list(adapter.iter_results("batch_123"))) == 1
-
-
-class TestExtractOutput:
- def _raw(self, content) -> RawResultItem:
- return RawResultItem(
- custom_id=f"{KEY}-0",
- index=0,
- provider_status="success",
- model="gpt-5",
- usage=None,
- finish_reason="stop",
- error=None,
- raw=content,
- )
-
- def test_unstructured_is_plain_text(self, adapter, str_spec):
- extracted = adapter.extract_output(self._raw("hello"), str_spec)
- assert extracted.kind == "text"
- assert extracted.text == "hello"
-
- def test_structured_is_json_text(self, adapter):
- extracted = adapter.extract_output(self._raw('{"age": 3}'),
build_output_spec(Diagnosis))
- assert extracted.kind == "json_text"
-
- @pytest.mark.parametrize("output_type", [str, Diagnosis])
- def test_null_content_is_absent_not_success(self, adapter, output_type):
- """A refusal, or a reasoning model that spent its budget before
visible output, has no content."""
- assert adapter.extract_output(self._raw(None),
build_output_spec(output_type)).kind == "absent"
diff --git
a/providers/common/ai/tests/unit/common/ai/batch/test_pydantic_ai_backend.py
b/providers/common/ai/tests/unit/common/ai/batch/test_pydantic_ai_backend.py
index ec77f720aad..de77c223469 100644
--- a/providers/common/ai/tests/unit/common/ai/batch/test_pydantic_ai_backend.py
+++ b/providers/common/ai/tests/unit/common/ai/batch/test_pydantic_ai_backend.py
@@ -17,6 +17,7 @@
from __future__ import annotations
import asyncio
+import contextlib
import dataclasses
import json
import threading
@@ -32,6 +33,7 @@ from pydantic import BaseModel, TypeAdapter, create_model
from structlog.typing import FilteringBoundLogger
pytest.importorskip("anthropic")
+pytest.importorskip("openai")
pytest.importorskip("google.genai")
from anthropic._decoders.jsonl import AsyncJSONLDecoder
@@ -40,6 +42,8 @@ from anthropic.types.beta.messages import
BetaMessageBatchIndividualResponse
from google.genai.batches import AsyncBatches
from google.genai.files import AsyncFiles
from google.genai.types import BatchJob, BatchJobDestination, JobError,
JobState
+from openai.resources.batches import AsyncBatches as OpenAIAsyncBatches
+from openai.types import Batch as OpenAIBatch
from pydantic_ai.exceptions import (
ModelHTTPError,
ModelRequestRejectedError,
@@ -60,9 +64,11 @@ from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.models.batch import Batch, BatchResult, BatchStatus
from pydantic_ai.models.function import AgentInfo, FunctionModel
from pydantic_ai.models.google import GoogleModel
+from pydantic_ai.models.openai import OpenAIResponsesModel
from pydantic_ai.profiles import ModelProfile
from pydantic_ai.providers.anthropic import AnthropicProvider
from pydantic_ai.providers.google import GoogleProvider
+from pydantic_ai.providers.openai import OpenAIProvider
from airflow.providers.common.ai.batch import pydantic_ai_backend as
backend_module
from airflow.providers.common.ai.batch.output_schema import build_output_spec
@@ -70,7 +76,10 @@ from airflow.providers.common.ai.batch.pydantic_ai_backend
import (
_RESULT_BUFFER,
AnthropicBatchAdapter,
GoogleBatchAdapter,
+ OpenAIBatchAdapter,
PydanticAIBatchAdapter,
+ _error_code,
+ _split_lines,
_stream,
)
from airflow.providers.common.ai.exceptions import (
@@ -87,6 +96,8 @@ KEY = "k" * 16
CLAUDE = "anthropic:claude-sonnet-4-5"
CLAUDE_OLD = "anthropic:claude-3-5-haiku-latest"
GEMINI = "google:gemini-2.5-flash"
+GPT = "openai:gpt-5-mini"
+GPT_4 = "openai:gpt-4.1-mini"
class Diagnosis(BaseModel):
@@ -175,6 +186,10 @@ def _gemini(name: str = "gemini-2.5-flash") -> GoogleModel:
return GoogleModel(name, provider=GoogleProvider(api_key="gemini-test"))
+def _gpt(name: str = "gpt-5-mini") -> OpenAIResponsesModel:
+ return OpenAIResponsesModel(name,
provider=OpenAIProvider(api_key="sk-test"))
+
+
def _submitted_on(adapter_cls, model, *, model_name: str, provider_name: str)
-> str:
"""Return the handle of a batch submitted on ``model``, with the group the
real model class computes."""
submitter = adapter_cls(model_id=f"{provider_name}:{model_name}",
model_factory=lambda _id: model)
@@ -434,7 +449,7 @@ class TestInMemoryBatchRoundTrip:
("absent", None, None),
]
- def test_an_http_error_becomes_an_errored_row_with_its_status(self):
+ def
test_an_http_error_becomes_an_errored_row_with_the_providers_message_and_code(self):
def reply(prompt):
raise ModelHTTPError(
429, "claude", {"error": {"type": "rate_limit_error",
"message": "slow down"}}
@@ -446,9 +461,25 @@ class TestInMemoryBatchRoundTrip:
(row,) = _adapter(recorder.model,
handle=submitted.handle).iter_results(submitted.batch_id)
assert row.provider_status == "errored"
- assert row.error["provider_code"] == "rate_limit_error"
- assert row.error["stage"] == "provider"
- assert "429" in row.error["message"]
+ assert row.error == {
+ "type": "errored",
+ "message": "slow down",
+ "provider_code": "rate_limit_error",
+ "stage": "provider",
+ }
+
+ def
test_an_http_error_whose_body_has_no_provider_object_keeps_the_status_and_pydantic_ais_message(self):
+ def reply(prompt):
+ raise ModelHTTPError(502, "claude", "bad gateway")
+
+ recorder = _Recorder(reply)
+ submitted = _submit(_adapter(recorder.model), [{"prompt": "a"}])
+
+ (row,) = _adapter(recorder.model,
handle=submitted.handle).iter_results(submitted.batch_id)
+
+ assert row.error["provider_code"] == 502
+ assert "502" in row.error["message"]
+ assert "bad gateway" in row.error["message"]
def
test_an_unreadable_result_is_skipped_so_the_merge_counts_it_missing(self):
def reply(prompt):
@@ -1092,6 +1123,311 @@ class TestStream:
list(_stream(source()))
+class _Lines(httpx2.AsyncByteStream):
+ """
+ A file's body served one line per chunk, which can stop arriving after
``fail_after`` lines.
+
+ A ``str`` line is served as it is, to stand for a line that is not JSON.
JSON is written without
+ escaping non-ASCII characters, as the API may write it.
+ """
+
+ def __init__(self, lines: list[dict | str], fail_after: int | None = None):
+ self.lines = [
+ ((line if isinstance(line, str) else json.dumps(line,
ensure_ascii=False)) + "\n").encode()
+ for line in lines
+ ]
+ self.fail_after = fail_after
+ self.pulled = 0
+ self.closed = False
+
+ async def __aiter__(self):
+ for line in self.lines:
+ if self.fail_after is not None and self.pulled >= self.fail_after:
+ raise RuntimeError("the next line has not arrived")
+ self.pulled += 1
+ yield line
+
+ async def aclose(self):
+ self.closed = True
+
+
+def _openai_output(index: int, status_code: int = 200, text: str | None =
None) -> dict:
+ """One line of OpenAI's output file, as the API writes it."""
+ if status_code == 200:
+ body = {
+ "id": f"resp_{index}",
+ "object": "response",
+ "created_at": 1760000000,
+ "model": "gpt-5-mini",
+ "status": "completed",
+ "output": [
+ {
+ "id": f"msg_{index}",
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [
+ {"type": "output_text", "text": text or f"answer
{index}", "annotations": []}
+ ],
+ }
+ ],
+ "usage": {
+ "input_tokens": 3,
+ "output_tokens": 2,
+ "total_tokens": 5,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens_details": {"reasoning_tokens": 0},
+ },
+ }
+ else:
+ body = {"error": {"message": "slow down", "type": "rate_limit_error",
"code": "rate_limit_exceeded"}}
+ return {
+ "id": f"batch_req_{index}",
+ "custom_id": f"{KEY}-{index}",
+ "response": {"status_code": status_code, "request_id": f"req_{index}",
"body": body},
+ "error": None,
+ }
+
+
+def _openai_error(index: int, code: str) -> dict:
+ """One line of OpenAI's error file for a request that never got a
response."""
+ return {
+ "id": f"batch_req_{index}",
+ "custom_id": f"{KEY}-{index}",
+ "response": None,
+ "error": {"code": code, "message": f"request {index}: {code}"},
+ }
+
+
+def _openai_input(count: int) -> list[dict]:
+ return [
+ {"custom_id": f"{KEY}-{i}", "method": "POST", "url": "/v1/responses",
"body": {}}
+ for i in range(count)
+ ]
+
+
+_OPENAI_JOBS = {
+ "completed": (
+ {"status": "completed", "output_file_id": "file-out", "error_file_id":
"file-err"},
+ {
+ "file-out": [_openai_output(0), _openai_output(1, 429)],
+ "file-err": [_openai_error(2, "batch_expired"), _openai_error(3,
"batch_cancelled")],
+ },
+ ),
+ "expired with unrun requests": (
+ {"status": "expired", "output_file_id": "file-out", "error_file_id":
"file-err"},
+ {
+ "file-out": [_openai_output(0)],
+ "file-err": [_openai_error(1, "batch_expired")],
+ "file-in": _openai_input(4),
+ },
+ ),
+ "cancelled before any request ran": (
+ {"status": "cancelled"},
+ {"file-in": _openai_input(3)},
+ ),
+ "failed validation": (
+ {
+ "status": "failed",
+ "errors": [
+ {"code": "invalid_json_line", "line": 2, "message": "bad
line"},
+ {"code": "token_limit", "message": "too many tokens"},
+ ],
+ },
+ {"file-in": _openai_input(3)},
+ ),
+}
+
+
+class TestOpenAIResultsStream:
+ """OpenAI's output, error and input files are read line by line instead of
as one list per batch."""
+
+ @contextlib.contextmanager
+ def _job(self, details, files, *, fail_after=None):
+ """Serve ``files`` through a real OpenAI client and report the batch
as ended with ``details``."""
+ served: dict[str, _Lines] = {}
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ file_id = request.url.path.split("/")[-2]
+ served[file_id] = _Lines(files[file_id], (fail_after or
{}).get(file_id))
+ return httpx2.Response(200, stream=served[file_id])
+
+ def build(_model_id):
+ client =
httpx2.AsyncClient(transport=httpx2.MockTransport(handler))
+ return OpenAIResponsesModel(
+ "gpt-5-mini", provider=OpenAIProvider(api_key="sk-test",
http_client=client)
+ )
+
+ handle = _submitted_on(
+ OpenAIBatchAdapter, build(None), model_name="gpt-5-mini",
provider_name="openai"
+ )
+ ended = dataclasses.replace(
+ TypeAdapter(Batch).validate_json(handle),
+ status="ended",
+ provider_details={"input_file_id": "file-in", **details},
+ )
+ adapter = OpenAIBatchAdapter(model_id=GPT, batch_handle=handle,
model_factory=build)
+ with mock.patch.object(OpenAIResponsesModel, "batch_status",
autospec=True, return_value=ended):
+ yield adapter, build(None), ended, served
+
+ @pytest.mark.parametrize("job", list(_OPENAI_JOBS), ids=list(_OPENAI_JOBS))
+ def test_the_streamed_rows_match_pydantic_ais_own_collection(self, job):
+ details, files = _OPENAI_JOBS[job]
+ with self._job(details, files) as (adapter, model, ended, _):
+ reference = asyncio.run(model.batch_results(ended))
+ parameters = adapter._output_parameters(model,
build_output_spec(str))
+ expected = [adapter._decode_one(model, result, parameters) for
result in reference]
+
+ with mock.patch.object(OpenAIResponsesModel, "batch_results",
autospec=True) as collect_all:
+ rows = list(adapter.iter_results("batch_1"))
+
+ collect_all.assert_not_called()
+ assert len(rows) == len(expected) > 0
+ assert sorted(map(_row_view, rows)) == sorted(map(_row_view, expected))
+
+ @pytest.mark.parametrize(
+ ("job", "stalls_on"),
+ [("completed", "file-out"), ("cancelled before any request ran",
"file-in")],
+ ids=["output file", "input file of the unrun requests"],
+ )
+ def
test_the_first_row_arrives_before_the_file_has_been_read_to_the_end(self, job,
stalls_on):
+ details, files = _OPENAI_JOBS[job]
+ with self._job(details, files, fail_after={stalls_on: 1}) as (adapter,
*_):
+ rows = adapter.iter_results("batch_1")
+ first = next(rows)
+
+ assert first.index == 0
+ with pytest.raises(RuntimeError, match="next line has not
arrived"):
+ next(rows)
+
+ def test_closing_early_stops_the_producer_and_the_download(self):
+ count = _RESULT_BUFFER * 4
+ details = {"status": "completed", "output_file_id": "file-out"}
+ files = {"file-out": [_openai_output(i) for i in range(count)]}
+ with self._job(details, files) as (adapter, _, _, served):
+ rows = adapter.iter_results("batch_1")
+ next(rows)
+ rows.close()
+
+ assert served["file-out"].closed
+ assert served["file-out"].pulled <= _RESULT_BUFFER + 3
+ assert not [t for t in threading.enumerate() if t.name ==
"llm-batch-results"]
+
+ def test_a_rate_limited_row_keeps_openais_code_and_message(self):
+ details, files = _OPENAI_JOBS["completed"]
+ with self._job(details, files) as (adapter, *_):
+ rows = {row.index: row for row in adapter.iter_results("batch_1")}
+
+ assert rows[1].provider_status == "errored"
+ assert rows[1].error["provider_code"] == "rate_limit_exceeded"
+ assert rows[1].error["message"] == "slow down"
+
+ def
test_a_request_the_error_file_reports_with_another_code_is_an_errored_row(self):
+ details = {"status": "completed", "error_file_id": "file-err"}
+ files = {"file-err": [_openai_error(0, "server_error")]}
+ with self._job(details, files) as (adapter, *_):
+ (row,) = adapter.iter_results("batch_1")
+
+ assert row.provider_status == "errored"
+ assert row.error["provider_code"] == "server_error"
+ assert row.error["message"] == "request 0: server_error"
+
+ def test_a_response_with_line_separators_inside_its_text_lands(self):
+ text = "one\u2028two\u0085three\x0bfour\x0cfive\x1csix"
+ details = {"status": "completed", "output_file_id": "file-out"}
+ files = {"file-out": [_openai_output(0, text=text), _openai_output(1)]}
+ with self._job(details, files) as (adapter, *_):
+ rows = sorted(adapter.iter_results("batch_1"), key=lambda row:
row.index)
+
+ assert [adapter.extract_output(row, build_output_spec(str)).text for
row in rows] == [
+ text,
+ "answer 1",
+ ]
+
+ def
test_a_blank_or_unparsable_line_is_skipped_with_a_warning_and_the_rest_land(self):
+ details = {"status": "completed", "output_file_id": "file-out"}
+ files = {"file-out": [_openai_output(0), "{not json", "",
_openai_output(3), '{"custom_id": 4}']}
+ with (
+ self._job(details, files) as (adapter, *_),
+ mock.patch.object(backend_module, "log",
spec=FilteringBoundLogger) as log,
+ ):
+ rows = list(adapter.iter_results("batch_1"))
+
+ assert sorted(row.index for row in rows) == [0, 3]
+ assert [
+ (call.kwargs["file_id"], call.kwargs["line_number"]) for call in
log.warning.call_args_list
+ ] == [("file-out", 2), ("file-out", 3), ("file-out", 5)]
+
+ def
test_an_unreadable_input_line_does_not_shift_the_line_numbers_of_the_ones_after_it(self):
+ details = {
+ "status": "failed",
+ "errors": [
+ {"code": "bad", "line": 1, "message": "first line problem"},
+ {"code": "bad", "line": 3, "message": "third line problem"},
+ ],
+ }
+ input_lines = _openai_input(3)
+ files = {"file-in": [input_lines[0], "{not json", input_lines[2]]}
+ with self._job(details, files) as (adapter, *_):
+ rows = sorted(adapter.iter_results("batch_1"), key=lambda row:
row.index)
+
+ assert [row.index for row in rows] == [0, 2]
+ assert "first line problem" in rows[0].error["message"]
+ assert "third line problem" not in rows[0].error["message"]
+ assert "third line problem" in rows[1].error["message"]
+ assert "first line problem" not in rows[1].error["message"]
+
+
+class TestErrorCode:
+ @pytest.mark.parametrize(
+ ("body", "kwargs", "code"),
+ [
+ (
+ {"message": "m", "type": "t", "code": "c"},
+ {"provider_error_code": "RESOURCE_EXHAUSTED"},
+ "RESOURCE_EXHAUSTED",
+ ),
+ ({"error": {"type": "overloaded_error"}}, {}, "overloaded_error"),
+ ({"message": "m", "code": "server_error"}, {}, "server_error"),
+ (None, {}, 503),
+ ],
+ ids=["the code pydantic-ai parsed", "type under error", "code of an
unwrapped body", "status"],
+ )
+ def test_the_providers_code_wins_over_the_status(self, body, kwargs, code):
+ assert _error_code(ModelHTTPError(503, "m", body, **kwargs)) == code
+
+
+class TestSplitLines:
+ @staticmethod
+ async def _chunks(*chunks: bytes):
+ for chunk in chunks:
+ yield chunk
+
+ def _split(self, *chunks: bytes) -> list[bytes]:
+ async def collect():
+ return [line async for line in _split_lines(self._chunks(*chunks))]
+
+ return asyncio.run(collect())
+
+ def test_lines_are_split_on_newlines_only(self):
+ assert self._split("a\u2028b\u0085c\r\nd\n".encode()) ==
["a\u2028b\u0085c\r".encode(), b"d"]
+
+ def
test_a_line_split_across_chunks_is_joined_even_inside_a_character(self):
+ euro = "\u20ac".encode()
+
+ assert self._split(b"ab", euro[:1], euro[1:] + b"\ncd", b"\n", b"ef")
== [
+ b"ab" + euro,
+ b"cd",
+ b"ef",
+ ]
+
+ def test_a_file_without_a_final_newline_keeps_its_last_line(self):
+ assert self._split(b"a\nb") == [b"a", b"b"]
+
+ def test_blank_lines_are_kept_for_the_caller_to_skip(self):
+ assert self._split(b"a\n\nb\n") == [b"a", b"", b"b"]
+
+
def _ended(state: str | None, *, status: BatchStatus = "ended", count: int =
2) -> Batch:
return Batch(
id="batches/1",
@@ -1298,3 +1634,338 @@ class TestAdapterRegistration:
asyncio.run(adapter._amodel("anthropic:claude-haiku-4-5"))
hook.aget_primary_model.assert_awaited_once_with("anthropic:claude-haiku-4-5")
+
+
+class TestOpenAIBatches:
+ """OpenAI batches run on the Responses model, so the requests are
Responses API bodies."""
+
+ def
test_requests_are_responses_bodies_with_the_settings_the_system_prompt_and_raw_fields(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT_4, model_factory=lambda _id:
_gpt("gpt-4.1-mini"))
+
+ (encoded,) = _real_encode(
+ adapter,
+ [{"prompt": "hi", "params": {"user": "u-1"}}],
+ system_prompt="be brief",
+ request_params={"temperature": 0.2},
+ )
+
+ body = json.loads(encoded.body)
+ assert encoded.custom_id == f"{KEY}-0"
+ assert body["model"] == "gpt-4.1-mini"
+ assert body["max_output_tokens"] == 256
+ assert body["temperature"] == 0.2
+ assert body["user"] == "u-1"
+ assert "be brief" in json.dumps(body["input"])
+
+ def
test_a_provider_prefixed_setting_reaches_the_request_in_its_typed_form(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ (encoded,) = _real_encode(
+ adapter, [{"prompt": "hi"}],
request_params={"openai_reasoning_effort": "low"}
+ )
+
+ assert json.loads(encoded.body)["reasoning"]["effort"] == "low"
+
+ def test_structured_output_sends_the_schema_natively(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ (encoded,) = _real_encode(adapter, [{"prompt": "hi"}],
spec=build_output_spec(Diagnosis))
+
+ fmt = json.loads(encoded.body)["text"]["format"]
+ assert fmt["type"] == "json_schema"
+ assert fmt["schema"]["properties"].keys() == {"label", "score"}
+
+ @pytest.mark.parametrize(
+ ("key", "value", "renamed"),
+ [
+ ("reasoning_effort", "low", "openai_reasoning_effort"),
+ ("verbosity", "low", "openai_text_verbosity"),
+ ("logprobs", True, "openai_logprobs"),
+ ],
+ )
+ @pytest.mark.parametrize("where", ["request_params", "request"])
+ def
test_a_chat_completions_parameter_fails_before_submission_with_its_responses_name(
+ self, key, value, renamed, where
+ ):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+ request: dict[str, Any] = {"prompt": "hi", "params": {"user": "u-1"}}
+ request_params: dict[str, Any] = {"temperature": 0.2}
+ (request["params"] if where == "request" else request_params)[key] =
value
+
+ with pytest.raises(LLMBatchInputError, match=f"{key!r} is a Chat
Completions parameter.*{renamed!r}"):
+ _real_encode(adapter, [request], request_params=request_params)
+
+ @pytest.mark.parametrize("key", ["seed", "top_k"])
+ def test_a_setting_the_responses_api_would_silently_drop_is_rejected(self,
key):
+ adapter = OpenAIBatchAdapter(model_id=GPT)
+
+ with pytest.raises(LLMBatchInputError, match=f"'{key}' is not
supported by OpenAIResponsesModel"):
+ adapter._build_settings(_gpt(), {key: 3}, max_tokens=8)
+
+ def
test_raw_fields_the_batch_sets_itself_cannot_replace_the_prompt_or_the_model(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ (encoded,) = _real_encode(
+ adapter,
+ [{"prompt": "hi"}],
+ request_params={"model": "evil", "input": "x", "extra_body":
{"model": "evil", "user": "u"}},
+ )
+
+ body = json.loads(encoded.body)
+ assert body["model"] == "gpt-5-mini"
+ assert body["input"] != "x"
+ assert body["user"] == "u"
+
+ def
test_models_do_not_share_a_group_so_a_mixed_batch_is_rejected_before_any_call(self):
+ models = {GPT: _gpt(), "openai:gpt-4.1-mini": _gpt("gpt-4.1-mini")}
+ adapter = OpenAIBatchAdapter(model_id=GPT,
model_factory=models.__getitem__)
+
+ with pytest.raises(LLMBatchModelMismatchError, match="Request 1 cannot
share a batch with request 0"):
+ _real_encode(adapter, [{"prompt": "a"}, {"prompt": "b", "model":
"openai:gpt-4.1-mini"}])
+
+ def test_a_per_request_model_from_another_provider_is_rejected(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ with pytest.raises(LLMBatchModelMismatchError, match="Request 0"):
+ _real_encode(adapter, [{"prompt": "a", "model": CLAUDE}])
+
+ @pytest.mark.parametrize("prefix", ["openai", "openai-chat"])
+ def test_the_model_is_always_built_as_a_responses_model(self, prefix):
+ hook = mock.create_autospec(PydanticAIHook, instance=True)
+ hook.aget_primary_model.return_value = _gpt()
+ adapter = OpenAIBatchAdapter(hook=hook,
model_id=f"{prefix}:gpt-5-mini")
+
+ asyncio.run(adapter._amodel(f"{prefix}:gpt-5-mini"))
+
+ hook.aget_primary_model.assert_awaited_once_with("openai:gpt-5-mini")
+
+ def
test_an_openai_responses_model_id_is_built_as_a_responses_model_by_the_connections_hook(self):
+ conn = Connection(conn_id="my_openai", conn_type="pydanticai",
password="sk-test")
+ with mock.patch.object(PydanticAIHook, "get_connection",
new=classmethod(lambda cls, conn_id: conn)):
+ hook = PydanticAIHook(llm_conn_id="my_openai")
+ adapter = OpenAIBatchAdapter(hook=hook,
model_id="openai-responses:gpt-5-mini")
+
+ model = asyncio.run(adapter._amodel("openai-responses:gpt-5-mini"))
+
+ assert isinstance(model, OpenAIResponsesModel)
+ assert model.model_name == "gpt-5-mini"
+
+ def
test_the_openai_chat_prefix_is_logged_when_validating_and_submitting_but_not_when_polling(self):
+ recorder = _Recorder()
+ chat_id = "openai-chat:gpt-5-mini"
+ spec = build_output_spec(str)
+ adapter = _adapter(recorder.model, cls=OpenAIBatchAdapter,
model_id=chat_id)
+
+ with mock.patch.object(backend_module, "log",
spec=FilteringBoundLogger) as log:
+ adapter.validate_requests(
+ [{"prompt": "a"}], model="gpt-5-mini", output_spec=spec,
idempotency_key=KEY
+ )
+ validated = log.info.call_count
+ submitted = _submit(adapter, [{"prompt": "a"}], spec=spec)
+ submit_logs = log.info.call_count - validated
+ log.info.reset_mock()
+ later = _adapter(
+ recorder.model, cls=OpenAIBatchAdapter, model_id=chat_id,
handle=submitted.handle
+ )
+ later.get_batch(submitted.batch_id)
+ list(later.iter_results(submitted.batch_id))
+ later.cancel_batch(submitted.batch_id)
+
+ assert (validated, submit_logs) == (1, 1)
+ log.info.assert_not_called()
+
+ def test_a_batch_recorded_without_a_handle_is_cancelled_by_its_id(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ with mock.patch.object(OpenAIAsyncBatches, "cancel", autospec=True) as
cancel:
+ adapter.cancel_batch("batch_old")
+
+ assert cancel.call_args.args[1] == "batch_old"
+
+ def
test_a_per_request_openai_chat_model_is_accepted_and_built_as_a_responses_model(self):
+ hook = mock.create_autospec(PydanticAIHook, instance=True)
+ hook.aget_primary_model.side_effect = lambda model_id:
_gpt(model_id.partition(":")[2])
+ adapter = OpenAIBatchAdapter(hook=hook, model_id=GPT)
+
+ encoded = _real_encode(adapter, [{"prompt": "a", "model":
"openai-chat:gpt-5-mini"}])
+
+ assert json.loads(encoded[0].body)["model"] == "gpt-5-mini"
+ hook.aget_primary_model.assert_awaited_once_with("openai:gpt-5-mini")
+
+ def test_the_lifecycle_runs_on_an_in_memory_model(self):
+ recorder = _Recorder()
+ adapter = _adapter(recorder.model, cls=OpenAIBatchAdapter,
model_id=GPT)
+
+ submitted = _submit(adapter, [{"prompt": "a"}, {"prompt": "b"}])
+ later = _adapter(recorder.model, cls=OpenAIBatchAdapter, model_id=GPT,
handle=submitted.handle)
+ rows = sorted(later.iter_results(submitted.batch_id), key=lambda item:
item.index)
+
+ assert later.get_batch(submitted.batch_id).status == "completed"
+ assert [later.extract_output(row, build_output_spec(str)).text for row
in rows] == [
+ "echo:a",
+ "echo:b",
+ ]
+
+ def
test_a_batch_an_earlier_version_submitted_to_chat_completions_is_not_re_attached(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+
+ with pytest.raises(LLMBatchStateReadError, match="batch_old.*Chat
Completions.*cancel it at OpenAI"):
+ adapter.get_batch("batch_old")
+
+ def
test_there_is_no_batch_to_find_after_a_crash_between_submit_and_record(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT)
+
+ assert adapter.find_orphaned_batch(KEY, "fp",
"2026-10-01T00:00:00+00:00") is None
+
+
+def _openai_batch(status: str, *, errors: list | None = None, state:
BatchStatus = "ended") -> Batch:
+ details: dict = {"status": status, "input_file_id": "file-in"}
+ if errors is not None:
+ details["errors"] = errors
+ return Batch(
+ id="batch_1",
+ model_name="gpt-5-mini",
+ provider_name="openai",
+ group="{}",
+ status=state,
+ created_at=datetime(2026, 10, 1, tzinfo=UTC),
+ request_count=3,
+ provider_details=details,
+ )
+
+
+class TestOpenAISubmit:
+ def
test_the_uploaded_input_file_is_recorded_under_the_id_pydantic_ai_returns(self):
+ adapter = OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
_gpt())
+ created = _openai_batch("validating", state="in_progress")
+
+ with mock.patch.object(OpenAIResponsesModel, "batch_create",
autospec=True, return_value=created):
+ result = adapter.submit(
+ [{"prompt": "a"}],
+ model="gpt-5-mini",
+ output_spec=build_output_spec(str),
+ idempotency_key=KEY,
+ input_fingerprint="fp",
+ )
+
+ assert result.provider_input_ref == "file-in"
+
+
+class TestOpenAIExistingBatches:
+ @pytest.fixture
+ def gpt5_batch(self):
+ """An OpenAI batch submitted on ``gpt-5``, polled by a task whose own
model is ``gpt-5-mini``."""
+ handle = _submitted_on(OpenAIBatchAdapter, _gpt("gpt-5"),
model_name="gpt-5", provider_name="openai")
+ return OpenAIBatchAdapter(
+ model_id=GPT,
+ batch_handle=handle,
+ model_factory=lambda model_id: _gpt(model_id.partition(":")[2]),
+ )
+
+ @pytest.fixture
+ def job(self):
+ created_at = int(datetime(2026, 10, 1, tzinfo=UTC).timestamp())
+ with mock.patch.object(
+ OpenAIAsyncBatches,
+ "retrieve",
+ autospec=True,
+ return_value=OpenAIBatch(
+ id="batches/1",
+ completion_window="24h",
+ created_at=created_at,
+ endpoint="/v1/responses",
+ input_file_id="file-in",
+ object="batch",
+ status="in_progress",
+ ),
+ ) as retrieve:
+ yield retrieve
+
+ def test_an_openai_batch_submitted_on_another_model_is_polled(self,
gpt5_batch, job):
+ assert gpt5_batch.get_batch("batches/1").status == "in_progress"
+
+ def test_an_openai_batch_submitted_on_another_model_is_cancelled(self,
gpt5_batch, job):
+ with mock.patch.object(
+ OpenAIAsyncBatches, "cancel", autospec=True,
return_value=job.return_value
+ ) as cancel:
+ gpt5_batch.cancel_batch("batches/1")
+
+ assert cancel.call_args.args[1] == "batches/1"
+
+ def
test_the_chat_completions_prefix_of_the_task_still_builds_the_responses_model(self):
+ recorder = _Recorder()
+ submitted = _submit(_adapter(recorder.model), [{"prompt": "a"}])
+ batch = TypeAdapter(Batch).validate_json(submitted.handle)
+ batch.model_name = "gpt-5"
+ asked: list[str] = []
+
+ def factory(model_id):
+ asked.append(model_id)
+ return recorder.model
+
+ adapter = OpenAIBatchAdapter(
+ model_id="openai-chat:gpt-5-mini",
+ batch_handle=TypeAdapter(Batch).dump_json(batch).decode(),
+ model_factory=factory,
+ )
+
+ adapter.get_batch(submitted.batch_id)
+
+ assert asked == ["openai:gpt-5"]
+
+
+class TestOpenAIJobStates:
+ @pytest.fixture
+ def adapter(self):
+ model = FunctionModel(lambda messages, info: ModelResponse(parts=[]))
+ return OpenAIBatchAdapter(model_id=GPT, model_factory=lambda _id:
model), model
+
+ @pytest.mark.parametrize(
+ ("job_status", "status"),
+ [("completed", "completed"), ("expired", "expired"), ("cancelled",
"cancelled")],
+ )
+ def test_an_ended_job_is_classified_by_its_own_status(self, adapter,
job_status, status):
+ adapter, model = adapter
+
+ state = asyncio.run(adapter._describe(model,
_openai_batch(job_status)))
+
+ assert (state.status, state.counts, state.error_message) == (status,
None, None)
+
+ def
test_a_job_rejected_before_running_is_failed_with_the_providers_reasons(self,
adapter):
+ adapter, model = adapter
+ errors = [
+ {"code": "invalid_json_line", "line": 2, "message": "bad line"},
+ {"code": "token_limit", "message": "too many tokens"},
+ ]
+
+ state = asyncio.run(adapter._describe(model, _openai_batch("failed",
errors=errors)))
+
+ assert state.status == "failed"
+ assert state.counts is None
+ assert "line 2: bad line" in state.error_message
+ assert "too many tokens" in state.error_message
+
+ def
test_a_rejection_reason_falls_back_to_the_code_and_then_to_unknown_error(self,
adapter):
+ adapter, model = adapter
+ errors = [{"code": "token_limit", "line": 4}, {"line": 5}, "not an
object"]
+
+ state = asyncio.run(adapter._describe(model, _openai_batch("failed",
errors=errors)))
+
+ assert state.error_message == (
+ "OpenAI batch batch_1 failed before processing. line 4:
token_limit; line 5: unknown error"
+ )
+
+ def test_a_rejected_job_without_reasons_still_says_it_failed(self,
adapter):
+ adapter, model = adapter
+
+ state = asyncio.run(adapter._describe(model, _openai_batch("failed")))
+
+ assert state.error_message == "OpenAI batch batch_1 failed before
processing."
+
+ @pytest.mark.parametrize("status", ["in_progress", "canceling"])
+ def test_a_job_that_has_not_ended_is_in_progress(self, adapter, status):
+ adapter, model = adapter
+
+ state = asyncio.run(adapter._describe(model,
_openai_batch("in_progress", state=status)))
+
+ assert state.status == "in_progress"
diff --git a/uv.lock b/uv.lock
index 0bd18397540..3f938c5eb0b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4981,7 +4981,7 @@ requires-dist = [
{ name = "llama-index-llms-openai", marker = "extra == 'llamaindex'",
specifier = ">=0.6.8" },
{ name = "mcp", marker = "extra == 'openai-codex'", specifier = ">=2.2.0"
},
{ name = "modal", marker = "extra == 'modal'", specifier = ">=1.5.2" },
- { name = "openai", marker = "extra == 'openai'", specifier = ">=2.47.0" },
+ { name = "openai", marker = "extra == 'openai'", specifier = ">=3.31.0" },
{ name = "openai-codex", marker = "extra == 'openai-codex'", specifier =
">=0.163.0" },
{ name = "opensandbox", marker = "extra == 'opensandbox'", specifier =
">=1.1.0" },
{ name = "openshell", marker = "extra == 'openshell'", specifier =
">=0.1.2,<0.2" },
@@ -4996,7 +4996,7 @@ requires-dist = [
{ name = "pydantic-ai-slim", extras = ["bedrock"], marker = "extra ==
'bedrock'", specifier = ">=2.46.0" },
{ name = "pydantic-ai-slim", extras = ["google"], marker = "extra ==
'google'", specifier = ">=2.66.0" },
{ name = "pydantic-ai-slim", extras = ["mcp"], marker = "extra == 'mcp'",
specifier = ">=2.46.0" },
- { name = "pydantic-ai-slim", extras = ["openai"], marker = "extra ==
'openai'", specifier = ">=2.46.0" },
+ { name = "pydantic-ai-slim", extras = ["openai"], marker = "extra ==
'openai'", specifier = ">=2.66.0" },
{ name = "pypdf", marker = "extra == 'pdf'", specifier = ">=4.0.0" },
{ name = "python-docx", marker = "extra == 'docx'", specifier = ">=1.1.2"
},
{ name = "sqlglot", marker = "extra == 'sql'", specifier = ">=30.0.0" },