-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add REPL run_demo_loop helper #811
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
--- | ||
search: | ||
exclude: true | ||
--- | ||
# REPL ユーティリティ | ||
|
||
`run_demo_loop` を使うと、ターミナルから手軽にエージェントを試せます。 | ||
|
||
```python | ||
import asyncio | ||
from agents import Agent, run_demo_loop | ||
|
||
async def main() -> None: | ||
agent = Agent(name="Assistant", instructions="あなたは親切なアシスタントです") | ||
await run_demo_loop(agent) | ||
|
||
if __name__ == "__main__": | ||
asyncio.run(main()) | ||
``` | ||
|
||
`run_demo_loop` は入力を繰り返し受け取り、会話履歴を保持したままエージェントを実行します。既定ではストリーミング出力を表示します。 | ||
`quit` または `exit` と入力するか `Ctrl-D` を押すと終了します。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
# `repl` | ||
|
||
::: agents.repl | ||
options: | ||
members: | ||
- run_demo_loop |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# REPL utility | ||
|
||
The SDK provides `run_demo_loop` for quick interactive testing. | ||
|
||
```python | ||
import asyncio | ||
from agents import Agent, run_demo_loop | ||
|
||
async def main() -> None: | ||
agent = Agent(name="Assistant", instructions="You are a helpful assistant.") | ||
await run_demo_loop(agent) | ||
|
||
if __name__ == "__main__": | ||
asyncio.run(main()) | ||
``` | ||
|
||
`run_demo_loop` prompts for user input in a loop, keeping the conversation | ||
history between turns. By default it streams model output as it is produced. | ||
Type `quit` or `exit` (or press `Ctrl-D`) to leave the loop. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
from __future__ import annotations | ||
|
||
from typing import Any | ||
|
||
from openai.types.responses.response_text_delta_event import ResponseTextDeltaEvent | ||
|
||
from .agent import Agent | ||
from .items import ItemHelpers, TResponseInputItem | ||
from .result import RunResultBase | ||
from .run import Runner | ||
from .stream_events import AgentUpdatedStreamEvent, RawResponsesStreamEvent, RunItemStreamEvent | ||
|
||
|
||
async def run_demo_loop(agent: Agent[Any], *, stream: bool = True) -> None: | ||
"""Run a simple REPL loop with the given agent. | ||
|
||
This utility allows quick manual testing and debugging of an agent from the | ||
command line. Conversation state is preserved across turns. Enter ``exit`` | ||
or ``quit`` to stop the loop. | ||
|
||
Args: | ||
agent: The starting agent to run. | ||
stream: Whether to stream the agent output. | ||
""" | ||
|
||
current_agent = agent | ||
input_items: list[TResponseInputItem] = [] | ||
while True: | ||
try: | ||
user_input = input(" > ") | ||
except (EOFError, KeyboardInterrupt): | ||
print() | ||
break | ||
if user_input.strip().lower() in {"exit", "quit"}: | ||
break | ||
if not user_input: | ||
continue | ||
|
||
input_items.append({"role": "user", "content": user_input}) | ||
|
||
result: RunResultBase | ||
if stream: | ||
result = Runner.run_streamed(current_agent, input=input_items) | ||
async for event in result.stream_events(): | ||
if isinstance(event, RawResponsesStreamEvent): | ||
if isinstance(event.data, ResponseTextDeltaEvent): | ||
print(event.data.delta, end="", flush=True) | ||
elif isinstance(event, RunItemStreamEvent): | ||
if event.item.type == "tool_call_item": | ||
print("\n[tool called]", flush=True) | ||
elif event.item.type == "tool_call_output_item": | ||
print(f"\n[tool output: {event.item.output}]", flush=True) | ||
elif event.item.type == "message_output_item": | ||
message = ItemHelpers.text_message_output(event.item) | ||
print(message, end="", flush=True) | ||
elif isinstance(event, AgentUpdatedStreamEvent): | ||
print(f"\n[Agent updated: {event.new_agent.name}]", flush=True) | ||
print() | ||
else: | ||
result = await Runner.run(current_agent, input_items) | ||
if result.final_output is not None: | ||
print(result.final_output) | ||
|
||
current_agent = result.last_agent | ||
input_items = result.to_input_list() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import pytest | ||
|
||
from agents import Agent, run_demo_loop | ||
|
||
from .fake_model import FakeModel | ||
from .test_responses import get_text_input_item, get_text_message | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_run_demo_loop_conversation(monkeypatch, capsys): | ||
model = FakeModel() | ||
model.add_multiple_turn_outputs([[get_text_message("hello")], [get_text_message("good")]]) | ||
|
||
agent = Agent(name="test", model=model) | ||
|
||
inputs = iter(["Hi", "How are you?", "quit"]) | ||
monkeypatch.setattr("builtins.input", lambda _=" > ": next(inputs)) | ||
|
||
await run_demo_loop(agent, stream=False) | ||
|
||
output = capsys.readouterr().out | ||
assert "hello" in output | ||
assert "good" in output | ||
assert model.last_turn_args["input"] == [ | ||
get_text_input_item("Hi"), | ||
get_text_message("hello").model_dump(exclude_unset=True), | ||
get_text_input_item("How are you?"), | ||
] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
im pretty sure codex just wrote the japanese lol