流式传输
流式传输允许你在智能体运行的过程中订阅其更新。这对于向最终用户展示进度更新和部分响应非常有用。
要进行流式传输,你可以调用Runner.run_streamed(),它会返回一个RunResultStreaming。调用result.stream_events() 会给出一个由StreamEvent 对象组成的异步流,具体类型见下文。
原始响应事件
RawResponsesStreamEvent 是直接从 LLM 传递过来的原始事件。它们采用 OpenAI Responses API 格式,这意味着每个事件都有一个类型(如response.created、response.output_text.delta 等)和数据。如果你想在生成时就将响应消息流式传给用户,这些事件会很有用。
例如,下面会按 token 逐个输出 LLM 生成的文本。
importasynciofromopenai.types.responsesimportResponseTextDeltaEventfromagentsimportAgent,Runnerasyncdefmain():agent=Agent(name="Joker",instructions="You are a helpful assistant.",)result=Runner.run_streamed(agent,input="Please tell me 5 jokes.")asyncforeventinresult.stream_events():ifevent.type=="raw_response_event"andisinstance(event.data,ResponseTextDeltaEvent):print(event.data.delta,end="",flush=True)if__name__=="__main__":asyncio.run(main())运行项事件与智能体事件
RunItemStreamEvent 是更高层的事件。它会在某个条目完全生成时通知你。这样你就可以在“消息已生成”“工具已运行”等层面推送进度更新,而不是每个 token。同样,AgentUpdatedStreamEvent 会在当前智能体发生变化时(例如由于任务转移)向你提供更新。
例如,下面会忽略原始事件并向用户流式推送更新。
importasyncioimportrandomfromagentsimportAgent,ItemHelpers,Runner,function_tool@function_tooldefhow_many_jokes()->int:returnrandom.randint(1,10)asyncdefmain():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 ===")asyncforeventinresult.stream_events():# We'll ignore the raw responses event deltasifevent.type=="raw_response_event":continue# When the agent updates, print thatelifevent.type=="agent_updated_stream_event":print(f"Agent updated:{event.new_agent.name}")continue# When items are generated, print themelifevent.type=="run_item_stream_event":ifevent.item.type=="tool_call_item":print("-- Tool was called")elifevent.item.type=="tool_call_output_item":print(f"-- Tool output:{event.item.output}")elifevent.item.type=="message_output_item":print(f"-- Message output:\n{ItemHelpers.text_message_output(event.item)}")else:pass# Ignore other event typesprint("=== Run complete ===")if__name__=="__main__":asyncio.run(main())