跳转至

运行代理

您可以通过Runner类运行代理,有3种选择:

  1. 异步运行并返回RunResult
  2. 同步方法,底层调用.run()
  3. 异步运行并返回RunResultStreaming,以流式模式调用LLM并实时传输事件
from agents import Agent, Runner

async def main():
    agent = Agent(name="Assistant", instructions="You are a helpful assistant")

    result = await Runner.run(agent, "Write a haiku about recursion in programming.")
    print(result.final_output)
    # Code within the code,
    # Functions calling themselves,
    # Infinite loop's dance.

更多信息请参阅结果指南

代理循环

当使用Runner中的run方法时,您需要传入初始代理和输入。输入可以是字符串(视为用户消息),也可以是OpenAI Responses API中的输入项列表

运行器会执行以下循环:

  1. 为当前代理调用LLM,传入当前输入
  2. LLM产生输出
    1. 如果LLM返回final_output,循环结束并返回结果
    2. 如果LLM执行交接,我们更新当前代理和输入,并重新运行循环
    3. 如果LLM产生工具调用,我们运行这些工具调用,追加结果并重新运行循环
  3. 如果超过max_turns限制,抛出MaxTurnsExceeded异常

说明

LLM输出被视为"final output"的规则是:它产生具有所需类型的文本输出,并且没有工具调用

流式传输

流式传输允许您在LLM运行时接收流式事件。流结束后,RunResultStreaming将包含运行的完整信息,包括所有新产生的输出。您可以调用.stream_events()获取流式事件。更多信息请参阅流式指南

运行配置

run_config参数允许您为代理运行配置一些全局设置:

对话/聊天线程

调用任何运行方法可能导致一个或多个代理运行(因此有一个或多个LLM调用),但它代表聊天对话中的单个逻辑轮次

  1. 用户轮次:用户输入文本
  2. 运行器运行:第一个代理调用LLM,运行工具,交接给第二个代理,第二个代理运行更多工具,然后产生输出

代理运行结束时,您可以选择向用户显示什么内容。例如,您可以显示代理生成的每个新项,或仅显示最终输出。无论哪种方式,用户可能会提出后续问题,这时您可以再次调用运行方法

您可以使用RunResultBase.to_input_list()方法获取下一轮次的输入

async def main():
    agent = Agent(name="Assistant", instructions="Reply very concisely.")

    with trace(workflow_name="Conversation", group_id=thread_id):
        # First turn
        result = await Runner.run(agent, "What city is the Golden Gate Bridge in?")
        print(result.final_output)
        # San Francisco

        # Second turn
        new_input = result.to_input_list() + [{"role": "user", "content": "What state is it in?"}]
        result = await Runner.run(agent, new_input)
        print(result.final_output)
        # California

异常

SDK在某些情况下会抛出异常,完整列表见agents.exceptions,概述如下: