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 RunContextWrapper

From Leeroopedia
Revision as of 11:44, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Openai_Openai_agents_python_RunContextWrapper.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains AI_Agents, State_Management, Orchestration
Last Updated 2026-02-11 15:00 GMT

Overview

RunContextWrapper is a generic dataclass that wraps a user-defined context object with additional runtime metadata. It provides the primary mechanism for sharing mutable state across agents, tools, handoffs, guardrails, and lifecycle hooks within a single agent run.

Import

from agents import RunContextWrapper

Class Signature

@dataclass(eq=False)
class RunContextWrapper(Generic[TContext]):
    context: TContext
    usage: Usage = field(default_factory=Usage)
    turn_input: list[TResponseInputItem] = field(default_factory=list)
    _approvals: dict[str, _ApprovalRecord] = field(default_factory=dict)
    tool_input: Any | None = None

Fields

Field Type Default Description
context TContext required The user-provided context object. Can be any type (dataclass, Pydantic model, plain class, etc.).
usage Usage Usage() Tracks token consumption (input tokens, output tokens) across the entire run.
turn_input list[TResponseInputItem] [] The list of input items for the current turn. Updated by the run loop.
_approvals dict[str, _ApprovalRecord] {} Internal dictionary tracking tool approval/rejection state for human-in-the-loop workflows.
tool_input None None The raw input for the currently executing tool, set by the run loop during tool execution.

Key Methods

approve_tool

def approve_tool(self, approval_item, always_approve: bool = False) -> None

Records approval for a specific tool call. If always_approve is True, all future calls to the same tool name are automatically approved.

reject_tool

def reject_tool(self, approval_item, always_reject: bool = False) -> None

Records rejection for a specific tool call. If always_reject is True, all future calls to the same tool name are automatically rejected.

is_tool_approved

def is_tool_approved(self, tool_name: str, call_id: str) -> bool | None

Checks whether a tool call is approved, rejected, or undecided. Returns True if approved, False if rejected, and None if no decision has been recorded for this tool call.

Usage Examples

Basic Context with Tools

from dataclasses import dataclass
from agents import Agent, Runner, RunContextWrapper, function_tool

@dataclass
class MyContext:
    user_id: str
    request_count: int = 0

@function_tool
def get_user_info(ctx: RunContextWrapper[MyContext]) -> str:
    ctx.context.request_count += 1
    return f"User: {ctx.context.user_id}, requests: {ctx.context.request_count}"

agent = Agent(name="assistant", instructions="Help the user.", tools=[get_user_info])
my_ctx = MyContext(user_id="user_123")
result = await Runner.run(agent, "Who am I?", context=my_ctx)

Shared State Across Multiple Tools

from dataclasses import dataclass, field
from agents import Agent, Runner, RunContextWrapper, function_tool

@dataclass
class SessionContext:
    user_id: str
    retrieved_items: list[str] = field(default_factory=list)
    total_cost: float = 0.0

@function_tool
def search_catalog(ctx: RunContextWrapper[SessionContext], query: str) -> str:
    results = ["item_a", "item_b"]
    ctx.context.retrieved_items.extend(results)
    return f"Found: {results}"

@function_tool
def calculate_total(ctx: RunContextWrapper[SessionContext]) -> str:
    ctx.context.total_cost = len(ctx.context.retrieved_items) * 9.99
    return f"Total: ${ctx.context.total_cost}"

agent = Agent(
    name="shop_assistant",
    instructions="Help the user shop.",
    tools=[search_catalog, calculate_total],
)

Accessing Usage Tracking

from agents import Agent, Runner

result = await Runner.run(agent, "Hello!")
print(f"Input tokens: {result.context_wrapper.usage.input_tokens}")
print(f"Output tokens: {result.context_wrapper.usage.output_tokens}")

Source Reference

Source: src/agents/run_context.py:L34-215

Related Pages

GitHub URL

Source: run_context.py

Page Connections

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