Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions packages/genkit-flask/src/genkit_flask/_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,6 @@ def _parse_request_json() -> object:
T = TypeVar('T')


def _create_loop() -> AbstractEventLoop:
"""Creates a new asyncio event loop or returns the current one."""
try:
return asyncio.get_event_loop()
except Exception:
return asyncio.new_event_loop()


def _iter_over_async(ait: AsyncIterable[T], loop: AbstractEventLoop) -> Generator[T, None, None]:
"""Synchronously iterates over an AsyncIterable using a specified event loop."""
ait_iter = ait.__aiter__()
Expand Down Expand Up @@ -156,7 +148,6 @@ async def say_hi(name: str, ctx: FlowContext) -> str:
```

"""
loop = _create_loop()

def decorator(flow: Action) -> Callable[..., Awaitable[Response]]:
if not isinstance(flow, Action):
Expand Down Expand Up @@ -206,7 +197,12 @@ async def async_gen() -> AsyncIterator[str]:
async for line in lines:
yield line

return Response(_iter_over_async(async_gen(), loop), mimetype='text/event-stream')
def stream_body() -> Generator[str, None, None]:
# WSGI consumes the body after the async view returns.
with contextlib.closing(asyncio.new_event_loop()) as loop:
yield from _iter_over_async(async_gen(), loop)

return Response(stream_body(), mimetype='text/event-stream')
try:
response = await flow.run(input=action_input, context=action_context, init=init)
return Response(response=result_json(response.response), mimetype='application/json')
Expand Down
36 changes: 36 additions & 0 deletions packages/genkit-flask/tests/flask_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import threading
import warnings
from collections.abc import AsyncIterator
from concurrent.futures import ThreadPoolExecutor
from typing import Any

import pytest
Expand Down Expand Up @@ -463,6 +464,41 @@ async def chat(_: str) -> str:
assert response.status_code == 401


def test_concurrent_streaming_requests_to_same_flow() -> None:
"""Both SSE responses complete while one flow invocation waits for the other."""
ai = Genkit()
app = Flask(__name__)
app.config['TESTING'] = True
first_started = threading.Event()
release_first = threading.Event()

@app.post('/chat')
@genkit_flask_handler(ai)
@ai.flow()
async def chat(name: str, ctx: FlowContext) -> str:
if name == 'first':
first_started.set()
if not await asyncio.to_thread(release_first.wait, 10):
raise TimeoutError('second response did not complete')
ctx.send_chunk(name)
return name

def request_stream(name: str) -> bytes:
response = app.test_client().post(
'/chat', json={'data': name}, headers={'accept': 'text/event-stream'}, buffered=True
)
return response.data

with ThreadPoolExecutor(max_workers=1) as executor:
first = executor.submit(request_stream, 'first')
try:
assert first_started.wait(5)
assert request_stream('second') == b'data: {"message":"second"}\n\ndata: {"result":"second"}\n\n'
finally:
release_first.set()
assert first.result(timeout=5) == b'data: {"message":"first"}\n\ndata: {"result":"first"}\n\n'


def test_flask_streaming_client_disconnect_cancels_flow() -> None:
"""A client that hangs up after the first SSE chunk cancels the flow and lets awaiting `finally:` finish."""
ai = Genkit()
Expand Down
Loading