Run one agent turn with streaming output and persist the new history.
(
agent: Any,
session: ChatSession,
user_input: str,
style: Style,
*,
use_color: bool = True,
raw: bool = False,
)
| 324 | |
| 325 | |
| 326 | async def _run_turn( |
| 327 | agent: Any, |
| 328 | session: ChatSession, |
| 329 | user_input: str, |
| 330 | style: Style, |
| 331 | *, |
| 332 | use_color: bool = True, |
| 333 | raw: bool = False, |
| 334 | ) -> None: |
| 335 | """Run one agent turn with streaming output and persist the new history.""" |
| 336 | from agents import ( |
| 337 | RawResponsesStreamEvent, |
| 338 | RunItemStreamEvent, |
| 339 | Runner, |
| 340 | ) |
| 341 | from openai.types.responses import ResponseTextDeltaEvent |
| 342 | |
| 343 | new_input = session.history + [{"role": "user", "content": user_input}] |
| 344 | |
| 345 | result = Runner.run_streamed(agent, new_input, max_turns=MAX_TURNS) |
| 346 | |
| 347 | print() |
| 348 | collected: list[str] = [] |
| 349 | segment: list[str] = [] |
| 350 | last_was_text = False |
| 351 | need_blank_before_text = False |
| 352 | |
| 353 | if use_color and not raw: |
| 354 | from rich.live import Live |
| 355 | |
| 356 | console = _make_rich_console() |
| 357 | else: |
| 358 | console = None # type: ignore[assignment] |
| 359 | |
| 360 | def _start_live() -> Any: |
| 361 | if console is None: |
| 362 | return None |
| 363 | lv = Live(console=console, vertical_overflow="visible") |
| 364 | lv.start() |
| 365 | return lv |
| 366 | |
| 367 | live = _start_live() |
| 368 | |
| 369 | try: |
| 370 | async for event in result.stream_events(): |
| 371 | if isinstance(event, RawResponsesStreamEvent): |
| 372 | if isinstance(event.data, ResponseTextDeltaEvent): |
| 373 | text = event.data.delta |
| 374 | if text: |
| 375 | if need_blank_before_text: |
| 376 | if console is not None: |
| 377 | print() |
| 378 | segment = [] |
| 379 | live = _start_live() |
| 380 | else: |
| 381 | sys.stdout.write("\n") |
| 382 | need_blank_before_text = False |
| 383 | collected.append(text) |
no test coverage detected