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 e76ea94dbc9 Build OpenAI Agents SDK example clients with `OpenAIHook` 
(#77071)
e76ea94dbc9 is described below

commit e76ea94dbc9f274346d153e5347a795e70a54c11
Author: Kaxil Naik <[email protected]>
AuthorDate: Mon Nov 23 11:41:52 2026 +0000

    Build OpenAI Agents SDK example clients with `OpenAIHook` (#77071)
    
    The common.ai OpenAI Agents SDK examples built AsyncOpenAI from the
    connection's password and host by hand, so a connection's
    openai_client_kwargs and workload identity were ignored. The examples now
    run as async tasks and get the client from OpenAIHook.aget_conn(), and the
    guide lists apache-airflow-providers-openai>=2.2.0 in its install command.
---
 .../common/ai/docs/frameworks/openai_agents.rst    | 92 ++++++++++++++--------
 .../ai/example_dags/example_openai_agents_agent.py | 47 +++++------
 .../example_dags/example_openai_agents_approval.py | 46 ++++++-----
 .../example_openai_agents_data_access.py           | 45 ++++++-----
 .../example_dags/example_openai_agents_durable.py  | 52 ++++++------
 5 files changed, 155 insertions(+), 127 deletions(-)

diff --git a/providers/common/ai/docs/frameworks/openai_agents.rst 
b/providers/common/ai/docs/frameworks/openai_agents.rst
index 795fd75b790..9a73debf223 100644
--- a/providers/common/ai/docs/frameworks/openai_agents.rst
+++ b/providers/common/ai/docs/frameworks/openai_agents.rst
@@ -27,7 +27,8 @@ through connections your deployment already manages. The 
agent, its runner, hand
 guardrails and your own function tools stay plain OpenAI Agents SDK. Airflow 
adds these,
 each of which you can use without the others:
 
-- :func:`~airflow.providers.common.ai.durable.openai_agents.run_durably_sync` 
runs the
+- :func:`~airflow.providers.common.ai.durable.openai_agents.run_durably` and
+  :func:`~airflow.providers.common.ai.durable.openai_agents.run_durably_sync` 
run the
   agent so that a task retry replays the model and tool calls the failed try 
completed,
   instead of paying for them again.
 - :class:`~airflow.providers.common.ai.tools.openai_agents.AirflowTools` gives 
the agent
@@ -53,12 +54,14 @@ switched on with one argument. See 
:ref:`howto/operator:agent`.
 Installation
 ------------
 
-Install the provider with the ``sql`` extra, which the examples' SQL toolset 
needs, and
-the SDK:
+Install the provider with the ``sql`` extra, which the examples' SQL toolset 
needs, the
+SDK, and the OpenAI provider, whose hook builds the SDK's client from an 
Airflow
+connection:
 
 .. code-block:: bash
 
-    pip install "apache-airflow-providers-common-ai[sql]>=1.0.0" 
"openai-agents>=0.20.0"
+    pip install "apache-airflow-providers-common-ai[sql]>=1.0.0" 
"openai-agents>=0.20.0" \
+        "apache-airflow-providers-openai>=2.2.0"
 
 ``openai-agents`` 0.21 and later require ``openai`` 3. Where ``openai`` is 
held below 3,
 the resolver picks ``openai-agents`` 0.20, the last release that accepts 
``openai`` 2.
@@ -115,18 +118,42 @@ Run the agent in a task
 -----------------------
 
 In a Dag, build the agent inside the ``@task`` function, so connections are 
read when
-the task runs rather than when the Dag file is parsed. Here the model's API 
key, and
-optionally the base URL of another OpenAI-compatible endpoint such as a 
gateway or a
-self-hosted server, come from an Airflow connection too:
+the task runs rather than when the Dag file is parsed. Here the model's client 
comes
+from an Airflow connection too:
+:meth:`~airflow.providers.openai.hooks.openai.OpenAIHook.aget_conn` returns an
+``AsyncOpenAI`` built from it, which is what the SDK's models take:
 
 .. exampleinclude:: 
/../../ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_agent.py
     :language: python
     :start-after: [START example_openai_agents_agent]
     :end-before: [END example_openai_agents_agent]
 
-The example reads two connections: ``openai_default``, whose password is the 
API key and
-whose host, if set, is the base URL, and ``sql_default``, a database 
connection. Set the
-``LLM_CONN_ID`` and ``DB_CONN_ID`` environment variables to use others.
+The example reads two connections: ``openai_default``, an OpenAI connection, 
and
+``sql_default``, a database connection. Set the ``LLM_CONN_ID`` and 
``DB_CONN_ID``
+environment variables to use others. The OpenAI connection's password is the 
API key and
+its host, if set, is the base URL of another OpenAI-compatible endpoint, such 
as a
+gateway or a self-hosted server. Because the hook builds the client, the 
connection's
+other settings apply too: ``openai_client_kwargs`` in its extra (such as 
``timeout``,
+``organization`` or ``default_headers``), and workload identity instead of an 
API key.
+See :doc:`apache-airflow-providers-openai:connections`.
+
+The task is ``async`` because ``aget_conn`` is a coroutine, and async tasks 
need Airflow
+3.2.1 or later. On an earlier Airflow, use a sync task: build the client from 
the
+connection's key and host, pass it to the model as above, and run the agent 
with
+``Runner.run_sync``. The connection's other settings don't apply then:
+
+.. code-block:: python
+
+    from openai import AsyncOpenAI
+
+    from airflow.providers.common.compat.sdk import BaseHook
+
+    conn = BaseHook.get_connection(LLM_CONN_ID)
+    client = AsyncOpenAI(api_key=conn.password, base_url=conn.host or None)
+
+The OpenAI provider's next release after 2.2.0 adds
+``OpenAIHook(LLM_CONN_ID).get_conn(async_client=True)``, which builds the same 
client as
+``aget_conn`` from sync code, the connection's other settings included.
 
 The example uses ``OpenAIChatCompletionsModel``, so the connection's host can 
point at
 a server that implements only the Chat Completions API. Against OpenAI itself,
@@ -536,13 +563,14 @@ Durable execution
 
 When a task that calls ``Runner.run`` fails and Airflow retries it, the agent 
starts
 again from the prompt: every model call is paid for again, and every tool call 
happens
-again. On a task with ``retries``, run the agent with ``run_durably_sync``, or
-:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably` from 
async code,
-instead. They take the same arguments as ``Runner.run_sync`` and 
``Runner.run``, except
-``previous_response_id``, ``conversation_id`` and 
``auto_previous_response_id``, which
-they refuse with ``ValueError`` inside a task: with them OpenAI keeps the 
conversation,
-and a replayed call never reaches it. This Dag runs the agent from the task 
example
-with ``run_durably_sync``:
+again. On a task with ``retries``, run the agent with
+:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably`, or
+``run_durably_sync`` from sync code, instead. They take the same arguments as
+``Runner.run`` and ``Runner.run_sync``, except ``previous_response_id``,
+``conversation_id`` and ``auto_previous_response_id``, which they refuse with
+``ValueError`` inside a task: with them OpenAI keeps the conversation, and a 
replayed
+call never reaches it. This Dag runs the agent from the task example with
+``run_durably``:
 
 .. exampleinclude:: 
/../../ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_durable.py
     :language: python
@@ -558,21 +586,23 @@ Outside a task there is nothing to replay into, and the 
agent runs as ``Runner.r
 it.
 
 What was recorded is deleted when the agent's run succeeds, so clearing the 
task later
-starts over. That happens when ``run_durably_sync`` returns, not when the task
-succeeds: if the task fails after the agent has answered, for example while 
writing the
-answer somewhere, the retry runs the whole agent again. Write the answer in a
-downstream task, so that a failed write retries on its own. Here 
``build_agent()``
-stands for building the agent as the task example does:
+starts over. That happens when ``run_durably`` or ``run_durably_sync`` 
returns, not when
+the task succeeds: if the task fails after the agent has answered, for example 
while
+writing the answer somewhere, the retry runs the whole agent again. Write the 
answer in a
+downstream task, so that a failed write retries on its own. Here 
``build_agent(client)``
+stands for building the agent on the client as the task example does:
 
 .. code-block:: python
 
-    from airflow.providers.common.ai.durable.openai_agents import 
run_durably_sync
+    from airflow.providers.common.ai.durable.openai_agents import run_durably
+    from airflow.providers.openai.hooks.openai import OpenAIHook
     from airflow.sdk import ObjectStoragePath, task
 
 
     @task(retries=2)
-    def answer(question: str) -> str:
-        return run_durably_sync(build_agent(), question).final_output
+    async def answer(question: str) -> str:
+        async with await OpenAIHook(LLM_CONN_ID).aget_conn() as client:
+            return (await run_durably(build_agent(client), 
question)).final_output
 
 
     @task(retries=5)
@@ -652,10 +682,10 @@ Have a person approve tool calls
 
 A refund, a deployment or an email to a customer shouldn't happen only because 
a model
 asked for it. Set ``needs_approval=True`` on the function tool and run the 
agent with
-``run_durably_sync``: each call to that tool waits in Required Actions until a 
person
-approves or rejects it. To have a person review the agent's answer rather than 
its tool
-calls, use ``AgentOperator(enable_hitl_review=True)``, or add the standard 
provider's
-``ApprovalOperator`` as the next task.
+``run_durably``, or ``run_durably_sync`` in a sync task: each call to that 
tool waits in
+Required Actions until a person approves or rejects it. To have a person 
review the
+agent's answer rather than its tool calls, use 
``AgentOperator(enable_hitl_review=True)``,
+or add the standard provider's ``ApprovalOperator`` as the next task.
 
 .. exampleinclude:: 
/../../ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_approval.py
     :language: python
@@ -668,7 +698,7 @@ state without holding a worker slot, and Required Actions 
shows a request titled
 tool's description, and lists the call's arguments after Airflow's secret 
masker has
 masked them. The reviewer chooses **Approve** or **Reject**, and can fill in a 
reason.
 
-The answer resumes the task, which runs from the top again. 
``run_durably_sync`` replays
+The answer resumes the task, which runs from the top again. ``run_durably`` 
replays
 the calls it recorded before the pause instead of making them again (the calls 
in "What
 always runs live" above still run live), and then:
 
@@ -682,7 +712,7 @@ Things to know:
   :func:`~airflow.providers.standard.operators.hitl.request_input`, and a 
``@task`` or
   ``PythonOperator``. Elsewhere the task fails with 
``UnsupportedToolDeferralError``
   instead, without retrying.
-- Code in the task before ``run_durably_sync`` runs again every time the task 
resumes. So
+- Code in the task before ``run_durably`` runs again every time the task 
resumes. So
   does an earlier agent run in the same task, since what it recorded is 
deleted when it
   finishes: run an agent whose tools need approval in a task of its own.
 - If a step before the paused call returns something different when the task 
resumes (a
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_agent.py
 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_agent.py
index 25a573990b7..62c7a2fcd38 100644
--- 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_agent.py
+++ 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_agent.py
@@ -18,7 +18,7 @@
 Run an OpenAI Agents SDK agent in an Airflow task, with Airflow's SQL toolset 
as its tools.
 
 The agent is plain OpenAI Agents SDK: you build the model, the ``Agent`` and 
the run
-yourself. Airflow supplies three things. The model's API key comes from an 
Airflow
+yourself. Airflow supplies three things. The model's client comes from an 
Airflow
 connection; 
:class:`~airflow.providers.common.ai.tools.openai_agents.AirflowTools`
 gives the agent a ``SQLToolset``'s tools, with read-only SQL validation and 
bounded
 results, and with Airflow's secret masker applied to every tool result; and
@@ -27,19 +27,22 @@ the SDK's traces as the task's OpenTelemetry spans instead 
of sending them to Op
 
 Before running:
 
-1. Install the SDK: ``pip install "openai-agents>=0.20.0"``.
-2. Create a connection (``LLM_CONN_ID``, default ``openai_default``) whose 
password is
-   an OpenAI API key. Set its host to the base URL of any other 
OpenAI-compatible
-   endpoint, such as a gateway or a self-hosted server.
+1. Install the SDK and the OpenAI provider:
+   ``pip install "openai-agents>=0.20.0" 
"apache-airflow-providers-openai>=2.2.0"``.
+2. Create an OpenAI connection (``LLM_CONN_ID``, default ``openai_default``) 
whose
+   password is an OpenAI API key. Set its host to the base URL of any other
+   OpenAI-compatible endpoint, such as a gateway or a self-hosted server.
 3. Create a database connection (``DB_CONN_ID``, default ``sql_default``) whose
    hook is a ``DbApiHook`` (e.g. SQLite, Postgres, MySQL).
+4. Use Airflow 3.2.1 or later: the task is ``async``. On an earlier Airflow, 
see
+   the OpenAI Agents SDK guide's fallback for a sync task.
 """
 
 from __future__ import annotations
 
 import os
 
-from airflow.providers.common.compat.sdk import BaseHook, dag, task
+from airflow.providers.common.compat.sdk import dag, task
 
 LLM_CONN_ID = os.environ.get("LLM_CONN_ID", "openai_default")
 LLM_MODEL = os.environ.get("LLM_MODEL", "gpt-5.6-luna")
@@ -54,32 +57,30 @@ def example_openai_agents_agent():
     """Answer a question about a database with an OpenAI Agents SDK agent."""
 
     @task
-    def run_openai_agent(question: str = DEFAULT_QUESTION) -> str:
+    async def run_openai_agent(question: str = DEFAULT_QUESTION) -> str:
         from agents import Agent, OpenAIChatCompletionsModel, Runner, 
set_trace_processors
-        from openai import AsyncOpenAI
 
         from airflow.providers.common.ai.tools.openai_agents import 
AirflowTools, AirflowTraceProcessor
         from airflow.providers.common.ai.tools.tracing import 
agent_framework_tracing
         from airflow.providers.common.ai.toolsets.sql import SQLToolset
+        from airflow.providers.openai.hooks.openai import OpenAIHook
 
         # Record the SDK's traces as the task's OpenTelemetry spans instead of 
sending them to OpenAI.
         set_trace_processors([AirflowTraceProcessor()])
 
-        llm = BaseHook.get_connection(LLM_CONN_ID)
-        agent = Agent(
-            name="analyst",
-            model=OpenAIChatCompletionsModel(
-                model=LLM_MODEL,
-                openai_client=AsyncOpenAI(api_key=llm.password, 
base_url=llm.host or None),
-            ),
-            instructions=(
-                "You are a SQL analyst. Use list_tables and get_schema to 
explore "
-                "the database, then run read-only queries to answer the 
question."
-            ),
-            tools=AirflowTools(SQLToolset(db_conn_id=DB_CONN_ID)),
-        )
-        with agent_framework_tracing():
-            return Runner.run_sync(agent, question).final_output
+        async with await OpenAIHook(LLM_CONN_ID).aget_conn() as client:
+            agent = Agent(
+                name="analyst",
+                model=OpenAIChatCompletionsModel(model=LLM_MODEL, 
openai_client=client),
+                instructions=(
+                    "You are a SQL analyst. Use list_tables and get_schema to 
explore "
+                    "the database, then run read-only queries to answer the 
question."
+                ),
+                tools=AirflowTools(SQLToolset(db_conn_id=DB_CONN_ID)),
+            )
+            with agent_framework_tracing():
+                result = await Runner.run(agent, question)
+        return result.final_output
 
     run_openai_agent()
 
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_approval.py
 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_approval.py
index a6c2776d9eb..92a3d0aef78 100644
--- 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_approval.py
+++ 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_approval.py
@@ -18,15 +18,16 @@
 Have a person approve each refund an OpenAI Agents SDK support agent wants to 
issue.
 
 The agent looks orders up on its own, but ``issue_refund`` sets 
``needs_approval=True``, so
-:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably_sync` 
pauses the task
+:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably` pauses 
the task
 in Required Actions for every refund and resumes it with the reviewer's answer.
 
 Before running:
 
-1. Install the SDK: ``pip install "openai-agents>=0.20.0"``.
-2. Create a connection (``LLM_CONN_ID``, default ``openai_default``) whose 
password is
-   an OpenAI API key. Set its host to the base URL of any other 
OpenAI-compatible
-   endpoint, such as a gateway or a self-hosted server.
+1. Install the SDK and the OpenAI provider:
+   ``pip install "openai-agents>=0.20.0" 
"apache-airflow-providers-openai>=2.2.0"``.
+2. Create an OpenAI connection (``LLM_CONN_ID``, default ``openai_default``) 
whose
+   password is an OpenAI API key. Set its host to the base URL of any other
+   OpenAI-compatible endpoint, such as a gateway or a self-hosted server.
 3. Use Airflow 3.4 or later, with a standard provider that has
    :func:`~airflow.providers.standard.operators.hitl.request_input`.
 """
@@ -35,7 +36,7 @@ from __future__ import annotations
 
 import os
 
-from airflow.providers.common.compat.sdk import BaseHook, dag, task
+from airflow.providers.common.compat.sdk import dag, task
 
 LLM_CONN_ID = os.environ.get("LLM_CONN_ID", "openai_default")
 LLM_MODEL = os.environ.get("LLM_MODEL", "gpt-5.6-luna")
@@ -53,12 +54,12 @@ def example_openai_agents_approval():
     """Resolve a support ticket with an agent whose refunds a person approves 
in Required Actions."""
 
     @task
-    def handle_ticket(ticket: str = DEFAULT_TICKET) -> str:
+    async def handle_ticket(ticket: str = DEFAULT_TICKET) -> str:
         # The SDK is an optional dependency, so it is imported when the task 
runs, not at parse time.
         from agents import Agent, OpenAIChatCompletionsModel, RunConfig, 
function_tool
-        from openai import AsyncOpenAI
 
-        from airflow.providers.common.ai.durable.openai_agents import 
run_durably_sync
+        from airflow.providers.common.ai.durable.openai_agents import 
run_durably
+        from airflow.providers.openai.hooks.openai import OpenAIHook
 
         @function_tool
         def get_order(order_id: str) -> dict:
@@ -70,21 +71,18 @@ def example_openai_agents_approval():
             """Refund part or all of an order."""
             return f"Refunded {amount:.2f} on {order_id}"
 
-        llm = BaseHook.get_connection(LLM_CONN_ID)
-        agent = Agent(
-            name="support",
-            model=OpenAIChatCompletionsModel(
-                model=LLM_MODEL,
-                openai_client=AsyncOpenAI(api_key=llm.password, 
base_url=llm.host or None),
-            ),
-            instructions=(
-                "You resolve support tickets. Check each order with get_order, 
then refund "
-                "only what the order supports with issue_refund, one call per 
order."
-            ),
-            tools=[get_order, issue_refund],
-        )
-        # The SDK sends traces to OpenAI by default; see the guide's tracing 
section.
-        result = run_durably_sync(agent, ticket, 
run_config=RunConfig(tracing_disabled=True))
+        async with await OpenAIHook(LLM_CONN_ID).aget_conn() as client:
+            agent = Agent(
+                name="support",
+                model=OpenAIChatCompletionsModel(model=LLM_MODEL, 
openai_client=client),
+                instructions=(
+                    "You resolve support tickets. Check each order with 
get_order, then refund "
+                    "only what the order supports with issue_refund, one call 
per order."
+                ),
+                tools=[get_order, issue_refund],
+            )
+            # The SDK sends traces to OpenAI by default; see the guide's 
tracing section.
+            result = await run_durably(agent, ticket, 
run_config=RunConfig(tracing_disabled=True))
         return result.final_output
 
     handle_ticket()
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_data_access.py
 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_data_access.py
index dd71915dd6c..74927d08462 100644
--- 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_data_access.py
+++ 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_data_access.py
@@ -25,21 +25,23 @@ agent as function tools.
 
 Before running:
 
-1. Install the SDK and the provider the bucket needs:
-   ``pip install "openai-agents>=0.20.0" 
"apache-airflow-providers-amazon[s3fs]"``.
-2. Create a connection (``LLM_CONN_ID``, default ``openai_default``) whose 
password is
-   an OpenAI API key. Set its host to the base URL of any other 
OpenAI-compatible
-   endpoint, such as a gateway or a self-hosted server.
+1. Install the SDK, the OpenAI provider and the provider the bucket needs:
+   ``pip install "openai-agents>=0.20.0" 
"apache-airflow-providers-openai>=2.2.0" 
"apache-airflow-providers-amazon[s3fs]"``.
+2. Create an OpenAI connection (``LLM_CONN_ID``, default ``openai_default``) 
whose
+   password is an OpenAI API key. Set its host to the base URL of any other
+   OpenAI-compatible endpoint, such as a gateway or a self-hosted server.
 3. Create the two data connections: ``warehouse_agent_reader`` (a ``DbApiHook``
    database, such as Postgres) and ``aws_reports_reader`` (AWS). Give each 
credentials
    that can read only what the agent needs.
+4. Use Airflow 3.2.1 or later: the task is ``async``. On an earlier Airflow, 
see
+   the OpenAI Agents SDK guide's fallback for a sync task.
 """
 
 from __future__ import annotations
 
 import os
 
-from airflow.providers.common.compat.sdk import BaseHook, dag, task
+from airflow.providers.common.compat.sdk import dag, task
 
 LLM_CONN_ID = os.environ.get("LLM_CONN_ID", "openai_default")
 LLM_MODEL = os.environ.get("LLM_MODEL", "gpt-5.6-luna")
@@ -53,13 +55,13 @@ def example_openai_agents_data_access():
     """Answer a revenue question from the warehouse and the finance reports."""
 
     @task
-    def explain_revenue(question: str = DEFAULT_QUESTION) -> str:
+    async def explain_revenue(question: str = DEFAULT_QUESTION) -> str:
         # The SDK is an optional dependency, so it is imported when the task 
runs, not at parse time.
         from agents import Agent, OpenAIChatCompletionsModel, RunConfig, Runner
-        from openai import AsyncOpenAI
 
         from airflow.providers.common.ai.tools.openai_agents import 
AirflowTools
         from airflow.providers.common.ai.toolsets import ObjectStorageToolset, 
SQLToolset
+        from airflow.providers.openai.hooks.openai import OpenAIHook
 
         warehouse = SQLToolset(
             # A role granted SELECT on these two tables only.
@@ -75,21 +77,18 @@ def example_openai_agents_data_access():
             max_read_bytes=1024 * 1024,
         )
 
-        llm = BaseHook.get_connection(LLM_CONN_ID)
-        agent = Agent(
-            name="revenue_analyst",
-            model=OpenAIChatCompletionsModel(
-                model=LLM_MODEL,
-                openai_client=AsyncOpenAI(api_key=llm.password, 
base_url=llm.host or None),
-            ),
-            instructions=(
-                "Answer revenue questions. Query the warehouse for the 
numbers, and read "
-                "the finance reports for context."
-            ),
-            tools=AirflowTools(warehouse, reports),
-        )
-        # The SDK sends traces to OpenAI by default; see the guide's tracing 
section.
-        result = Runner.run_sync(agent, question, 
run_config=RunConfig(tracing_disabled=True))
+        async with await OpenAIHook(LLM_CONN_ID).aget_conn() as client:
+            agent = Agent(
+                name="revenue_analyst",
+                model=OpenAIChatCompletionsModel(model=LLM_MODEL, 
openai_client=client),
+                instructions=(
+                    "Answer revenue questions. Query the warehouse for the 
numbers, and read "
+                    "the finance reports for context."
+                ),
+                tools=AirflowTools(warehouse, reports),
+            )
+            # The SDK sends traces to OpenAI by default; see the guide's 
tracing section.
+            result = await Runner.run(agent, question, 
run_config=RunConfig(tracing_disabled=True))
         return result.final_output
 
     explain_revenue()
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_durable.py
 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_durable.py
index ca27e8da8ab..5e3c1895251 100644
--- 
a/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_durable.py
+++ 
b/providers/common/ai/src/airflow/providers/common/ai/example_dags/example_openai_agents_durable.py
@@ -17,23 +17,26 @@
 """
 Run an OpenAI Agents SDK agent whose completed model and tool calls a task 
retry replays.
 
-The agent is the one in ``example_openai_agents_agent``: a model whose API key 
comes from
+The agent is the one in ``example_openai_agents_agent``: a model whose client 
comes from
 an Airflow connection, and a ``SQLToolset``'s tools through
 :class:`~airflow.providers.common.ai.tools.openai_agents.AirflowTools`.
-:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably_sync` 
runs it, so
+:func:`~airflow.providers.common.ai.durable.openai_agents.run_durably` runs 
it, so
 when the task fails and Airflow retries it, the calls the failed try completed 
return
 what they returned then instead of running again.
 
 Before running:
 
-1. Install the SDK: ``pip install "openai-agents>=0.20.0"``.
-2. Create a connection (``LLM_CONN_ID``, default ``openai_default``) whose 
password is
-   an OpenAI API key. Set its host to the base URL of any other 
OpenAI-compatible
-   endpoint, such as a gateway or a self-hosted server.
+1. Install the SDK and the OpenAI provider:
+   ``pip install "openai-agents>=0.20.0" 
"apache-airflow-providers-openai>=2.2.0"``.
+2. Create an OpenAI connection (``LLM_CONN_ID``, default ``openai_default``) 
whose
+   password is an OpenAI API key. Set its host to the base URL of any other
+   OpenAI-compatible endpoint, such as a gateway or a self-hosted server.
 3. Create a database connection (``DB_CONN_ID``, default ``sql_default``) whose
    hook is a ``DbApiHook`` (e.g. SQLite, Postgres, MySQL).
 4. On Airflow before 3.3, set ``[common.ai] durable_cache_path`` to where the 
journal
    is kept; from 3.3 on it is kept in the task state store.
+5. Use Airflow 3.2.1 or later: the task is ``async``. On an earlier Airflow, 
see
+   the OpenAI Agents SDK guide's fallback for a sync task.
 """
 
 from __future__ import annotations
@@ -41,7 +44,7 @@ from __future__ import annotations
 import os
 from datetime import timedelta
 
-from airflow.providers.common.compat.sdk import BaseHook, dag, task
+from airflow.providers.common.compat.sdk import dag, task
 
 LLM_CONN_ID = os.environ.get("LLM_CONN_ID", "openai_default")
 LLM_MODEL = os.environ.get("LLM_MODEL", "gpt-5.6-luna")
@@ -56,29 +59,26 @@ def example_openai_agents_durable():
     """Answer a question about a database with an OpenAI Agents SDK agent that 
survives task retries."""
 
     @task(retries=2, retry_delay=timedelta(minutes=1))
-    def run_durable_openai_agent(question: str = DEFAULT_QUESTION) -> str:
+    async def run_durable_openai_agent(question: str = DEFAULT_QUESTION) -> 
str:
         from agents import Agent, OpenAIChatCompletionsModel, RunConfig
-        from openai import AsyncOpenAI
 
-        from airflow.providers.common.ai.durable.openai_agents import 
run_durably_sync
+        from airflow.providers.common.ai.durable.openai_agents import 
run_durably
         from airflow.providers.common.ai.tools.openai_agents import 
AirflowTools
         from airflow.providers.common.ai.toolsets.sql import SQLToolset
-
-        llm = BaseHook.get_connection(LLM_CONN_ID)
-        agent = Agent(
-            name="analyst",
-            model=OpenAIChatCompletionsModel(
-                model=LLM_MODEL,
-                openai_client=AsyncOpenAI(api_key=llm.password, 
base_url=llm.host or None),
-            ),
-            instructions=(
-                "You are a SQL analyst. Use list_tables and get_schema to 
explore "
-                "the database, then run read-only queries to answer the 
question."
-            ),
-            tools=AirflowTools(SQLToolset(db_conn_id=DB_CONN_ID)),
-        )
-        # The SDK sends traces to OpenAI by default; see the guide's tracing 
section.
-        result = run_durably_sync(agent, question, 
run_config=RunConfig(tracing_disabled=True))
+        from airflow.providers.openai.hooks.openai import OpenAIHook
+
+        async with await OpenAIHook(LLM_CONN_ID).aget_conn() as client:
+            agent = Agent(
+                name="analyst",
+                model=OpenAIChatCompletionsModel(model=LLM_MODEL, 
openai_client=client),
+                instructions=(
+                    "You are a SQL analyst. Use list_tables and get_schema to 
explore "
+                    "the database, then run read-only queries to answer the 
question."
+                ),
+                tools=AirflowTools(SQLToolset(db_conn_id=DB_CONN_ID)),
+            )
+            # The SDK sends traces to OpenAI by default; see the guide's 
tracing section.
+            result = await run_durably(agent, question, 
run_config=RunConfig(tracing_disabled=True))
         return result.final_output
 
     run_durable_openai_agent()

Reply via email to