跳过内容

Items

TResponse 模块属性

TResponse = Response

OpenAI SDK 中的 Response 类型的别名。

TResponseInputItem 模块属性

TResponseInputItem = ResponseInputItemParam

OpenAI SDK 中的 ResponseInputItemParam 类型的别名。

TResponseOutputItem 模块属性

TResponseOutputItem = ResponseOutputItem

OpenAI SDK 中的 ResponseOutputItem 类型的别名。

TResponseStreamEvent 模块属性

TResponseStreamEvent = ResponseStreamEvent

OpenAI SDK 中的 ResponseStreamEvent 类型的别名。

ToolCallItemTypes 模块属性

ToolCallItemTypes: TypeAlias = Union[
    ResponseFunctionToolCall,
    ResponseComputerToolCall,
    ResponseFileSearchToolCall,
    ResponseFunctionWebSearch,
    McpCall,
    ResponseCodeInterpreterToolCall,
    ImageGenerationCall,
    LocalShellCall,
    dict[str, Any],
]

表示工具调用项的类型。

RunItemBase dataclass

基础: Generic[T], ABC

源代码在 src/agents/items.py
@dataclass
class RunItemBase(Generic[T], abc.ABC):
    agent: Agent[Any]
    """The agent whose run caused this item to be generated."""

    raw_item: T
    """The raw Responses item from the run. This will always be either an output item (i.e.
    `openai.types.responses.ResponseOutputItem` or an input item
    (i.e. `openai.types.responses.ResponseInputItemParam`).
    """

    _agent_ref: weakref.ReferenceType[Agent[Any]] | None = field(
        init=False,
        repr=False,
        default=None,
    )

    def __post_init__(self) -> None:
        # Store a weak reference so we can release the strong reference later if desired.
        self._agent_ref = weakref.ref(self.agent)

    def __getattribute__(self, name: str) -> Any:
        if name == "agent":
            return self._get_agent_via_weakref("agent", "_agent_ref")
        return super().__getattribute__(name)

    def release_agent(self) -> None:
        """Release the strong reference to the agent while keeping a weak reference."""
        if "agent" not in self.__dict__:
            return
        agent = self.__dict__["agent"]
        if agent is None:
            return
        self._agent_ref = weakref.ref(agent) if agent is not None else None
        # Set to None instead of deleting so dataclass repr/asdict keep working.
        self.__dict__["agent"] = None

    def _get_agent_via_weakref(self, attr_name: str, ref_name: str) -> Any:
        # Preserve the dataclass field so repr/asdict still read it, but lazily resolve the weakref
        # when the stored value is None (meaning release_agent already dropped the strong ref).
        # If the attribute was never overridden we fall back to the default descriptor chain.
        data = object.__getattribute__(self, "__dict__")
        value = data.get(attr_name, _MISSING_ATTR_SENTINEL)
        if value is _MISSING_ATTR_SENTINEL:
            return object.__getattribute__(self, attr_name)
        if value is not None:
            return value
        ref = object.__getattribute__(self, ref_name)
        if ref is not None:
            agent = ref()
            if agent is not None:
                return agent
        return None

    def to_input_item(self) -> TResponseInputItem:
        """Converts this item into an input item suitable for passing to the model."""
        if isinstance(self.raw_item, dict):
            # We know that input items are dicts, so we can ignore the type error
            return self.raw_item  # type: ignore
        elif isinstance(self.raw_item, BaseModel):
            # All output items are Pydantic models that can be converted to input items.
            return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
        else:
            raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

raw_item 实例属性

raw_item: T

运行中的原始 Responses 项目。 这始终是输出项目(即 openai.types.responses.ResponseOutputItem)或输入项目(即 openai.types.responses.ResponseInputItemParam)。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

MessageOutputItem dataclass

基础: RunItemBase[ResponseOutputMessage]

表示来自 LLM 的消息。

源代码在 src/agents/items.py
@dataclass
class MessageOutputItem(RunItemBase[ResponseOutputMessage]):
    """Represents a message from the LLM."""

    raw_item: ResponseOutputMessage
    """The raw response output message."""

    type: Literal["message_output_item"] = "message_output_item"

raw_item 实例属性

raw_item: ResponseOutputMessage

原始响应输出消息。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

HandoffCallItem dataclass

基础: RunItemBase[ResponseFunctionToolCall]

表示从一个代理到另一个代理的交接的工具调用。

源代码在 src/agents/items.py
@dataclass
class HandoffCallItem(RunItemBase[ResponseFunctionToolCall]):
    """Represents a tool call for a handoff from one agent to another."""

    raw_item: ResponseFunctionToolCall
    """The raw response function tool call that represents the handoff."""

    type: Literal["handoff_call_item"] = "handoff_call_item"

raw_item 实例属性

raw_item: ResponseFunctionToolCall

表示交接的原始响应函数工具调用。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

HandoffOutputItem dataclass

基础: RunItemBase[TResponseInputItem]

表示交接的输出。

源代码在 src/agents/items.py
@dataclass
class HandoffOutputItem(RunItemBase[TResponseInputItem]):
    """Represents the output of a handoff."""

    raw_item: TResponseInputItem
    """The raw input item that represents the handoff taking place."""

    source_agent: Agent[Any]
    """The agent that made the handoff."""

    target_agent: Agent[Any]
    """The agent that is being handed off to."""

    type: Literal["handoff_output_item"] = "handoff_output_item"

    _source_agent_ref: weakref.ReferenceType[Agent[Any]] | None = field(
        init=False,
        repr=False,
        default=None,
    )
    _target_agent_ref: weakref.ReferenceType[Agent[Any]] | None = field(
        init=False,
        repr=False,
        default=None,
    )

    def __post_init__(self) -> None:
        super().__post_init__()
        # Maintain weak references so downstream code can release the strong references when safe.
        self._source_agent_ref = weakref.ref(self.source_agent)
        self._target_agent_ref = weakref.ref(self.target_agent)

    def __getattribute__(self, name: str) -> Any:
        if name == "source_agent":
            # Provide lazy weakref access like the base `agent` field so HandoffOutputItem
            # callers keep seeing the original agent until GC occurs.
            return self._get_agent_via_weakref("source_agent", "_source_agent_ref")
        if name == "target_agent":
            # Same as above but for the target of the handoff.
            return self._get_agent_via_weakref("target_agent", "_target_agent_ref")
        return super().__getattribute__(name)

    def release_agent(self) -> None:
        super().release_agent()
        if "source_agent" in self.__dict__:
            source_agent = self.__dict__["source_agent"]
            if source_agent is not None:
                self._source_agent_ref = weakref.ref(source_agent)
            # Preserve dataclass fields for repr/asdict while dropping strong refs.
            self.__dict__["source_agent"] = None
        if "target_agent" in self.__dict__:
            target_agent = self.__dict__["target_agent"]
            if target_agent is not None:
                self._target_agent_ref = weakref.ref(target_agent)
            # Preserve dataclass fields for repr/asdict while dropping strong refs.
            self.__dict__["target_agent"] = None

raw_item 实例属性

表示正在进行的交接的原始输入项目。

source_agent 实例属性

source_agent: Agent[Any]

发起交接的代理。

target_agent 实例属性

target_agent: Agent[Any]

The agent that is being handed off to.

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

ToolCallItem dataclass

基础: RunItemBase[Any]

表示工具调用,例如函数调用或计算机操作调用。

源代码在 src/agents/items.py
@dataclass
class ToolCallItem(RunItemBase[Any]):
    """Represents a tool call e.g. a function call or computer action call."""

    raw_item: ToolCallItemTypes
    """The raw tool call item."""

    type: Literal["tool_call_item"] = "tool_call_item"

raw_item 实例属性

原始工具调用项目。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

ToolCallOutputItem dataclass

基础: RunItemBase[Any]

表示工具调用的输出。

源代码在 src/agents/items.py
@dataclass
class ToolCallOutputItem(RunItemBase[Any]):
    """Represents the output of a tool call."""

    raw_item: ToolCallOutputTypes
    """The raw item from the model."""

    output: Any
    """The output of the tool call. This is whatever the tool call returned; the `raw_item`
    contains a string representation of the output.
    """

    type: Literal["tool_call_output_item"] = "tool_call_output_item"

    def to_input_item(self) -> TResponseInputItem:
        """Converts the tool output into an input item for the next model turn.

        Hosted tool outputs (e.g. shell/apply_patch) carry a `status` field for the SDK's
        book-keeping, but the Responses API does not yet accept that parameter. Strip it from the
        payload we send back to the model while keeping the original raw item intact.
        """

        if isinstance(self.raw_item, dict):
            payload = dict(self.raw_item)
            payload_type = payload.get("type")
            if payload_type == "shell_call_output":
                payload.pop("status", None)
                payload.pop("shell_output", None)
                payload.pop("provider_data", None)
            return cast(TResponseInputItem, payload)

        return super().to_input_item()

raw_item 实例属性

raw_item: ToolCallOutputTypes

来自模型的原始项目。

output 实例属性

output: Any

工具调用的输出。 这是工具调用返回的内容;raw_item 包含输出的字符串表示形式。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

to_input_item

to_input_item() -> TResponseInputItem

将工具输出转换为下一个模型轮次的输入项目。

