Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai agents python RunResult To State

From Leeroopedia

Overview

This page documents the concrete API for capturing an interrupted agent run's state via RunResult.to_state() and the RunState constructor.

RunResult.to_state() Method

Defined in src/agents/result.py (lines 268-313):

class RunResult:
    def to_state(self) -> RunState[Any]:
        """Create a RunState from this result to resume execution.

        This is useful when the run was interrupted (e.g., for tool approval). You can
        approve or reject the tool calls on the returned state, then pass it back to
        Runner.run() to continue execution.

        Returns:
            A RunState that can be used to resume the run.
        """

Internal Behavior

The method constructs a RunState and then delegates to _populate_state_from_result(), which copies the following internal fields:

  • _current_turn: Preserves the turn counter so the resumed run respects the original turn budget
  • _last_processed_response: The model's processed response at the point of interruption
  • _current_turn_persisted_item_count: Tracks how many items from the current turn were already written to the session
  • _tool_use_tracker_snapshot: Records which tools each agent has used
  • _conversation_id, _previous_response_id, _auto_previous_response_id: Server-managed conversation tracking state

RunState Constructor

Defined in src/agents/run_state.py (lines 175-206):

@dataclass
class RunState(Generic[TContext, TAgent]):
    """Serializable snapshot of an agent run, including context, usage, and interruptions."""

    def __init__(
        self,
        context: RunContextWrapper[TContext],
        original_input: str | list[Any],
        starting_agent: TAgent,
        max_turns: int = 10,
        *,
        conversation_id: str | None = None,
        previous_response_id: str | None = None,
        auto_previous_response_id: bool = False,
    ):
        """Initialize a new RunState."""

Constructor Parameters

  • context: The RunContextWrapper that tracks approvals, usage, and other metadata
  • original_input: The user's original input (string or list of input items) prior to any processing
  • starting_agent: The agent that was active at the point of interruption
  • max_turns: Maximum allowed turns before forcing termination (default: 10)
  • conversation_id: Optional conversation identifier for server-managed conversation tracking
  • previous_response_id: Optional response identifier of the last server-managed response
  • auto_previous_response_id: Whether the previous response ID should be automatically tracked

Import

from agents import RunResult, RunState

Example: Capturing State After Interruption

from agents import Agent, Runner

agent = Agent(
    name="admin",
    instructions="Execute commands.",
    tools=[shell_tool],
)

result = await Runner.run(agent, "Delete the temp files")

if result.interruptions:
    # Capture the run state for later resumption
    state = result.to_state()

    # Inspect pending approvals
    for item in state.get_interruptions():
        print(f"Tool: {item.tool_name}")
        print(f"Raw item: {item.raw_item}")

Example: Using to_state() in a Web Application

from agents import Agent, Runner

async def handle_agent_request(user_message: str):
    """Run the agent and return approval requests if any."""
    result = await Runner.run(agent, user_message)

    if result.interruptions:
        state = result.to_state()
        # In a real application, serialize and store the state
        # for later retrieval when the user responds
        pending = []
        for item in state.get_interruptions():
            pending.append({
                "tool_name": item.tool_name,
                "raw_item": str(item.raw_item),
            })
        return {"status": "needs_approval", "pending": pending}

    return {"status": "complete", "output": result.final_output}

Key RunState Fields

The RunState dataclass holds the following internal fields:

Field Type Description
_current_turn int Current turn number in the conversation
_current_agent None The agent currently handling the conversation
_original_input list[Any] Original user input prior to processing
_generated_items list[RunItem] Items for building model input on resumption
_session_items list[RunItem] Full unfiltered run items for session history
_model_responses list[ModelResponse] All model responses received so far
_max_turns int Maximum allowed turns (default 10)
_current_step None Current step if the run is interrupted

Source References

  • src/agents/result.py lines 268-313: RunResult.to_state()
  • src/agents/run_state.py lines 112-207: RunState dataclass and constructor

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment