Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Openai Openai agents python Runner Run

From Leeroopedia
Property Value
Implementation Name Runner Run
SDK OpenAI Agents Python
Repository openai-agents-python
Source File src/agents/run.py
Line Range L154-231
Import from agents import Runner
Type Async classmethod

Overview

The Runner.run() classmethod is the primary entry point for executing an agent in the OpenAI Agents Python SDK. It accepts an agent and input, orchestrates the turn-based execution loop, and returns a RunResult containing the final output, generated items, and execution metadata. This method is asynchronous and must be awaited.

Code Reference

Source Location

Property Value
File src/agents/run.py
Class Runner
Method run
Lines 154-231

Signature

class Runner:
    @classmethod
    async def run(
        cls,
        starting_agent: Agent[TContext],
        input: str | list[TResponseInputItem] | RunState[TContext],
        *,
        context: TContext | None = None,
        max_turns: int = DEFAULT_MAX_TURNS,
        hooks: RunHooks[TContext] | None = None,
        run_config: RunConfig | None = None,
        error_handlers: RunErrorHandlers[TContext] | None = None,
        previous_response_id: str | None = None,
        auto_previous_response_id: bool = False,
        conversation_id: str | None = None,
        session: Session | None = None,
    ) -> RunResult:

Import Statement

from agents import Runner

I/O Contract

Inputs

Parameter Type Default Description
starting_agent Agent[TContext] (required) The agent to begin execution with.
input list[TResponseInputItem] | RunState[TContext] (required) The initial input. A string is treated as a user message. A list provides full conversation history. A RunState resumes an interrupted run.
context None None A mutable context object shared across the execution lifecycle (tools, guardrails, handoffs).
max_turns int DEFAULT_MAX_TURNS (10) Maximum number of turns (model invocations) before raising MaxTurnsExceeded.
hooks None None Lifecycle callbacks for run-level events (agent start, agent end, tool start, tool end).
run_config None None Global settings for the run, including tracing configuration, model provider, and overrides.
error_handlers None None Custom error handlers keyed by error kind. Currently supports max_turns.
previous_response_id None None ID of the previous response for server-managed conversation continuity via the Responses API.
auto_previous_response_id bool False If True, automatically tracks and passes the previous response ID between turns.
conversation_id None None Server-side conversation ID for reading and writing items to a persistent conversation.
session None None A session object for automatic client-side conversation history management.

Output

Type Description
RunResult Contains final_output, new_items, raw_responses, last_agent, input_guardrail_results, output_guardrail_results, interruptions, and context_wrapper.

Exceptions

Exception Condition
MaxTurnsExceeded Raised when max_turns is exceeded and no custom error handler is provided.
GuardrailTripwireTriggered Raised when an input or output guardrail tripwire is activated.

Execution Flow

The run() method delegates to an internal AgentRunner that implements the following loop:

  1. Assemble model input: system instructions, conversation history, tool schemas, output schema.
  2. Invoke the model and receive a response with output items.
  3. Process output items:
    • Final output: Terminate the loop and return the result.
    • Handoff: Switch to the target agent and continue the loop.
    • Tool calls: Execute tools, append results to history, and re-invoke the model.
    • Interruption: Pause execution and return the result with pending approval items.
  4. If max_turns is exceeded, raise MaxTurnsExceeded or invoke the error handler.

Usage Examples

Simple String Input

from agents import Agent, Runner

agent = Agent(name="assistant", instructions="You are helpful.")
result = await Runner.run(agent, "What is the capital of France?")
print(result.final_output)

With Context Object

from dataclasses import dataclass
from agents import Agent, Runner

@dataclass
class UserContext:
    user_id: str
    preferences: dict

ctx = UserContext(user_id="123", preferences={"language": "en"})
result = await Runner.run(agent, "Show my settings", context=ctx)

Multi-Turn Conversation

result1 = await Runner.run(agent, "My name is Alice.")
next_input = result1.to_input_list()
next_input.append({"role": "user", "content": "What is my name?"})
result2 = await Runner.run(agent, next_input)
print(result2.final_output)  # Should reference "Alice"

Synchronous Invocation

# For non-async contexts, use run_sync:
result = Runner.run_sync(agent, "Hello, world!")
print(result.final_output)

Related Pages

Page Connections

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