|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from openai.types.responses.response_text_delta_event import ResponseTextDeltaEvent |
| 6 | + |
| 7 | +from .agent import Agent |
| 8 | +from .items import ItemHelpers, TResponseInputItem |
| 9 | +from .result import RunResultBase |
| 10 | +from .run import Runner |
| 11 | +from .stream_events import AgentUpdatedStreamEvent, RawResponsesStreamEvent, RunItemStreamEvent |
| 12 | + |
| 13 | + |
| 14 | +async def run_demo_loop(agent: Agent[Any], *, stream: bool = True) -> None: |
| 15 | + """Run a simple REPL loop with the given agent. |
| 16 | +
|
| 17 | + This utility allows quick manual testing and debugging of an agent from the |
| 18 | + command line. Conversation state is preserved across turns. Enter ``exit`` |
| 19 | + or ``quit`` to stop the loop. |
| 20 | +
|
| 21 | + Args: |
| 22 | + agent: The starting agent to run. |
| 23 | + stream: Whether to stream the agent output. |
| 24 | + """ |
| 25 | + |
| 26 | + current_agent = agent |
| 27 | + input_items: list[TResponseInputItem] = [] |
| 28 | + while True: |
| 29 | + try: |
| 30 | + user_input = input(" > ") |
| 31 | + except (EOFError, KeyboardInterrupt): |
| 32 | + print() |
| 33 | + break |
| 34 | + if user_input.strip().lower() in {"exit", "quit"}: |
| 35 | + break |
| 36 | + if not user_input: |
| 37 | + continue |
| 38 | + |
| 39 | + input_items.append({"role": "user", "content": user_input}) |
| 40 | + |
| 41 | + result: RunResultBase |
| 42 | + if stream: |
| 43 | + result = Runner.run_streamed(current_agent, input=input_items) |
| 44 | + async for event in result.stream_events(): |
| 45 | + if isinstance(event, RawResponsesStreamEvent): |
| 46 | + if isinstance(event.data, ResponseTextDeltaEvent): |
| 47 | + print(event.data.delta, end="", flush=True) |
| 48 | + elif isinstance(event, RunItemStreamEvent): |
| 49 | + if event.item.type == "tool_call_item": |
| 50 | + print("\n[tool called]", flush=True) |
| 51 | + elif event.item.type == "tool_call_output_item": |
| 52 | + print(f"\n[tool output: {event.item.output}]", flush=True) |
| 53 | + elif event.item.type == "message_output_item": |
| 54 | + message = ItemHelpers.text_message_output(event.item) |
| 55 | + print(message, end="", flush=True) |
| 56 | + elif isinstance(event, AgentUpdatedStreamEvent): |
| 57 | + print(f"\n[Agent updated: {event.new_agent.name}]", flush=True) |
| 58 | + print() |
| 59 | + else: |
| 60 | + result = await Runner.run(current_agent, input_items) |
| 61 | + if result.final_output is not None: |
| 62 | + print(result.final_output) |
| 63 | + |
| 64 | + current_agent = result.last_agent |
| 65 | + input_items = result.to_input_list() |
0 commit comments