托管工具输出(例如 shell/apply_patch)带有 SDK 的记录保留的 status 字段,但 Responses API 尚未接受该参数。 在将内容发送回模型时,将其从有效负载中删除,同时保留原始 raw_item 不变。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts the tool output into an input item for the next model turn.

    Hosted tool outputs (e.g. shell/apply_patch) carry a `status` field for the SDK's
    book-keeping, but the Responses API does not yet accept that parameter. Strip it from the
    payload we send back to the model while keeping the original raw item intact.
    """

    if isinstance(self.raw_item, dict):
        payload = dict(self.raw_item)
        payload_type = payload.get("type")
        if payload_type == "shell_call_output":
            payload.pop("status", None)
            payload.pop("shell_output", None)
            payload.pop("provider_data", None)
        return cast(TResponseInputItem, payload)

    return super().to_input_item()

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

ReasoningItem dataclass

基础: RunItemBase[ResponseReasoningItem]

表示推理项目。

源代码在 src/agents/items.py
@dataclass
class ReasoningItem(RunItemBase[ResponseReasoningItem]):
    """Represents a reasoning item."""

    raw_item: ResponseReasoningItem
    """The raw reasoning item."""

    type: Literal["reasoning_item"] = "reasoning_item"

raw_item 实例属性

raw_item: ResponseReasoningItem

原始推理项目。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

MCPListToolsItem dataclass

基础: RunItemBase[McpListTools]

表示调用 MCP 服务器以列出工具。

源代码在 src/agents/items.py
@dataclass
class MCPListToolsItem(RunItemBase[McpListTools]):
    """Represents a call to an MCP server to list tools."""

    raw_item: McpListTools
    """The raw MCP list tools call."""

    type: Literal["mcp_list_tools_item"] = "mcp_list_tools_item"

raw_item 实例属性

raw_item: McpListTools

原始 MCP 列出工具调用。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

MCPApprovalRequestItem dataclass

基础: RunItemBase[McpApprovalRequest]

表示请求 MCP 批准。

源代码在 src/agents/items.py
@dataclass
class MCPApprovalRequestItem(RunItemBase[McpApprovalRequest]):
    """Represents a request for MCP approval."""

    raw_item: McpApprovalRequest
    """The raw MCP approval request."""

    type: Literal["mcp_approval_request_item"] = "mcp_approval_request_item"

raw_item 实例属性

raw_item: McpApprovalRequest

原始 MCP 批准请求。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

MCPApprovalResponseItem dataclass

基础: RunItemBase[McpApprovalResponse]

表示对 MCP 批准请求的响应。

源代码在 src/agents/items.py
@dataclass
class MCPApprovalResponseItem(RunItemBase[McpApprovalResponse]):
    """Represents a response to an MCP approval request."""

    raw_item: McpApprovalResponse
    """The raw MCP approval response."""

    type: Literal["mcp_approval_response_item"] = "mcp_approval_response_item"

raw_item 实例属性

raw_item: McpApprovalResponse

原始 MCP 批准响应。

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    if isinstance(self.raw_item, dict):
        # We know that input items are dicts, so we can ignore the type error
        return self.raw_item  # type: ignore
    elif isinstance(self.raw_item, BaseModel):
        # All output items are Pydantic models that can be converted to input items.
        return self.raw_item.model_dump(exclude_unset=True)  # type: ignore
    else:
        raise AgentsException(f"Unexpected raw item type: {type(self.raw_item)}")

CompactionItem dataclass

基础: RunItemBase[TResponseInputItem]

表示来自 responses.compact 的压缩项目。

源代码在 src/agents/items.py
@dataclass
class CompactionItem(RunItemBase[TResponseInputItem]):
    """Represents a compaction item from responses.compact."""

    type: Literal["compaction_item"] = "compaction_item"

    def to_input_item(self) -> TResponseInputItem:
        """Converts this item into an input item suitable for passing to the model."""
        return self.raw_item

agent 实例属性

agent: Agent[Any]

导致生成此项目的主动代理。

raw_item 实例属性

raw_item: T

运行中的原始 Responses 项目。 这始终是输出项目(即 openai.types.responses.ResponseOutputItem)或输入项目(即 openai.types.responses.ResponseInputItemParam)。

to_input_item

to_input_item() -> TResponseInputItem

将此项目转换为适合传递给模型的输入项目。

源代码在 src/agents/items.py
def to_input_item(self) -> TResponseInputItem:
    """Converts this item into an input item suitable for passing to the model."""
    return self.raw_item

release_agent

release_agent() -> None

释放对代理的强引用,同时保留弱引用。

源代码在 src/agents/items.py
def release_agent(self) -> None:
    """Release the strong reference to the agent while keeping a weak reference."""
    if "agent" not in self.__dict__:
        return
    agent = self.__dict__["agent"]
    if agent is None:
        return
    self._agent_ref = weakref.ref(agent) if agent is not None else None
    # Set to None instead of deleting so dataclass repr/asdict keep working.
    self.__dict__["agent"] = None

ModelResponse

源代码在 src/agents/items.py
@pydantic.dataclasses.dataclass
class ModelResponse:
    output: list[TResponseOutputItem]
    """A list of outputs (messages, tool calls, etc) generated by the model"""

    usage: Usage
    """The usage information for the response."""

    response_id: str | None
    """An ID for the response which can be used to refer to the response in subsequent calls to the
    model. Not supported by all model providers.
    If using OpenAI models via the Responses API, this is the `response_id` parameter, and it can
    be passed to `Runner.run`.
    """

    def to_input_items(self) -> list[TResponseInputItem]:
        """Convert the output into a list of input items suitable for passing to the model."""
        # We happen to know that the shape of the Pydantic output items are the same as the
        # equivalent TypedDict input items, so we can just convert each one.
        # This is also tested via unit tests.
        return [it.model_dump(exclude_unset=True) for it in self.output]  # type: ignore

output 实例属性

output: list[TResponseOutputItem]

模型生成的一系列输出(消息、工具调用等)

usage 实例属性

usage: Usage

响应的使用信息。

response_id 实例属性

response_id: str | None

可用于在后续调用模型中引用响应的 ID。 并非所有模型提供程序都支持。 如果使用 Responses API 中的 OpenAI 模型,这是 response_id 参数,可以传递给 Runner.run

to_input_items

to_input_items() -> list[TResponseInputItem]

将输出转换为适合传递给模型的输入项目列表。

源代码在 src/agents/items.py
def to_input_items(self) -> list[TResponseInputItem]:
    """Convert the output into a list of input items suitable for passing to the model."""
    # We happen to know that the shape of the Pydantic output items are the same as the
    # equivalent TypedDict input items, so we can just convert each one.
    # This is also tested via unit tests.
    return [it.model_dump(exclude_unset=True) for it in self.output]  # type: ignore

ItemHelpers

源代码在 src/agents/items.py
class ItemHelpers:
    @classmethod
    def extract_last_content(cls, message: TResponseOutputItem) -> str:
        """Extracts the last text content or refusal from a message."""
        if not isinstance(message, ResponseOutputMessage):
            return ""

        if not message.content:
            return ""
        last_content = message.content[-1]
        if isinstance(last_content, ResponseOutputText):
            return last_content.text
        elif isinstance(last_content, ResponseOutputRefusal):
            return last_content.refusal
        else:
            raise ModelBehaviorError(f"Unexpected content type: {type(last_content)}")

    @classmethod
    def extract_last_text(cls, message: TResponseOutputItem) -> str | None:
        """Extracts the last text content from a message, if any. Ignores refusals."""
        if isinstance(message, ResponseOutputMessage):
            if not message.content:
                return None
            last_content = message.content[-1]
            if isinstance(last_content, ResponseOutputText):
                return last_content.text

        return None

    @classmethod
    def input_to_new_input_list(
        cls, input: str | list[TResponseInputItem]
    ) -> list[TResponseInputItem]:
        """Converts a string or list of input items into a list of input items."""
        if isinstance(input, str):
            return [
                {
                    "content": input,
                    "role": "user",
                }
            ]
        return input.copy()

    @classmethod
    def text_message_outputs(cls, items: list[RunItem]) -> str:
        """Concatenates all the text content from a list of message output items."""
        text = ""
        for item in items:
            if isinstance(item, MessageOutputItem):
                text += cls.text_message_output(item)
        return text

    @classmethod
    def text_message_output(cls, message: MessageOutputItem) -> str:
        """Extracts all the text content from a single message output item."""
        text = ""
        for item in message.raw_item.content:
            if isinstance(item, ResponseOutputText):
                text += item.text
        return text

    @classmethod
    def tool_call_output_item(
        cls, tool_call: ResponseFunctionToolCall, output: Any
    ) -> FunctionCallOutput:
        """Creates a tool call output item from a tool call and its output.

        Accepts either plain values (stringified) or structured outputs using
        input_text/input_image/input_file shapes. Structured outputs may be
        provided as Pydantic models or dicts, or an iterable of such items.
        """

        converted_output = cls._convert_tool_output(output)

        return {
            "call_id": tool_call.call_id,
            "output": converted_output,
            "type": "function_call_output",
        }

    @classmethod
    def _convert_tool_output(cls, output: Any) -> str | ResponseFunctionCallOutputItemListParam:
        """Converts a tool return value into an output acceptable by the Responses API."""

        # If the output is either a single or list of the known structured output types, convert to
        # ResponseFunctionCallOutputItemListParam. Else, just stringify.
        if isinstance(output, (list, tuple)):
            maybe_converted_output_list = [
                cls._maybe_get_output_as_structured_function_output(item) for item in output
            ]
            if all(maybe_converted_output_list):
                return [
                    cls._convert_single_tool_output_pydantic_model(item)
                    for item in maybe_converted_output_list
                    if item is not None
                ]
            else:
                return str(output)
        else:
            maybe_converted_output = cls._maybe_get_output_as_structured_function_output(output)
            if maybe_converted_output:
                return [cls._convert_single_tool_output_pydantic_model(maybe_converted_output)]
            else:
                return str(output)

    @classmethod
    def _maybe_get_output_as_structured_function_output(
        cls, output: Any
    ) -> ValidToolOutputPydanticModels | None:
        if isinstance(output, (ToolOutputText, ToolOutputImage, ToolOutputFileContent)):
            return output
        elif isinstance(output, dict):
            # Require explicit 'type' field in dict to be considered a structured output
            if "type" not in output:
                return None
            try:
                return ValidToolOutputPydanticModelsTypeAdapter.validate_python(output)
            except pydantic.ValidationError:
                logger.debug("dict was not a valid tool output pydantic model")
                return None

        return None

    @classmethod
    def _convert_single_tool_output_pydantic_model(
        cls, output: ValidToolOutputPydanticModels
    ) -> ResponseFunctionCallOutputItemParam:
        if isinstance(output, ToolOutputText):
            return {"type": "input_text", "text": output.text}
        elif isinstance(output, ToolOutputImage):
            # Forward all provided optional fields so the Responses API receives
            # the correct identifiers and settings for the image resource.
            result: ResponseInputImageContentParam = {"type": "input_image"}
            if output.image_url is not None:
                result["image_url"] = output.image_url
            if output.file_id is not None:
                result["file_id"] = output.file_id
            if output.detail is not None:
                result["detail"] = output.detail
            return result
        elif isinstance(output, ToolOutputFileContent):
            # Forward all provided optional fields so the Responses API receives
            # the correct identifiers and metadata for the file resource.
            result_file: ResponseInputFileContentParam = {"type": "input_file"}
            if output.file_data is not None:
                result_file["file_data"] = output.file_data
            if output.file_url is not None:
                result_file["file_url"] = output.file_url
            if output.file_id is not None:
                result_file["file_id"] = output.file_id
            if output.filename is not None:
                result_file["filename"] = output.filename
            return result_file
        else:
            assert_never(output)
            raise ValueError(f"Unexpected tool output type: {output}")

extract_last_content 类方法

extract_last_content(message: TResponseOutputItem) -> str

从消息中提取最后一个文本内容或拒绝。

源代码在 src/agents/items.py
@classmethod
def extract_last_content(cls, message: TResponseOutputItem) -> str:
    """Extracts the last text content or refusal from a message."""
    if not isinstance(message, ResponseOutputMessage):
        return ""

    if not message.content:
        return ""
    last_content = message.content[-1]
    if isinstance(last_content, ResponseOutputText):
        return last_content.text
    elif isinstance(last_content, ResponseOutputRefusal):
        return last_content.refusal
    else:
        raise ModelBehaviorError(f"Unexpected content type: {type(last_content)}")

extract_last_text 类方法

extract_last_text(
    message: TResponseOutputItem,
) -> str | None

从消息中提取最后一个文本内容(如果有)。 忽略拒绝。

源代码在 src/agents/items.py
@classmethod
def extract_last_text(cls, message: TResponseOutputItem) -> str | None:
    """Extracts the last text content from a message, if any. Ignores refusals."""
    if isinstance(message, ResponseOutputMessage):
        if not message.content:
            return None
        last_content = message.content[-1]
        if isinstance(last_content, ResponseOutputText):
            return last_content.text

    return None

input_to_new_input_list 类方法

input_to_new_input_list(
    input: str | list[TResponseInputItem],
) -> list[TResponseInputItem]

将字符串或输入项目列表转换为输入项目列表。

源代码在 src/agents/items.py
@classmethod
def input_to_new_input_list(
    cls, input: str | list[TResponseInputItem]
) -> list[TResponseInputItem]:
    """Converts a string or list of input items into a list of input items."""
    if isinstance(input, str):
        return [
            {
                "content": input,
                "role": "user",
            }
        ]
    return input.copy()

text_message_outputs 类方法

text_message_outputs(items: list[RunItem]) -> str

连接消息输出项目列表中所有文本内容。

源代码在 src/agents/items.py
@classmethod
def text_message_outputs(cls, items: list[RunItem]) -> str:
    """Concatenates all the text content from a list of message output items."""
    text = ""
    for item in items:
        if isinstance(item, MessageOutputItem):
            text += cls.text_message_output(item)
    return text

text_message_output 类方法

text_message_output(message: MessageOutputItem) -> str

从单个消息输出项目中提取所有文本内容。

源代码在 src/agents/items.py
@classmethod
def text_message_output(cls, message: MessageOutputItem) -> str:
    """Extracts all the text content from a single message output item."""
    text = ""
    for item in message.raw_item.content:
        if isinstance(item, ResponseOutputText):
            text += item.text
    return text

tool_call_output_item 类方法

tool_call_output_item(
    tool_call: ResponseFunctionToolCall, output: Any
) -> FunctionCallOutput

从工具调用及其输出创建工具调用输出项目。

接受纯值(字符串化)或使用 input_text/input_image/input_file 形状的结构化输出。 结构化输出可以作为 Pydantic 模型或字典提供,也可以是这些项目的可迭代对象。

源代码在 src/agents/items.py
@classmethod
def tool_call_output_item(
    cls, tool_call: ResponseFunctionToolCall, output: Any
) -> FunctionCallOutput:
    """Creates a tool call output item from a tool call and its output.

    Accepts either plain values (stringified) or structured outputs using
    input_text/input_image/input_file shapes. Structured outputs may be
    provided as Pydantic models or dicts, or an iterable of such items.
    """

    converted_output = cls._convert_tool_output(output)

    return {
        "call_id": tool_call.call_id,
        "output": converted_output,
        "type": "function_call_output",
    }