Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Items

TResponsemodule-attribute

TResponse=Response

A type alias for the Response type from the OpenAI SDK.

TResponseInputItemmodule-attribute

TResponseInputItem=ResponseInputItemParam

A type alias for the ResponseInputItemParam type from the OpenAI SDK.

TResponseOutputItemmodule-attribute

TResponseOutputItem=ResponseOutputItem

A type alias for the ResponseOutputItem type from the OpenAI SDK.

TResponseStreamEventmodule-attribute

TResponseStreamEvent=ResponseStreamEvent

A type alias for the ResponseStreamEvent type from the OpenAI SDK.

ToolCallItemTypesmodule-attribute

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

A type that represents a tool call item.

RunItemBasedataclass

Bases:Generic[T],ABC

Source code insrc/agents/items.py
@dataclassclassRunItemBase(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:ifname=="agent":returnself._get_agent_via_weakref("agent","_agent_ref")returnsuper().__getattribute__(name)defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=Nonedef_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)ifvalueis_MISSING_ATTR_SENTINEL:returnobject.__getattribute__(self,attr_name)ifvalueisnotNone:returnvalueref=object.__getattribute__(self,ref_name)ifrefisnotNone:agent=ref()ifagentisnotNone:returnagentreturnNonedefto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

raw_iteminstance-attribute

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).

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

MessageOutputItemdataclass

Bases:RunItemBase[ResponseOutputMessage]

Represents a message from the LLM.

