ai-lawyer-agent/core/stream_response.py
2026-03-15 22:45:33 +01:00

14 lines
645 B
Python

from typing import AsyncGenerator
from agents import Agent, Runner
from openai.types.responses import ResponseTextDeltaEvent
async def stream_response(agent: Agent, prompt: list[dict] | str) -> AsyncGenerator[str, None]:
"""Stream agent response and update the UI."""
try:
result = Runner.run_streamed(agent, input=prompt)
async for event in result.stream_events():
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
yield event.data.delta # <-- sends the next piece of response text
except Exception as e:
yield f"⚠️🖨️ Error: {e}"