跳过内容

Runner

Runner

源代码在 src/agents/run.py
class Runner:
    @classmethod
    async def run(
        cls,
        starting_agent: Agent[TContext],
        input: str | list[TResponseInputItem],
        *,
        context: TContext | None = None,
        max_turns: int = DEFAULT_MAX_TURNS,
        hooks: RunHooks[TContext] | None = None,
        run_config: RunConfig | None = None,
        previous_response_id: str | None = None,
        auto_previous_response_id: bool = False,
        conversation_id: str | None = None,
        session: Session | None = None,
    ) -> RunResult:
        """
        Run a workflow starting at the given agent.

        The agent will run in a loop until a final output is generated. The loop runs like so:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response. If using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The conversation ID
                (https://platform.openai.com/docs/guides/conversation-state?api-mode=responses).
                If provided, the conversation will be used to read and write items.
                Every agent will have access to the conversation history so far,
                and its output items will be written to the conversation.
                We recommend only using this if you are exclusively using OpenAI models;
                other model providers don't write to the Conversation object,
                so you'll end up having partial conversations stored.
            session: A session for automatic conversation history management.

        Returns:
            A run result containing all the inputs, guardrail results and the output of
            the last agent. Agents may perform handoffs, so we don't know the specific
            type of the output.
        """

        runner = DEFAULT_AGENT_RUNNER
        return await runner.run(
            starting_agent,
            input,
            context=context,
            max_turns=max_turns,
            hooks=hooks,
            run_config=run_config,
            previous_response_id=previous_response_id,
            auto_previous_response_id=auto_previous_response_id,
            conversation_id=conversation_id,
            session=session,
        )

    @classmethod
    def run_sync(
        cls,
        starting_agent: Agent[TContext],
        input: str | list[TResponseInputItem],
        *,
        context: TContext | None = None,
        max_turns: int = DEFAULT_MAX_TURNS,
        hooks: RunHooks[TContext] | None = None,
        run_config: RunConfig | None = None,
        previous_response_id: str | None = None,
        auto_previous_response_id: bool = False,
        conversation_id: str | None = None,
        session: Session | None = None,
    ) -> RunResult:
        """
        Run a workflow synchronously, starting at the given agent.

        Note:
            This just wraps the `run` method, so it will not work if there's already an
            event loop (e.g. inside an async function, or in a Jupyter notebook or async
            context like FastAPI). For those cases, use the `run` method instead.

        The agent will run in a loop until a final output is generated. The loop runs:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response, if using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The ID of the stored conversation, if any.
            session: A session for automatic conversation history management.

        Returns:
            A run result containing all the inputs, guardrail results and the output of
            the last agent. Agents may perform handoffs, so we don't know the specific
            type of the output.
        """

        runner = DEFAULT_AGENT_RUNNER
        return runner.run_sync(
            starting_agent,
            input,
            context=context,
            max_turns=max_turns,
            hooks=hooks,
            run_config=run_config,
            previous_response_id=previous_response_id,
            conversation_id=conversation_id,
            session=session,
            auto_previous_response_id=auto_previous_response_id,
        )

    @classmethod
    def run_streamed(
        cls,
        starting_agent: Agent[TContext],
        input: str | list[TResponseInputItem],
        context: TContext | None = None,
        max_turns: int = DEFAULT_MAX_TURNS,
        hooks: RunHooks[TContext] | None = None,
        run_config: RunConfig | None = None,
        previous_response_id: str | None = None,
        auto_previous_response_id: bool = False,
        conversation_id: str | None = None,
        session: Session | None = None,
    ) -> RunResultStreaming:
        """
        Run a workflow starting at the given agent in streaming mode.

        The returned result object contains a method you can use to stream semantic
        events as they are generated.

        The agent will run in a loop until a final output is generated. The loop runs like so:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response, if using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The ID of the stored conversation, if any.
            session: A session for automatic conversation history management.

        Returns:
            A result object that contains data about the run, as well as a method to
            stream events.
        """

        runner = DEFAULT_AGENT_RUNNER
        return runner.run_streamed(
            starting_agent,
            input,
            context=context,
            max_turns=max_turns,
            hooks=hooks,
            run_config=run_config,
            previous_response_id=previous_response_id,
            auto_previous_response_id=auto_previous_response_id,
            conversation_id=conversation_id,
            session=session,
        )