Source code insrc/agents/items.py
@dataclassclassMessageOutputItem(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_iteminstance-attribute

raw_item:ResponseOutputMessage

The raw response output message.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

HandoffCallItemdataclass

Bases:RunItemBase[ResponseFunctionToolCall]

Represents a tool call for a handoff from one agent to another.

Source code insrc/agents/items.py
@dataclassclassHandoffCallItem(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_iteminstance-attribute

raw_item:ResponseFunctionToolCall

The raw response function tool call that represents the handoff.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

HandoffOutputItemdataclass

Bases:RunItemBase[TResponseInputItem]

Represents the output of a handoff.

Source code insrc/agents/items.py
@dataclassclassHandoffOutputItem(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:ifname=="source_agent":# Provide lazy weakref access like the base `agent` field so HandoffOutputItem# callers keep seeing the original agent until GC occurs.returnself._get_agent_via_weakref("source_agent","_source_agent_ref")ifname=="target_agent":# Same as above but for the target of the handoff.returnself._get_agent_via_weakref("target_agent","_target_agent_ref")returnsuper().__getattribute__(name)defrelease_agent(self)->None:super().release_agent()if"source_agent"inself.__dict__:source_agent=self.__dict__["source_agent"]ifsource_agentisnotNone:self._source_agent_ref=weakref.ref(source_agent)# Preserve dataclass fields for repr/asdict while dropping strong refs.self.__dict__["source_agent"]=Noneif"target_agent"inself.__dict__:target_agent=self.__dict__["target_agent"]iftarget_agentisnotNone:self._target_agent_ref=weakref.ref(target_agent)# Preserve dataclass fields for repr/asdict while dropping strong refs.self.__dict__["target_agent"]=None

raw_iteminstance-attribute

The raw input item that represents the handoff taking place.

source_agentinstance-attribute

source_agent:Agent[Any]

The agent that made the handoff.

target_agentinstance-attribute

target_agent:Agent[Any]

The agent that is being handed off to.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

ToolCallItemdataclass

Bases:RunItemBase[Any]

Represents a tool call e.g. a function call or computer action call.

Source code insrc/agents/items.py
@dataclassclassToolCallItem(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_iteminstance-attribute

The raw tool call item.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

ToolCallOutputItemdataclass

Bases:RunItemBase[Any]

Represents the output of a tool call.

Source code insrc/agents/items.py
@dataclassclassToolCallOutputItem(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"defto_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.        """ifisinstance(self.raw_item,dict):payload=dict(self.raw_item)payload_type=payload.get("type")ifpayload_type=="shell_call_output":payload.pop("status",None)payload.pop("shell_output",None)payload.pop("provider_data",None)returncast(TResponseInputItem,payload)returnsuper().to_input_item()

raw_iteminstance-attribute

raw_item:ToolCallOutputTypes

The raw item from the model.

outputinstance-attribute

output:Any

The output of the tool call. This is whatever the tool call returned; theraw_itemcontains a string representation of the output.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

to_input_item

to_input_item()->TResponseInputItem

Converts the tool output into an input item for the next model turn.

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

Source code insrc/agents/items.py
defto_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.    """ifisinstance(self.raw_item,dict):payload=dict(self.raw_item)payload_type=payload.get("type")ifpayload_type=="shell_call_output":payload.pop("status",None)payload.pop("shell_output",None)payload.pop("provider_data",None)returncast(TResponseInputItem,payload)returnsuper().to_input_item()

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

ReasoningItemdataclass

Bases:RunItemBase[ResponseReasoningItem]

Represents a reasoning item.

Source code insrc/agents/items.py
@dataclassclassReasoningItem(RunItemBase[ResponseReasoningItem]):"""Represents a reasoning item."""raw_item:ResponseReasoningItem"""The raw reasoning item."""type:Literal["reasoning_item"]="reasoning_item"

raw_iteminstance-attribute

raw_item:ResponseReasoningItem

The raw reasoning item.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

MCPListToolsItemdataclass

Bases:RunItemBase[McpListTools]

Represents a call to an MCP server to list tools.

Source code insrc/agents/items.py
@dataclassclassMCPListToolsItem(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_iteminstance-attribute

raw_item:McpListTools

The raw MCP list tools call.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

MCPApprovalRequestItemdataclass

Bases:RunItemBase[McpApprovalRequest]

Represents a request for MCP approval.

Source code insrc/agents/items.py
@dataclassclassMCPApprovalRequestItem(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_iteminstance-attribute

raw_item:McpApprovalRequest

The raw MCP approval request.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

MCPApprovalResponseItemdataclass

Bases:RunItemBase[McpApprovalResponse]

Represents a response to an MCP approval request.

Source code insrc/agents/items.py
@dataclassclassMCPApprovalResponseItem(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_iteminstance-attribute

raw_item:McpApprovalResponse

The raw MCP approval response.

agentinstance-attribute

agent:Agent[Any]

The agent whose run caused this item to be generated.

release_agent

release_agent()->None

Release the strong reference to the agent while keeping a weak reference.

Source code insrc/agents/items.py
defrelease_agent(self)->None:"""Release the strong reference to the agent while keeping a weak reference."""if"agent"notinself.__dict__:returnagent=self.__dict__["agent"]ifagentisNone:returnself._agent_ref=weakref.ref(agent)ifagentisnotNoneelseNone# Set to None instead of deleting so dataclass repr/asdict keep working.self.__dict__["agent"]=None

to_input_item

to_input_item()->TResponseInputItem

Converts this item into an input item suitable for passing to the model.

Source code insrc/agents/items.py
defto_input_item(self)->TResponseInputItem:"""Converts this item into an input item suitable for passing to the model."""ifisinstance(self.raw_item,dict):# We know that input items are dicts, so we can ignore the type errorreturnself.raw_item# type: ignoreelifisinstance(self.raw_item,BaseModel):# All output items are Pydantic models that can be converted to input items.returnself.raw_item.model_dump(exclude_unset=True)# type: ignoreelse:raiseAgentsException(f"Unexpected raw item type:{type(self.raw_item)}")

ModelResponse

Source code insrc/agents/items.py
@pydantic.dataclasses.dataclassclassModelResponse: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`.    """defto_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)foritinself.output]# type: ignore

outputinstance-attribute

output:list[TResponseOutputItem]

A list of outputs (messages, tool calls, etc) generated by the model

usageinstance-attribute

usage:Usage

The usage information for the response.

response_idinstance-attribute

response_id:str|None

An ID for the response which can be used to refer to the response in subsequent calls to themodel. Not supported by all model providers.If using OpenAI models via the Responses API, this is theresponse_id parameter, and it canbe passed toRunner.run.

to_input_items

to_input_items()->list[TResponseInputItem]

Convert the output into a list of input items suitable for passing to the model.

Source code insrc/agents/items.py
defto_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)foritinself.output]# type: ignore

ItemHelpers

Source code insrc/agents/items.py
classItemHelpers:@classmethoddefextract_last_content(cls,message:TResponseOutputItem)->str:"""Extracts the last text content or refusal from a message."""ifnotisinstance(message,ResponseOutputMessage):return""ifnotmessage.content:return""last_content=message.content[-1]ifisinstance(last_content,ResponseOutputText):returnlast_content.textelifisinstance(last_content,ResponseOutputRefusal):returnlast_content.refusalelse:raiseModelBehaviorError(f"Unexpected content type:{type(last_content)}")@classmethoddefextract_last_text(cls,message:TResponseOutputItem)->str|None:"""Extracts the last text content from a message, if any. Ignores refusals."""ifisinstance(message,ResponseOutputMessage):ifnotmessage.content:returnNonelast_content=message.content[-1]ifisinstance(last_content,ResponseOutputText):returnlast_content.textreturnNone@classmethoddefinput_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."""ifisinstance(input,str):return[{"content":input,"role":"user",}]returninput.copy()@classmethoddeftext_message_outputs(cls,items:list[RunItem])->str:"""Concatenates all the text content from a list of message output items."""text=""foriteminitems:ifisinstance(item,MessageOutputItem):text+=cls.text_message_output(item)returntext@classmethoddeftext_message_output(cls,message:MessageOutputItem)->str:"""Extracts all the text content from a single message output item."""text=""foriteminmessage.raw_item.content:ifisinstance(item,ResponseOutputText):text+=item.textreturntext@classmethoddeftool_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",}@classmethoddef_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.ifisinstance(output,(list,tuple)):maybe_converted_output_list=[cls._maybe_get_output_as_structured_function_output(item)foriteminoutput]ifall(maybe_converted_output_list):return[cls._convert_single_tool_output_pydantic_model(item)foriteminmaybe_converted_output_listifitemisnotNone]else:returnstr(output)else:maybe_converted_output=cls._maybe_get_output_as_structured_function_output(output)ifmaybe_converted_output:return[cls._convert_single_tool_output_pydantic_model(maybe_converted_output)]else:returnstr(output)@classmethoddef_maybe_get_output_as_structured_function_output(cls,output:Any)->ValidToolOutputPydanticModels|None:ifisinstance(output,(ToolOutputText,ToolOutputImage,ToolOutputFileContent)):returnoutputelifisinstance(output,dict):# Require explicit 'type' field in dict to be considered a structured outputif"type"notinoutput:returnNonetry:returnValidToolOutputPydanticModelsTypeAdapter.validate_python(output)exceptpydantic.ValidationError:logger.debug("dict was not a valid tool output pydantic model")returnNonereturnNone@classmethoddef_convert_single_tool_output_pydantic_model(cls,output:ValidToolOutputPydanticModels)->ResponseFunctionCallOutputItemParam:ifisinstance(output,ToolOutputText):return{"type":"input_text","text":output.text}elifisinstance(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"}ifoutput.image_urlisnotNone:result["image_url"]=output.image_urlifoutput.file_idisnotNone:result["file_id"]=output.file_idifoutput.detailisnotNone:result["detail"]=output.detailreturnresultelifisinstance(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"}ifoutput.file_dataisnotNone:result_file["file_data"]=output.file_dataifoutput.file_urlisnotNone:result_file["file_url"]=output.file_urlifoutput.file_idisnotNone:result_file["file_id"]=output.file_idifoutput.filenameisnotNone:result_file["filename"]=output.filenamereturnresult_fileelse:assert_never(output)raiseValueError(f"Unexpected tool output type:{output}")

extract_last_contentclassmethod

extract_last_content(message:TResponseOutputItem)->str

Extracts the last text content or refusal from a message.

Source code insrc/agents/items.py
@classmethoddefextract_last_content(cls,message:TResponseOutputItem)->str:"""Extracts the last text content or refusal from a message."""ifnotisinstance(message,ResponseOutputMessage):return""ifnotmessage.content:return""last_content=message.content[-1]ifisinstance(last_content,ResponseOutputText):returnlast_content.textelifisinstance(last_content,ResponseOutputRefusal):returnlast_content.refusalelse:raiseModelBehaviorError(f"Unexpected content type:{type(last_content)}")

extract_last_textclassmethod

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

Extracts the last text content from a message, if any. Ignores refusals.

Source code insrc/agents/items.py
@classmethoddefextract_last_text(cls,message:TResponseOutputItem)->str|None:"""Extracts the last text content from a message, if any. Ignores refusals."""ifisinstance(message,ResponseOutputMessage):ifnotmessage.content:returnNonelast_content=message.content[-1]ifisinstance(last_content,ResponseOutputText):returnlast_content.textreturnNone

input_to_new_input_listclassmethod

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

Converts a string or list of input items into a list of input items.

Source code insrc/agents/items.py
@classmethoddefinput_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."""ifisinstance(input,str):return[{"content":input,"role":"user",}]returninput.copy()

text_message_outputsclassmethod

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

Concatenates all the text content from a list of message output items.

Source code insrc/agents/items.py
@classmethoddeftext_message_outputs(cls,items:list[RunItem])->str:"""Concatenates all the text content from a list of message output items."""text=""foriteminitems:ifisinstance(item,MessageOutputItem):text+=cls.text_message_output(item)returntext

text_message_outputclassmethod

text_message_output(message:MessageOutputItem)->str

Extracts all the text content from a single message output item.

Source code insrc/agents/items.py
@classmethoddeftext_message_output(cls,message:MessageOutputItem)->str:"""Extracts all the text content from a single message output item."""text=""foriteminmessage.raw_item.content:ifisinstance(item,ResponseOutputText):text+=item.textreturntext

tool_call_output_itemclassmethod

tool_call_output_item(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 usinginput_text/input_image/input_file shapes. Structured outputs may beprovided as Pydantic models or dicts, or an iterable of such items.

Source code insrc/agents/items.py
@classmethoddeftool_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",}

[8]ページ先頭

©2009-2025 Movatter.jp