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 3a75f6c496a Share error-detail and stream-close helpers across
common.ai adapters (#77681)
3a75f6c496a is described below
commit 3a75f6c496a54d722ea105f77df2f57c50b4a4ea
Author: Wei Lee <[email protected]>
AuthorDate: Sat Nov 28 08:05:02 2026 +0800
Share error-detail and stream-close helpers across common.ai adapters
(#77681)
The Claude Agent SDK and Codex adapters each kept their own copy of these
helpers, so a fix made in one adapter would not reach the other.
---
.../providers/common/ai/tools/_from_toolset.py | 24 ++++++++++++++++++++--
.../providers/common/ai/tools/claude_agent_sdk.py | 19 +++--------------
.../providers/common/ai/tools/openai_codex.py | 21 ++++---------------
.../unit/common/ai/tools/test_openai_codex.py | 2 +-
4 files changed, 30 insertions(+), 36 deletions(-)
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/tools/_from_toolset.py
b/providers/common/ai/src/airflow/providers/common/ai/tools/_from_toolset.py
index db9d1d562c2..cfa55354222 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/tools/_from_toolset.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/tools/_from_toolset.py
@@ -14,7 +14,11 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Expose a pydantic-ai toolset's tools as framework-neutral
:class:`AirflowTool` objects."""
+"""
+Expose a pydantic-ai toolset's tools as framework-neutral :class:`AirflowTool`
objects.
+
+Also hosts the helpers the framework adapters share.
+"""
from __future__ import annotations
@@ -46,7 +50,7 @@ from airflow.providers.common.ai.tools import AirflowTool,
ToolCallError, ToolRe
from airflow.providers.common.ai.utils.coroutines import run_coroutine_sync
if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable
+ from collections.abc import AsyncIterable, Awaitable, Callable
from pydantic_ai.toolsets.abstract import AbstractToolset, ToolsetTool
@@ -455,3 +459,19 @@ def _as_airflow_tool(
parameters=tool.tool_def.parameters_json_schema,
function=function,
)
+
+
+_MAX_ERROR_DETAIL_CHARS = 500
+
+
+def bound_detail(text: str) -> str:
+ omitted = len(text) - _MAX_ERROR_DETAIL_CHARS
+ return text if omitted <= 0 else
f"{text[:_MAX_ERROR_DETAIL_CHARS]}...(+{omitted} chars)"
+
+
+async def close_stream(stream: AsyncIterable[Any]) -> None:
+ # ``AsyncIterable`` does not guarantee ``aclose``; the streams the
adapters pass in (Claude's
+ # ``query()`` and ``receive_response()``, Codex's
``AsyncTurnHandle.stream()``) do.
+ aclose = getattr(stream, "aclose", None)
+ if aclose is not None:
+ await aclose()
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/tools/claude_agent_sdk.py
b/providers/common/ai/src/airflow/providers/common/ai/tools/claude_agent_sdk.py
index 63b5698aab6..3003457e5e9 100644
---
a/providers/common/ai/src/airflow/providers/common/ai/tools/claude_agent_sdk.py
+++
b/providers/common/ai/src/airflow/providers/common/ai/tools/claude_agent_sdk.py
@@ -43,7 +43,7 @@ import logging
from typing import TYPE_CHECKING, Any
from airflow.providers.common.ai.tools import AirflowTool, ToolCallError,
_collect_tools
-from airflow.providers.common.ai.tools._from_toolset import tool_call_scope
+from airflow.providers.common.ai.tools._from_toolset import bound_detail,
close_stream, tool_call_scope
from airflow.providers.common.ai.utils.tool_definition import serialize_for_llm
from airflow.providers.common.ai.utils.tool_metrics import calling_framework
@@ -62,7 +62,6 @@ _MCP_HINT = (
)
-_MAX_ERROR_DETAIL_CHARS = 500
_MAX_ERROR_ENTRIES = 5
# The bundled CLI clamps ``maxResultSizeChars`` to 500_000 (observed on CLI
2.1.286; other
# versions may differ), so a larger value is a no-op. With ``tools=[]`` the
model has no Read
@@ -99,11 +98,6 @@ def _truncate_result_text(text: str) -> str:
return units.decode("utf-16-le", errors="surrogatepass") + notice
-def _bound_detail(text: str) -> str:
- omitted = len(text) - _MAX_ERROR_DETAIL_CHARS
- return text if omitted <= 0 else
f"{text[:_MAX_ERROR_DETAIL_CHARS]}...(+{omitted} chars)"
-
-
def _describe_error_result(result: ResultMessage) -> str:
errors = result.errors or []
omitted_errors = len(errors) - _MAX_ERROR_ENTRIES
@@ -119,20 +113,13 @@ def _describe_error_result(result: ResultMessage) -> str:
for name, value in fields.items():
if not value:
continue
- text = _bound_detail(repr(value)) if name in ("result", "errors") else
repr(value)
+ text = bound_detail(repr(value)) if name in ("result", "errors") else
repr(value)
if name == "errors" and omitted_errors > 0:
text = f"{text} (+{omitted_errors} more)"
details.append(f"{name}={text}")
return f"The Claude Agent SDK run ended with an error result ({',
'.join(details)})."
-async def _close_stream(messages: AsyncIterable[Message]) -> None:
- # ``AsyncIterable`` does not guarantee ``aclose``; ``query()`` and
``receive_response()`` do.
- aclose = getattr(messages, "aclose", None)
- if aclose is not None:
- await aclose()
-
-
class _Run:
"""
One run of :meth:`AirflowTools.run`.
@@ -315,7 +302,7 @@ class AirflowTools:
return result
finally:
try:
- await _close_stream(messages)
+ await close_stream(messages)
except Exception as e:
if not raised:
raise
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/tools/openai_codex.py
b/providers/common/ai/src/airflow/providers/common/ai/tools/openai_codex.py
index 9bbe486cb39..95135cbf74b 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/tools/openai_codex.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/tools/openai_codex.py
@@ -57,12 +57,12 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from airflow.providers.common.ai.tools import AirflowTool, ToolCallError,
_collect_tools
-from airflow.providers.common.ai.tools._from_toolset import tool_call_scope
+from airflow.providers.common.ai.tools._from_toolset import bound_detail,
close_stream, tool_call_scope
from airflow.providers.common.ai.utils.tool_definition import serialize_for_llm
from airflow.providers.common.ai.utils.tool_metrics import calling_framework
if TYPE_CHECKING:
- from collections.abc import AsyncIterable, AsyncIterator, Awaitable,
Callable, Iterator, MutableMapping
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator,
MutableMapping
from mcp.server.context import ServerRequestContext
from openai_codex import AsyncTurnHandle
@@ -77,7 +77,6 @@ __all__ = ["AirflowTools"]
_MCP_HINT = "Add the server to Codex's mcp_servers config instead."
-_MAX_ERROR_DETAIL_CHARS = 500
# Every constant below was observed with openai-codex 0.163.0, not a
documented guarantee.
#
# The ceiling on a tool result this adapter lets through. It is our own
choice: unlike the Claude
@@ -125,11 +124,6 @@ def _truncate_result_text(text: str) -> str:
return text[: _MAX_INLINE_RESULT_CHARS - len(notice)] + notice
-def _bound_detail(text: str) -> str:
- omitted = len(text) - _MAX_ERROR_DETAIL_CHARS
- return text if omitted <= 0 else
f"{text[:_MAX_ERROR_DETAIL_CHARS]}...(+{omitted} chars)"
-
-
def _to_toml_string(value: str) -> str:
# A JSON string is a valid TOML basic string.
return json.dumps(value)
@@ -208,13 +202,6 @@ def _find_final_response(items: list[ThreadItem]) -> str |
None:
return last_unphased
-async def _close_stream(events: AsyncIterable[Any]) -> None:
- # ``AsyncIterable`` does not guarantee ``aclose``; the stream
``AsyncTurnHandle.stream()`` returns does.
- aclose = getattr(events, "aclose", None)
- if aclose is not None:
- await aclose()
-
-
class _Run:
"""
One run of :meth:`AirflowTools.run`.
@@ -522,7 +509,7 @@ class AirflowTools:
raise RuntimeError("The Codex turn stream ended without a
turn/completed notification.")
finished = completed.turn
if finished.status != TurnStatus.completed:
- detail = f": {_bound_detail(finished.error.message)}" if
finished.error else ""
+ detail = f": {bound_detail(finished.error.message)}" if
finished.error else ""
raise RuntimeError(f"The Codex turn ended with status
{finished.status.value}{detail}")
raised = False
return TurnResult(
@@ -546,7 +533,7 @@ class AirflowTools:
raise
finally:
try:
- await _close_stream(events)
+ await close_stream(events)
except Exception as e:
if not raised:
raise
diff --git
a/providers/common/ai/tests/unit/common/ai/tools/test_openai_codex.py
b/providers/common/ai/tests/unit/common/ai/tools/test_openai_codex.py
index 942d233e0db..3a90f6cd810 100644
--- a/providers/common/ai/tests/unit/common/ai/tools/test_openai_codex.py
+++ b/providers/common/ai/tests/unit/common/ai/tools/test_openai_codex.py
@@ -548,7 +548,7 @@ class TestRun:
mock_log.warning.assert_called_once()
@pytest.mark.asyncio
- @mock.patch(f"{MODULE}._close_stream", autospec=True)
+ @mock.patch(f"{MODULE}.close_stream", autospec=True)
async def test_cancelling_a_run_interrupts_the_turn_before_it_ends(self,
mock_close_stream, ok_tools):
gate = asyncio.Event()
order: list[Any] = []