run async classmethod

run(
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    *,
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResult

从给定的 agent 开始运行一个工作流。

agent 将在一个循环中运行,直到生成最终输出。循环的运行方式如下

  1. 代理使用给定的输入被调用。
  2. 如果存在最终输出(即 agent 产生 agent.output_type 类型的内容),则循环终止。
  3. 如果存在移交,我们将再次运行循环,使用新的 agent。
  4. 否则,我们运行工具调用(如果有的话),并重新运行循环。

在两种情况下,代理可能会引发异常

  1. 如果超过了最大回合数,将引发 MaxTurnsExceeded 异常。
  2. 如果触发了护栏触发器,则会引发 GuardrailTripwireTriggered 异常。
注意

仅运行第一个 agent 的输入 guardrails。

参数

名称 类型 描述 默认
starting_agent Agent[TContext]

要运行的起始代理。

required
input str | list[TResponseInputItem]

agent 的初始输入。您可以传递单个字符串作为用户消息,也可以传递输入项列表。

required
context TContext | None

使用哪个 context 运行 agent。

None
max_turns int

运行 agent 的最大回合数。一个回合定义为一次 AI 调用(包括可能发生的任何工具调用)。

DEFAULT_MAX_TURNS
hooks RunHooks[TContext] | None

一个对象,它在各种生命周期事件发生时接收回调。

None
run_config RunConfig | None

整个 agent 运行的全局设置。

None
previous_response_id str | None

前一个响应的 ID。如果通过 Responses API 使用 OpenAI 模型,这允许您跳过传递前一回合的输入。

None
conversation_id str | None

会话 ID(https://platform.openai.com/docs/guides/conversation-state?api-mode=responses)。如果提供,将使用会话来读取和写入项。每个 agent 都可以访问到目前为止的会话历史记录,并且其输出项将被写入会话。我们建议仅在专门使用 OpenAI 模型时才使用此功能;其他模型提供程序不会写入 Conversation 对象,因此最终只会存储部分会话。

None
session Session | None

用于自动会话历史记录管理的会话。

None

返回值

类型 描述
RunResult

一个运行结果,包含所有输入、guardrail 结果和最后一个 agent 的输出

RunResult

agent 可能会执行移交,因此我们不知道输出的具体

RunResult

类型。

源代码在 src/agents/run.py
@classmethod
async def run(
    cls,
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    *,
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResult:
    """
    Run a workflow starting at the given agent.

    The agent will run in a loop until a final output is generated. The loop runs like so:

      1. The agent is invoked with the given input.
      2. If there is a final output (i.e. the agent produces something of type
         `agent.output_type`), the loop terminates.
      3. If there's a handoff, we run the loop again, with the new agent.
      4. Else, we run tool calls (if any), and re-run the loop.

    In two cases, the agent may raise an exception:

      1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
      2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
         exception is raised.

    Note:
        Only the first agent's input guardrails are run.

    Args:
        starting_agent: The starting agent to run.
        input: The initial input to the agent. You can pass a single string for a
            user message, or a list of input items.
        context: The context to run the agent with.
        max_turns: The maximum number of turns to run the agent for. A turn is
            defined as one AI invocation (including any tool calls that might occur).
        hooks: An object that receives callbacks on various lifecycle events.
        run_config: Global settings for the entire agent run.
        previous_response_id: The ID of the previous response. If using OpenAI
            models via the Responses API, this allows you to skip passing in input
            from the previous turn.
        conversation_id: The conversation ID
            (https://platform.openai.com/docs/guides/conversation-state?api-mode=responses).
            If provided, the conversation will be used to read and write items.
            Every agent will have access to the conversation history so far,
            and its output items will be written to the conversation.
            We recommend only using this if you are exclusively using OpenAI models;
            other model providers don't write to the Conversation object,
            so you'll end up having partial conversations stored.
        session: A session for automatic conversation history management.

    Returns:
        A run result containing all the inputs, guardrail results and the output of
        the last agent. Agents may perform handoffs, so we don't know the specific
        type of the output.
    """

    runner = DEFAULT_AGENT_RUNNER
    return await runner.run(
        starting_agent,
        input,
        context=context,
        max_turns=max_turns,
        hooks=hooks,
        run_config=run_config,
        previous_response_id=previous_response_id,
        auto_previous_response_id=auto_previous_response_id,
        conversation_id=conversation_id,
        session=session,
    )

run_sync classmethod

run_sync(
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    *,
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResult

同步运行一个工作流,从给定的 agent 开始。

注意

这只是包装了 run 方法,因此如果已经存在事件循环(例如,在异步函数内部,或者在 Jupyter notebook 或 FastAPI 等异步上下文中),它将无法工作。对于这些情况,请使用 run 方法。

agent 将在一个循环中运行,直到生成最终输出。循环运行

  1. 代理使用给定的输入被调用。
  2. 如果存在最终输出(即 agent 产生 agent.output_type 类型的内容),则循环终止。
  3. 如果存在移交,我们将再次运行循环,使用新的 agent。
  4. 否则,我们运行工具调用(如果有的话),并重新运行循环。

在两种情况下,代理可能会引发异常

  1. 如果超过了最大回合数,将引发 MaxTurnsExceeded 异常。
  2. 如果触发了护栏触发器,则会引发 GuardrailTripwireTriggered 异常。
注意

仅运行第一个 agent 的输入 guardrails。

参数

名称 类型 描述 默认
starting_agent Agent[TContext]

要运行的起始代理。

required
input str | list[TResponseInputItem]

agent 的初始输入。您可以传递单个字符串作为用户消息,也可以传递输入项列表。

required
context TContext | None

使用哪个 context 运行 agent。

None
max_turns int

运行 agent 的最大回合数。一个回合定义为一次 AI 调用(包括可能发生的任何工具调用)。

DEFAULT_MAX_TURNS
hooks RunHooks[TContext] | None

一个对象,它在各种生命周期事件发生时接收回调。

None
run_config RunConfig | None

整个 agent 运行的全局设置。

None
previous_response_id str | None

前一个响应的 ID,如果使用 OpenAI 模型通过 Responses API,这允许您跳过传递前一回合的输入。

None
conversation_id str | None

存储会话的 ID(如果有)。

None
session Session | None

用于自动会话历史记录管理的会话。

None

返回值

类型 描述
RunResult

一个运行结果,包含所有输入、guardrail 结果和最后一个 agent 的输出

RunResult

agent 可能会执行移交,因此我们不知道输出的具体

RunResult

类型。

源代码在 src/agents/run.py
@classmethod
def run_sync(
    cls,
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    *,
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResult:
    """
    Run a workflow synchronously, starting at the given agent.

    Note:
        This just wraps the `run` method, so it will not work if there's already an
        event loop (e.g. inside an async function, or in a Jupyter notebook or async
        context like FastAPI). For those cases, use the `run` method instead.

    The agent will run in a loop until a final output is generated. The loop runs:

      1. The agent is invoked with the given input.
      2. If there is a final output (i.e. the agent produces something of type
         `agent.output_type`), the loop terminates.
      3. If there's a handoff, we run the loop again, with the new agent.
      4. Else, we run tool calls (if any), and re-run the loop.

    In two cases, the agent may raise an exception:

      1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
      2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
         exception is raised.

    Note:
        Only the first agent's input guardrails are run.

    Args:
        starting_agent: The starting agent to run.
        input: The initial input to the agent. You can pass a single string for a
            user message, or a list of input items.
        context: The context to run the agent with.
        max_turns: The maximum number of turns to run the agent for. A turn is
            defined as one AI invocation (including any tool calls that might occur).
        hooks: An object that receives callbacks on various lifecycle events.
        run_config: Global settings for the entire agent run.
        previous_response_id: The ID of the previous response, if using OpenAI
            models via the Responses API, this allows you to skip passing in input
            from the previous turn.
        conversation_id: The ID of the stored conversation, if any.
        session: A session for automatic conversation history management.

    Returns:
        A run result containing all the inputs, guardrail results and the output of
        the last agent. Agents may perform handoffs, so we don't know the specific
        type of the output.
    """

    runner = DEFAULT_AGENT_RUNNER
    return runner.run_sync(
        starting_agent,
        input,
        context=context,
        max_turns=max_turns,
        hooks=hooks,
        run_config=run_config,
        previous_response_id=previous_response_id,
        conversation_id=conversation_id,
        session=session,
        auto_previous_response_id=auto_previous_response_id,
    )

run_streamed classmethod

run_streamed(
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResultStreaming

以流式模式运行一个工作流,从给定的 agent 开始。

返回的结果对象包含一个方法,您可以使用它来流式传输生成时语义事件。

agent 将在一个循环中运行,直到生成最终输出。循环的运行方式如下

  1. 代理使用给定的输入被调用。
  2. 如果存在最终输出(即 agent 产生 agent.output_type 类型的内容),则循环终止。
  3. 如果存在移交,我们将再次运行循环,使用新的 agent。
  4. 否则,我们运行工具调用(如果有的话),并重新运行循环。

在两种情况下,代理可能会引发异常

  1. 如果超过了最大回合数,将引发 MaxTurnsExceeded 异常。
  2. 如果触发了护栏触发器,则会引发 GuardrailTripwireTriggered 异常。
注意

仅运行第一个 agent 的输入 guardrails。

参数

名称 类型 描述 默认
starting_agent Agent[TContext]

要运行的起始代理。

required
input str | list[TResponseInputItem]

agent 的初始输入。您可以传递单个字符串作为用户消息,也可以传递输入项列表。

required
context TContext | None

使用哪个 context 运行 agent。

None
max_turns int

运行 agent 的最大回合数。一个回合定义为一次 AI 调用(包括可能发生的任何工具调用)。

DEFAULT_MAX_TURNS
hooks RunHooks[TContext] | None

一个对象,它在各种生命周期事件发生时接收回调。

None
run_config RunConfig | None

整个 agent 运行的全局设置。

None
previous_response_id str | None

前一个响应的 ID,如果使用 OpenAI 模型通过 Responses API,这允许您跳过传递前一回合的输入。

None
conversation_id str | None

存储会话的 ID(如果有)。

None
session Session | None

用于自动会话历史记录管理的会话。

None

返回值

类型 描述
RunResultStreaming

一个结果对象,包含有关运行的数据,以及一个方法来

RunResultStreaming

流式传输事件。

源代码在 src/agents/run.py
@classmethod
def run_streamed(
    cls,
    starting_agent: Agent[TContext],
    input: str | list[TResponseInputItem],
    context: TContext | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,
    hooks: RunHooks[TContext] | None = None,
    run_config: RunConfig | None = None,
    previous_response_id: str | None = None,
    auto_previous_response_id: bool = False,
    conversation_id: str | None = None,
    session: Session | None = None,
) -> RunResultStreaming:
    """
    Run a workflow starting at the given agent in streaming mode.

    The returned result object contains a method you can use to stream semantic
    events as they are generated.

    The agent will run in a loop until a final output is generated. The loop runs like so:

      1. The agent is invoked with the given input.
      2. If there is a final output (i.e. the agent produces something of type
         `agent.output_type`), the loop terminates.
      3. If there's a handoff, we run the loop again, with the new agent.
      4. Else, we run tool calls (if any), and re-run the loop.

    In two cases, the agent may raise an exception:

      1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
      2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
         exception is raised.

    Note:
        Only the first agent's input guardrails are run.

    Args:
        starting_agent: The starting agent to run.
        input: The initial input to the agent. You can pass a single string for a
            user message, or a list of input items.
        context: The context to run the agent with.
        max_turns: The maximum number of turns to run the agent for. A turn is
            defined as one AI invocation (including any tool calls that might occur).
        hooks: An object that receives callbacks on various lifecycle events.
        run_config: Global settings for the entire agent run.
        previous_response_id: The ID of the previous response, if using OpenAI
            models via the Responses API, this allows you to skip passing in input
            from the previous turn.
        conversation_id: The ID of the stored conversation, if any.
        session: A session for automatic conversation history management.

    Returns:
        A result object that contains data about the run, as well as a method to
        stream events.
    """

    runner = DEFAULT_AGENT_RUNNER
    return runner.run_streamed(
        starting_agent,
        input,
        context=context,
        max_turns=max_turns,
        hooks=hooks,
        run_config=run_config,
        previous_response_id=previous_response_id,
        auto_previous_response_id=auto_previous_response_id,
        conversation_id=conversation_id,
        session=session,
    )

RunConfig dataclass

配置整个 agent 运行的设置。

源代码在 src/agents/run.py
@dataclass
class RunConfig:
    """Configures settings for the entire agent run."""

    model: str | Model | None = None
    """The model to use for the entire agent run. If set, will override the model set on every
    agent. The model_provider passed in below must be able to resolve this model name.
    """

    model_provider: ModelProvider = field(default_factory=MultiProvider)
    """The model provider to use when looking up string model names. Defaults to OpenAI."""

    model_settings: ModelSettings | None = None
    """Configure global model settings. Any non-null values will override the agent-specific model
    settings.
    """

    handoff_input_filter: HandoffInputFilter | None = None
    """A global input filter to apply to all handoffs. If `Handoff.input_filter` is set, then that
    will take precedence. The input filter allows you to edit the inputs that are sent to the new
    agent. See the documentation in `Handoff.input_filter` for more details.
    """

    nest_handoff_history: bool = True
    """Wrap prior run history in a single assistant message before handing off when no custom
    input filter is set. Set to False to preserve the raw transcript behavior from previous
    releases.
    """

    handoff_history_mapper: HandoffHistoryMapper | None = None
    """Optional function that receives the normalized transcript (history + handoff items) and
    returns the input history that should be passed to the next agent. When left as `None`, the
    runner collapses the transcript into a single assistant message. This function only runs when
    `nest_handoff_history` is True.
    """

    input_guardrails: list[InputGuardrail[Any]] | None = None
    """A list of input guardrails to run on the initial run input."""

    output_guardrails: list[OutputGuardrail[Any]] | None = None
    """A list of output guardrails to run on the final output of the run."""

    tracing_disabled: bool = False
    """Whether tracing is disabled for the agent run. If disabled, we will not trace the agent run.
    """

    tracing: TracingConfig | None = None
    """Tracing configuration for this run."""

    trace_include_sensitive_data: bool = field(
        default_factory=_default_trace_include_sensitive_data
    )
    """Whether we include potentially sensitive data (for example: inputs/outputs of tool calls or
    LLM generations) in traces. If False, we'll still create spans for these events, but the
    sensitive data will not be included.
    """

    workflow_name: str = "Agent workflow"
    """The name of the run, used for tracing. Should be a logical name for the run, like
    "Code generation workflow" or "Customer support agent".
    """

    trace_id: str | None = None
    """A custom trace ID to use for tracing. If not provided, we will generate a new trace ID."""

    group_id: str | None = None
    """
    A grouping identifier to use for tracing, to link multiple traces from the same conversation
    or process. For example, you might use a chat thread ID.
    """

    trace_metadata: dict[str, Any] | None = None
    """
    An optional dictionary of additional metadata to include with the trace.
    """

    session_input_callback: SessionInputCallback | None = None
    """Defines how to handle session history when new input is provided.
    - `None` (default): The new input is appended to the session history.
    - `SessionInputCallback`: A custom function that receives the history and new input, and
      returns the desired combined list of items.
    """

    call_model_input_filter: CallModelInputFilter | None = None
    """
    Optional callback that is invoked immediately before calling the model. It receives the current
    agent, context and the model input (instructions and input items), and must return a possibly
    modified `ModelInputData` to use for the model call.

    This allows you to edit the input sent to the model e.g. to stay within a token limit.
    For example, you can use this to add a system prompt to the input.
    """

model class-attribute instance-attribute

model: str | Model | None = None

整个 agent 运行使用的模型。如果设置,将覆盖每个 agent 上设置的模型。下面传递的 model_provider 必须能够解析此模型名称。

model_provider class-attribute instance-attribute

model_provider: ModelProvider = field(
    default_factory=MultiProvider
)

在查找字符串模型名称时使用的模型提供程序。默认值为 OpenAI。

model_settings class-attribute instance-attribute

model_settings: ModelSettings | None = None

配置全局模型设置。任何非空值都将覆盖 agent 特定的模型设置。

handoff_input_filter class-attribute instance-attribute

handoff_input_filter: HandoffInputFilter | None = None

应用于所有移交的全局输入过滤器。如果设置了 Handoff.input_filter,则该过滤器优先。输入过滤器允许您编辑发送到新 agent 的输入。有关更多详细信息,请参阅 Handoff.input_filter 中的文档。

nest_handoff_history class-attribute instance-attribute

nest_handoff_history: bool = True

在没有自定义输入过滤器的情况下,在移交之前将先前的运行历史记录包装在单个助手消息中。设置为 False 以保留先前版本中的原始转录行为。

handoff_history_mapper class-attribute instance-attribute

handoff_history_mapper: HandoffHistoryMapper | None = None

可选函数,接收规范化的转录记录(历史记录 + 移交项),并返回应传递给下一个 agent 的输入历史记录。当 nest_handoff_history 为 True 时,此函数仅运行。

input_guardrails class-attribute instance-attribute

input_guardrails: list[InputGuardrail[Any]] | None = None

应用于初始运行输入的输入 guardrails 列表。

output_guardrails class-attribute instance-attribute

output_guardrails: list[OutputGuardrail[Any]] | None = None

应用于运行最终输出的输出 guardrails 列表。

tracing_disabled class-attribute instance-attribute

tracing_disabled: bool = False

是否禁用 agent 运行的跟踪。如果禁用,我们将不会跟踪 agent 运行。

tracing class-attribute instance-attribute

tracing: TracingConfig | None = None

本次运行的跟踪配置。

trace_include_sensitive_data class-attribute instance-attribute

trace_include_sensitive_data: bool = field(
    default_factory=_default_trace_include_sensitive_data
)

是否在跟踪中包含潜在的敏感数据(例如:工具调用或 LLM 生成的输入/输出)。如果为 False,我们将仍然为这些事件创建 span,但敏感数据将不会被包含。

workflow_name class-attribute instance-attribute

workflow_name: str = 'Agent workflow'

运行的名称,用于跟踪。应该是运行的逻辑名称,例如“代码生成工作流”或“客户支持 agent”。

trace_id class-attribute instance-attribute

trace_id: str | None = None

用于跟踪的自定义跟踪 ID。如果未提供,我们将生成一个新的跟踪 ID。

group_id class-attribute instance-attribute

group_id: str | None = None

用于跟踪的分组标识符,以链接来自同一对话或进程的多个跟踪。例如,您可以使用聊天线程 ID。

trace_metadata class-attribute instance-attribute

trace_metadata: dict[str, Any] | None = None

包含在跟踪中的可选附加元数据字典。

session_input_callback class-attribute instance-attribute

session_input_callback: SessionInputCallback | None = None

定义如何处理在提供新输入时会话历史记录。- None(默认):将新输入附加到会话历史记录中。- SessionInputCallback:一个自定义函数,它接收历史记录和新输入,并返回所需的组合项列表。

call_model_input_filter class-attribute instance-attribute

call_model_input_filter: CallModelInputFilter | None = None

在调用模型之前立即调用的可选回调。它接收当前 agent、context 和模型输入(指令和输入项),并且必须返回用于模型调用的可能修改后的 ModelInputData

这允许您编辑发送到模型的输入,例如以保持在 token 限制内。例如,您可以使用此功能向输入添加系统提示。