| 87 | ) |
| 88 | |
| 89 | async def _run(): |
| 90 | streamed_run = Runner.run_streamed(agent, prompt) |
| 91 | current_stream_kind = None |
| 92 | async for event in streamed_run.stream_events(): |
| 93 | if isinstance(event, RawResponsesStreamEvent): |
| 94 | if isinstance(event.data, ResponseReasoningSummaryTextDeltaEvent): |
| 95 | if current_stream_kind != "reasoning": |
| 96 | if current_stream_kind is not None: |
| 97 | print() |
| 98 | print("\n[reasoning]: ", end="", flush=True) |
| 99 | delta = event.data.delta |
| 100 | print(delta, end="", flush=True) |
| 101 | current_stream_kind = "reasoning" |
| 102 | elif isinstance(event.data, ResponseTextDeltaEvent): |
| 103 | if current_stream_kind != "text": |
| 104 | if current_stream_kind is not None: |
| 105 | print() |
| 106 | print("\n[text]: ", end="", flush=True) |
| 107 | delta = event.data.delta |
| 108 | print(delta, end="", flush=True) |
| 109 | current_stream_kind = "text" |
| 110 | elif isinstance(event, RunItemStreamEvent): |
| 111 | item = event.item |
| 112 | if item.type == "tool_call_item": |
| 113 | if current_stream_kind is not None: |
| 114 | print() |
| 115 | raw = item.raw_item |
| 116 | args = getattr(raw, "arguments", "{}") |
| 117 | args_str = f"({args})" if verbose else "" |
| 118 | print(f"\n[tool call]: {raw.name}{args_str}", flush=True) |
| 119 | current_stream_kind = None |
| 120 | elif item.type == "tool_call_output_item" and verbose: |
| 121 | if current_stream_kind is not None: |
| 122 | print() |
| 123 | output = str(item.output) |
| 124 | preview = output[:200] + "..." if len(output) > 200 else output |
| 125 | print(f"\n[tool call output]: {preview}", flush=True) |
| 126 | current_stream_kind = None |
| 127 | if current_stream_kind is not None: |
| 128 | print() |
| 129 | return "" if not streamed_run.final_output else str(streamed_run.final_output) |
| 130 | |
| 131 | try: |
| 132 | asyncio.get_running_loop() |