OpenAI Agents Python 21 files ยท 0 subfolders
Copy to Workspace 04_ITEMS_SYSTEM Shared from "OpenAI Agents Python" on Inkdown
Items System - Comprehensive Deep Dive
Overview
The Items system is the fundamental data structure that represents everything that happens during an agent run. Every message, tool call, handoff, and model response is represented as an "Item". Think of Items as the "ledger" or "transaction log" of an agent run - they record every event in a structured, serializable format.
Core Concepts
What is an Item?
An Item is a structured representation of an event that occurs during an agent run. Items are:
Typed - Each item has a specific type (message, tool call, handoff, etc.)
Serializable - Can be converted to/from JSON
Traceable - Each item can be traced back to the agent that created it
Convertible - Can be converted to input items for the model
Why Items Matter
Audit Trail - Complete record of what happened during a run
01_AGENT_SYSTEM.md
Session Persistence - Items are saved to sessions for conversation history
Debugging - Inspect items to understand agent behavior
Replay - Items can be replayed to reproduce runs
Analysis - Analyze patterns in agent behavior
Tracing - Items are the basis for trace spans
Item Types
MessageOutputItem Represents a message from the LLM:
When the LLM generates a message response
After tool execution when the LLM responds
When an agent produces final output
agent - The agent that generated this message
raw_item - The raw OpenAI ResponseOutputMessage object
type - Always "message_output_item"
ToolCallItem Represents a request to call a tool:
When the LLM decides to call a tool
For each tool call in a multi-tool invocation
agent - The agent that made the tool call
raw_item - The raw tool call object
type - The specific tool type (function, computer, shell, etc.)
ToolCallOutputItem Represents the result of a tool execution:
After a tool is executed
When a tool error occurs
When a tool is rejected (approval denied)
agent - The agent that called the tool
raw_item - The raw output item
output - The tool's output (as string)
HandoffCallItem Represents a handoff to another agent:
When the LLM calls a handoff tool
When an agent delegates to another agent
agent - The agent making the handoff
raw_item - The handoff tool call
target_agent - The agent being handed off to
HandoffOutputItem Represents the result of a handoff:
After a handoff completes
When the target agent produces output
ReasoningItem Represents model reasoning (for reasoning models like GPT-5):
When a reasoning model produces reasoning content
Before the final response
agent - The agent that produced reasoning
raw_item - The raw reasoning item
summary - Summary of the reasoning
ToolApprovalItem Represents a tool approval request (human-in-the-loop):
When a tool requires approval
When execution pauses for human review
agent - The agent that called the tool
tool_name - Name of the tool
tool_arguments - Arguments passed to the tool
call_id - Unique call ID
MCPApprovalRequestItem Represents an MCP tool approval request:
When an MCP tool requires approval
Before MCP tool execution
MCPApprovalResponseItem Represents the response to an MCP approval request:
After human approves/rejects MCP tool
Before actual MCP tool execution
ToolSearchCallItem Represents a tool search request (Responses API):
When the model uses tool search
To find relevant tools
ToolSearchOutputItem Represents tool search results:
After tool search completes
With search results
CompactionItem Represents conversation compaction (for long conversations):
When conversation history is compacted
To reduce token usage while preserving context
Item Base Class
RunItemBase All items inherit from RunItemBase:
Agent Reference - Every item knows which agent created it
Weak References - Uses weak references to avoid memory leaks
Type Generic - Generic over the raw item type
Convertible - Can convert to input items
Memory Management Items use weak references to agents to prevent memory leaks:
Long-running sessions with many items
Prevents agents from being kept alive by old items
Still allows debugging with agent information
Item Conversion
to_input_item() Every item can be converted to an input item for the model:
Why conversion is needed:
Items are output format (what came out)
Input items are input format (what goes in)
Conversion enables replay and session persistence
Different formats for output vs input
Dict items - Returned as-is (already input format)
Pydantic items - Converted using model_dump(exclude_unset=True)
Custom items - Must implement to_input_item()
run_items_to_input_items() Convert multiple items to input items:
Session persistence
Replay functionality
Handoff history preparation
Item Helpers
ItemHelpers Class Utility class for working with items:
get_tool_calls(items) - Extract tool call items
get_messages(items) - Extract message items
get_text_content(item) - Get text from a message
to_input_list(items) - Convert items to input list
get_function_call_outputs(items) - Get tool outputs
Model Response
ModelResponse Class Represents a complete model response:
After each model call
Contains all output items from the call
Includes usage information
response - Full OpenAI Response object
request_id - Request identifier
usage - Token usage data
agent - Agent that made the request
Item Lifecycle
Creation Flow
Persistence Flow
Replay Flow
Item Serialization
JSON Serialization Items can be serialized to JSON:
Serialization considerations:
Raw items are Pydantic models with built-in serialization
Agent references are not serialized (use weak references)
Context is not serialized (user data)
Only the raw item data is serialized
RunState Serialization Items are part of RunState serialization:
All generated items
Agent identities (name, handoff description)
Tool call metadata
Usage information
Guardrail results
Item Filtering
Filtering by Type
Filtering by Agent
Filtering by Tool Name
Item Analysis
Analyzing Tool Usage
Analyzing Turn Structure
Analyzing Agent Handoffs
Item and Session Integration
Session Items Sessions store items as conversation history:
Compaction Items For long conversations, items are compacted:
Item and Tracing
Trace Spans from Items Each item can create a trace span:
Item Metadata in Traces Items include metadata in traces:
Best Practices
1. Use Item Helpers Use the provided helper functions:
2. Check Item Types Always check item types before accessing:
3. Release Agent References Release agent references when done:
4. Convert to Input Items Use proper conversion for replay:
5. Filter Appropriately Filter items based on your needs:
Common Patterns
1. Extract Tool Results
2. Count Agent Turns
3. Find Handoff Points
4. Calculate Token Usage
Summary The Items system is the foundation of run representation. Key takeaways:
Items represent all events in an agent run
Item types include messages, tool calls, handoffs, reasoning, etc.
RunItemBase is the base class for all items
Weak references prevent memory leaks
Conversion enables replay and persistence
ItemHelpers provide utility functions
ModelResponse wraps a complete model response
Serialization enables state persistence
Filtering allows item analysis
Sessions store items as conversation history
Compaction reduces token usage for long conversations
Tracing uses items for observability
Analysis enables pattern detection
Replay enables reproducing runs
Debugging is easier with item inspection
Agent references track which agent created each item
Tool metadata tracks tool usage
Handoff tracking follows agent delegation
Usage tracking monitors token consumption
Type safety ensures correct item handling
Understanding Items is essential for debugging, persistence, and analysis of agent runs.