Skip to content

Commit 2bbc2c4

Browse files
committed
Refactor event loop management: move ensure_event_loop to its own module and clean up imports in hello_world and function_app
1 parent 96e5f66 commit 2bbc2c4

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed

samples-v2/openai_agents/basic/hello_world.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
1-
import asyncio
2-
31
from agents import Agent, Runner
4-
5-
# Ensure event loop is created
6-
try:
7-
asyncio.get_running_loop()
8-
except RuntimeError:
9-
loop = asyncio.new_event_loop()
10-
asyncio.set_event_loop(loop)
2+
import event_loop
113

124
def main():
135
agent = Agent(
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import asyncio
2+
3+
4+
def ensure_event_loop():
5+
"""
6+
Ensure an event loop is available for sync execution context.
7+
8+
This is necessary when calling Runner.run_sync from Azure Functions
9+
Durable orchestrators, which run in a synchronous context but need
10+
an event loop for internal async operations.
11+
"""
12+
try:
13+
asyncio.get_running_loop()
14+
except RuntimeError:
15+
loop = asyncio.new_event_loop()
16+
asyncio.set_event_loop(loop)

samples-v2/openai_agents/function_app.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from yield_exception import YieldException
66
from activity_call_tracker import ActivityCallTracker
77
from model_invoker import ModelInvoker, ActivityModelInput
8+
import event_loop
9+
810

911
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
1012

@@ -19,6 +21,7 @@ async def orchestration_starter(req: func.HttpRequest, client):
1921

2022
@app.orchestration_trigger(context_name="context")
2123
def basic_hello_world_orchestrator(context):
24+
event_loop.ensure_event_loop()
2225
activity_call_tracker = ActivityCallTracker(context)
2326
durable_openai_runner = DurableOpenAIRunner(activity_call_tracker=activity_call_tracker)
2427
set_default_agent_runner(durable_openai_runner)

0 commit comments

Comments
 (0)