ストリーミング
ストリーミングを使うと、エージェントの実行が進むにつれて更新を購読できます。これは、エンドユーザーに進捗更新や部分的な応答を表示するのに役立ちます。
ストリーミングするには、Runner.run_streamed() を呼び出せます。これにより RunResultStreaming が得られます。result.stream_events() を呼び出すと、以下で説明する StreamEvent オブジェクトの非同期ストリームが得られます。
raw レスポンスイベント
RawResponsesStreamEvent は、LLM から直接渡される raw イベントです。これらは OpenAI Responses API 形式であり、各イベントは type(response.created、response.output_text.delta など)と data を持ちます。これらのイベントは、生成され次第すぐに応答メッセージをユーザーにストリーミングしたい場合に有用です。
たとえば、これは LLM によって生成されたテキストをトークンごとに出力します。
import asyncio
from openai.types.responses import ResponseTextDeltaEvent
from agents import Agent, Runner
async def main():
agent = Agent(
name="Joker",
instructions="You are a helpful assistant.",
)
result = Runner.run_streamed(agent, input="Please tell me 5 jokes.")
async for event in result.stream_events():
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
print(event.data.delta, end="", flush=True)
if __name__ == "__main__":
asyncio.run(main())
実行アイテムイベントとエージェントイベント
RunItemStreamEvent は、より高レベルなイベントです。これは、アイテムが完全に生成されたタイミングを通知します。これにより、各トークン単位ではなく、「メッセージが生成された」「ツールが実行された」などのレベルで進捗更新を送れます。同様に、AgentUpdatedStreamEvent は、現在のエージェントが変わったとき(例: ハンドオフの結果)に更新を提供します。
実行アイテムイベント名
RunItemStreamEvent.name は、固定のセマンティックなイベント名セットを使用します。
message_output_createdhandoff_requestedhandoff_occuredtool_calledtool_outputreasoning_item_createdmcp_approval_requestedmcp_approval_responsemcp_list_tools
handoff_occured は、後方互換性のために意図的にスペルミスのままになっています。
たとえば、これは raw イベントを無視し、更新をユーザーにストリーミングします。
import asyncio
import random
from agents import Agent, ItemHelpers, Runner, function_tool
@function_tool
def how_many_jokes() -> int:
return random.randint(1, 10)
async def main():
agent = Agent(
name="Joker",
instructions="First call the `how_many_jokes` tool, then tell that many jokes.",
tools=[how_many_jokes],
)
result = Runner.run_streamed(
agent,
input="Hello",
)
print("=== Run starting ===")
async for event in result.stream_events():
# We'll ignore the raw responses event deltas
if event.type == "raw_response_event":
continue
# When the agent updates, print that
elif event.type == "agent_updated_stream_event":
print(f"Agent updated: {event.new_agent.name}")
continue
# When items are generated, print them
elif event.type == "run_item_stream_event":
if event.item.type == "tool_call_item":
print("-- Tool was called")
elif event.item.type == "tool_call_output_item":
print(f"-- Tool output: {event.item.output}")
elif event.item.type == "message_output_item":
print(f"-- Message output:\n {ItemHelpers.text_message_output(event.item)}")
else:
pass # Ignore other event types
print("=== Run complete ===")
if __name__ == "__main__":
asyncio.run(main())