Fix: capture main_agent before SSE generator to avoid lost app context
Quart exits the request/app context before iterating the SSE response body, so current_app inside event_generator() raised "Not within an app context". Capture the reference before the generator is defined. Also add return after the exception error yield to prevent falling through to a second "No response generated" event on the same stream. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -247,6 +247,10 @@ async def stream_query():
|
||||
"system_prompt": system_prompt,
|
||||
}
|
||||
}
|
||||
# Capture the agent reference while the request/app context is still active.
|
||||
# Quart exits the app context before iterating the SSE response body, so
|
||||
# current_app cannot be accessed inside event_generator().
|
||||
main_agent = current_app.main_agent
|
||||
|
||||
async def event_generator():
|
||||
final_message = None
|
||||
@@ -305,7 +309,7 @@ async def stream_query():
|
||||
)
|
||||
|
||||
try:
|
||||
aiter = current_app.main_agent.astream_events(
|
||||
aiter = main_agent.astream_events(
|
||||
payload, version="v2", config=agent_config
|
||||
).__aiter__()
|
||||
while True:
|
||||
@@ -414,6 +418,7 @@ async def stream_query():
|
||||
count_result(stream=True, result="error")
|
||||
_log_summary(error=str(e))
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
|
||||
return
|
||||
|
||||
final_message = final_message or streamed
|
||||
if final_message:
|
||||
|
||||
Reference in New Issue
Block a user