### Full Voice Pipeline Example Source: https://github.com/openai/openai-agents-python/blob/main/docs/voice/quickstart.md A complete example demonstrating agent setup, voice pipeline initialization, audio input simulation, and audio output playback. Includes a sample tool and handoff functionality. ```python import asyncio import random import numpy as np import sounddevice as sd from agents import ( Agent, function_tool, set_tracing_disabled, ) from agents.voice import ( AudioInput, SingleAgentVoiceWorkflow, VoicePipeline, ) from agents.extensions.handoff_prompt import prompt_with_handoff_instructions @function_tool def get_weather(city: str) -> str: """Get the weather for a given city.""" print(f"[debug] get_weather called with city: {city}") choices = ["sunny", "cloudy", "rainy", "snowy"] return f"The weather in {city} is {random.choice(choices)}." spanish_agent = Agent( name="Spanish", handoff_description="A Spanish-speaking agent.", instructions=prompt_with_handoff_instructions( "You're speaking to a human, so be polite and concise. Speak in Spanish.", ), model="gpt-5.5", ) agent = Agent( name="Assistant", instructions=prompt_with_handoff_instructions( "You're speaking to a human, so be polite and concise. If the user speaks in Spanish, hand off to the Spanish agent.", ), model="gpt-5.5", handoffs=[spanish_agent], tools=[get_weather], ) async def main(): pipeline = VoicePipeline(workflow=SingleAgentVoiceWorkflow(agent)) buffer = np.zeros(24000 * 3, dtype=np.int16) audio_input = AudioInput(buffer=buffer) result = await pipeline.run(audio_input) # Create an audio player using `sounddevice` player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16) player.start() # Play the audio stream as it comes in async for event in result.stream(): if event.type == "voice_stream_event_audio": player.write(event.data) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### NoopComputer and Agent Setup with Tools Source: https://github.com/openai/openai-agents-python/blob/main/docs/tools.md This example demonstrates how to set up a local agent with a NoopComputer (a mock implementation of AsyncComputer) and other tools like ShellTool and ApplyPatchTool. It's useful for testing agent behavior without actual computer interaction. ```python from agents import Agent, ApplyPatchTool, ShellTool from agents.computer import AsyncComputer from agents.editor import ApplyPatchResult, ApplyPatchOperation, ApplyPatchEditor class NoopComputer(AsyncComputer): environment = "browser" dimensions = (1024, 768) async def screenshot(self): return "" async def click(self, x, y, button): ... async def double_click(self, x, y): ... async def scroll(self, x, y, scroll_x, scroll_y): ... async def type(self, text): ... async def wait(self): ... async def move(self, x, y): ... async def keypress(self, keys): ... async def drag(self, path): ... class NoopEditor(ApplyPatchEditor): async def create_file(self, op: ApplyPatchOperation): return ApplyPatchResult(status="completed") async def update_file(self, op: ApplyPatchOperation): return ApplyPatchResult(status="completed") async def delete_file(self, op: ApplyPatchOperation): return ApplyPatchResult(status="completed") async def run_shell(request): return "shell output" agent = Agent( name="Local tools agent", tools=[ ShellTool(executor=run_shell), ApplyPatchTool(editor=NoopEditor()), # ComputerTool expects a Computer/AsyncComputer implementation; omitted here for brevity. ], ) ``` -------------------------------- ### Run Sandbox Resume Example Locally Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/sandbox_resume/README.md Execute the sandbox resume tutorial using `uv run python` to start the agent flow with default settings. ```bash uv run python examples/sandbox/tutorials/sandbox_resume/main.py ``` -------------------------------- ### Start Filesystem MCP Server with npx Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/filesystem_example/README.md This `npx` command initializes the filesystem MCP server locally. It requires a `` argument, which specifies the directory the server will have access to, enabling tools like `list_directory()` and `read_file()` for the agent. ```bash npx -y "@modelcontextprotocol/server-filesystem" ``` -------------------------------- ### Full Example: Sandbox Coding Task Source: https://github.com/openai/openai-agents-python/blob/main/docs/sandbox/guide.md This Python script provides a complete example of setting up and running a sandbox agent for a coding task. It includes agent configuration, capability setup, and execution logic. This is a good starting point for similar tasks. ```Python import asyncio from pathlib import Path from agents import ModelSettings, Runner from agents.run import RunConfig from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig from agents.sandbox.capabilities import ( Capabilities, LocalDirLazySkillSource, Skills, ) from agents.sandbox.entries import LocalDir from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient EXAMPLE_DIR = Path(__file__).resolve().parent HOST_REPO_DIR = EXAMPLE_DIR / "repo" HOST_SKILLS_DIR = EXAMPLE_DIR / "skills" TARGET_TEST_CMD = "sh tests/test_credit_note.sh" def build_agent(model: str) -> SandboxAgent[None]: return SandboxAgent( name="Sandbox engineer", model=model, instructions=( "Inspect the repo, make the smallest correct change, run the most relevant checks, " "and summarize the file changes and risks. " "Read `repo/task.md` before editing files. Stay grounded in the repository, preserve " "existing behavior, and mention the exact verification command you ran. " "Use the `$credit-note-fixer` skill before editing files. If the repo lives under " "`repo/`, remember that `apply_patch` paths stay relative to the sandbox workspace " "root, so edits still target `repo/...`." ), # Put repos and task files in the manifest. default_manifest=Manifest( entries={ "repo": LocalDir(src=HOST_REPO_DIR), } ), capabilities=Capabilities.default() + [ Skills( lazy_from=LocalDirLazySkillSource( # This is a host path read by the SDK process. # Requested skills are copied into `skills_path` in the sandbox. source=LocalDir(src=HOST_SKILLS_DIR), ) ), ], model_settings=ModelSettings(tool_choice="required"), ) async def main(model: str, prompt: str) -> None: result = await Runner.run( build_agent(model), prompt, run_config=RunConfig( sandbox=SandboxRunConfig(client=UnixLocalSandboxClient()), workflow_name="Sandbox coding example", ), ) print(result.final_output) if __name__ == "__main__": asyncio.run( main( model="gpt-5.5", prompt=( "Open `repo/task.md`, use the `$credit-note-fixer` skill, fix the bug, " f"run `{TARGET_TEST_CMD}`, and summarize the change." ), ) ) ``` -------------------------------- ### Run Model Provider Examples Source: https://github.com/openai/openai-agents-python/blob/main/examples/model_providers/README.md Execute various model provider examples using 'uv run' to demonstrate routing through adapter layers. ```bash uv run examples/model_providers/any_llm_provider.py ``` ```bash uv run examples/model_providers/any_llm_auto.py ``` ```bash uv run examples/model_providers/litellm_provider.py ``` ```bash uv run examples/model_providers/litellm_auto.py ``` -------------------------------- ### Run Sandbox Resume Example in Docker Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/sandbox_resume/README.md Build the necessary Docker image for the sandbox tutorials, then run the sandbox resume example within a Docker container. ```bash docker build --tag sandbox-tutorials:latest examples/sandbox/tutorials ``` ```bash uv run python examples/sandbox/tutorials/sandbox_resume/main.py --docker ``` -------------------------------- ### Run Financial Research Agent Example (Bash) Source: https://github.com/openai/openai-agents-python/blob/main/examples/financial_research_agent/README.md This bash command executes the financial research agent example. It uses Python's module runner to start the main script, initiating the agent's multi-step workflow for financial analysis. ```bash python -m examples.financial_research_agent.main ``` -------------------------------- ### Run Basic Sandbox Example with Modal Backend Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Executes the basic sandbox example script using Modal as the backend. ```bash uv run python examples/sandbox/basic.py \ --backend modal ``` -------------------------------- ### Run Cloudflare Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Executes the Cloudflare sandbox example script, optionally streaming output. ```bash uv run python examples/sandbox/extensions/cloudflare_runner.py --stream ``` -------------------------------- ### Run E2B Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Executes the E2B sandbox example script, optionally streaming output. ```bash uv run python examples/sandbox/extensions/e2b_runner.py --stream ``` -------------------------------- ### Run MCP get_all_mcp_tools Example with uv Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/get_all_mcp_tools_example/README.md This command executes the Python `get_all_mcp_tools` example using the `uv` tool. It requires `npx` to be available on your PATH and `OPENAI_API_KEY` to be set in your environment for model calls. ```bash uv run python examples/mcp/get_all_mcp_tools_example/main.py ``` -------------------------------- ### Quick Start: Initialize and Run Agent with AdvancedSQLiteSession (Python) Source: https://github.com/openai/openai-agents-python/blob/main/docs/sessions/advanced_sqlite_session.md This example demonstrates how to initialize an `AdvancedSQLiteSession` and use it with an `Agent` and `Runner` to manage a multi-turn conversation. It shows creating an agent, setting up the advanced session with a database path, running conversation turns, and crucially, storing usage data after each run to enable analytics. ```python from agents import Agent, Runner from agents.extensions.memory import AdvancedSQLiteSession # Create agent agent = Agent( name="Assistant", instructions="Reply very concisely.", ) # Create an advanced session session = AdvancedSQLiteSession( session_id="conversation_123", db_path="conversations.db", create_tables=True ) # First conversation turn result = await Runner.run( agent, "What city is the Golden Gate Bridge in?", session=session ) print(result.final_output) # "San Francisco" # IMPORTANT: Store usage data await session.store_run_usage(result) # Continue conversation result = await Runner.run( agent, "What state is it in?", session=session ) print(result.final_output) # "California" await session.store_run_usage(result) ``` -------------------------------- ### Run Modal Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Executes the Modal sandbox example script, specifying an application name and streaming output. ```bash uv run python examples/sandbox/extensions/modal_runner.py \ --app-name openai-agents-python-sandbox-example \ --stream ``` -------------------------------- ### Run Python MCP Filesystem Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/filesystem_example/README.md This command executes the main Python script for the MCP filesystem example using `uv run`. It initiates the application that interacts with the local filesystem MCP server, demonstrating its functionality. ```bash uv run python examples/mcp/filesystem_example/main.py ``` -------------------------------- ### Define Starting Agent Source: https://github.com/openai/openai-agents-python/blob/main/docs/realtime/quickstart.md Create a RealtimeAgent instance with a name and instructions for the assistant's behavior. ```python agent = RealtimeAgent( name="Assistant", instructions="You are a helpful voice assistant. Keep responses short and conversational.", ) ``` -------------------------------- ### Run the Streamable HTTP Remote Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/streamable_http_remote_example/README.md Execute the Python example to connect an agent to DeepWiki via Streamable HTTP. Ensure `OPENAI_API_KEY` is set in your environment. ```bash uv run python examples/mcp/streamable_http_remote_example/main.py ``` -------------------------------- ### Run Direct-Model Examples with Model Override Source: https://github.com/openai/openai-agents-python/blob/main/examples/model_providers/README.md Execute direct-model examples, overriding the default target model using the '--model' argument. ```bash uv run examples/model_providers/any_llm_provider.py --model openrouter/openai/gpt-5.4-mini ``` ```bash uv run examples/model_providers/litellm_provider.py --model openrouter/openai/gpt-5.4-mini ``` -------------------------------- ### Run Blaxel Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Execute the Blaxel sandbox runner script with streaming output. ```bash uv run python examples/sandbox/extensions/blaxel_runner.py --stream ``` -------------------------------- ### Run MCP Prompt Server Example using uv Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/prompt_server/README.md This command executes the MCP prompt server example. It uses `uv` to run the `main.py` script, which initializes an `MCPServerStreamableHttp` instance to serve user-controlled prompts. The server automatically selects an open localhost port or honors `STREAMABLE_HTTP_PORT`. ```bash uv run python examples/mcp/prompt_server/main.py ``` -------------------------------- ### Sync Dependencies Source: https://github.com/openai/openai-agents-python/blob/main/CLAUDE.md Run this command to sync dependencies, especially after changes or initial setup. ```bash make sync ``` -------------------------------- ### Start Sandbox from Local Snapshot Source: https://github.com/openai/openai-agents-python/blob/main/docs/sandbox/guide.md Seed a new sandbox from saved files and artifacts. Use this when a fresh run should start from saved workspace contents rather than only agent.default_manifest. ```python from pathlib import Path from agents.run import RunConfig from agents.sandbox import LocalSnapshotSpec, SandboxRunConfig from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient run_config = RunConfig( sandbox=SandboxRunConfig( client=UnixLocalSandboxClient(), snapshot=LocalSnapshotSpec(base_path=Path("/tmp/my-sandbox-snapshot")), ), ) ``` -------------------------------- ### Run MCP SSE Remote Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/sse_remote_example/README.md Execute the MCP SSE remote example using uv. Requires OPENAI_API_KEY environment variable to be set for model API calls. ```bash uv run python examples/mcp/sse_remote_example/main.py ``` -------------------------------- ### Run Daytona Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Execute the Daytona sandbox runner script with streaming output. ```bash uv run python examples/sandbox/extensions/daytona/daytona_runner.py --stream ``` -------------------------------- ### Run Runloop Sandbox Example Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Execute the Runloop sandbox runner script with streaming output. ```bash uv run python examples/sandbox/extensions/runloop/runner.py --stream ``` -------------------------------- ### Run MCP Server with uv Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/manager_example/README.md Command to start the MCP server using the `uv` tool. ```bash uv run python examples/mcp/manager_example/mcp_server.py ``` -------------------------------- ### Run FastAPI App with uv Source: https://github.com/openai/openai-agents-python/blob/main/examples/mcp/manager_example/README.md Command to start the FastAPI application using the `uv` tool. ```bash uv run python examples/mcp/manager_example/app.py ``` -------------------------------- ### Install Dependencies with uv pip Source: https://github.com/openai/openai-agents-python/blob/main/examples/realtime/twilio_sip/README.md Install required Python packages for the Twilio SIP Realtime example using the uv package manager. This command installs all dependencies listed in the requirements.txt file for the project. ```bash uv pip install -r examples/realtime/twilio_sip/requirements.txt ``` -------------------------------- ### Run Vision UI Reproduction Example in Docker Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/vision_website_clone/README.md Build the shared tutorial Docker image and run the demo with the `--docker` flag to execute in a containerized environment. ```bash docker build -t sandbox-tutorials:latest -f examples/sandbox/tutorials/Dockerfile . uv run python examples/sandbox/tutorials/vision_website_clone/main.py --docker ``` -------------------------------- ### Create Project and Virtual Environment Source: https://github.com/openai/openai-agents-python/blob/main/docs/quickstart.md Initial setup for a new project, creating a directory and a Python virtual environment. ```bash mkdir my_project cd my_project python -m venv .venv ``` -------------------------------- ### Quick Start with EncryptedSession and SQLAlchemy Source: https://github.com/openai/openai-agents-python/blob/main/docs/sessions/encrypted_session.md Initialize an Agent with an EncryptedSession wrapping a SQLAlchemySession backend. Demonstrates transparent encryption setup with a 10-minute TTL and running a conversation through the Runner. ```python import asyncio from agents import Agent, Runner from agents.extensions.memory import EncryptedSession, SQLAlchemySession async def main(): agent = Agent("Assistant") # Create underlying session underlying_session = SQLAlchemySession.from_url( "user-123", url="sqlite+aiosqlite:///:memory:", create_tables=True ) # Wrap with encryption session = EncryptedSession( session_id="user-123", underlying_session=underlying_session, encryption_key="your-secret-key-here", ttl=600 # 10 minutes ) result = await Runner.run(agent, "Hello", session=session) print(result.final_output) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Playwright Screenshot Capture Setup and Execution Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/vision_website_clone/skills/playwright/SKILL.md Creates output directories, configures temporary environment variables, installs Playwright with Chromium, and captures a screenshot of a static HTML file at 2048x1152 resolution. Change the final output path to draft-2.png for subsequent passes. ```shell mkdir -p output/screenshots output/playwright/.tmp export TMPDIR="$PWD/output/playwright/.tmp" export TEMP="$TMPDIR" export TMP="$TMPDIR" npx --yes --package playwright@1.50.0 playwright install chromium npx --yes --package playwright@1.50.0 playwright screenshot \ --browser=chromium \ --viewport-size=2048,1152 \ "file://$PWD/output/site/index.html" \ output/screenshots/draft-1.png ``` -------------------------------- ### Run Vision UI Reproduction Example Locally Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/vision_website_clone/README.md Execute the vision website clone demo from the repository root using uv and Python. ```bash uv run python examples/sandbox/tutorials/vision_website_clone/main.py ``` -------------------------------- ### Setup and run Dataroom Q&A locally Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/dataroom_qa/README.md Commands to initialize the data fixture and execute the agent in a local Unix environment. ```bash uv run python examples/sandbox/tutorials/data/dataroom/setup.py uv run python examples/sandbox/tutorials/dataroom_qa/main.py ``` -------------------------------- ### Run FastAPI Server with Uvicorn Source: https://github.com/openai/openai-agents-python/blob/main/examples/realtime/twilio_sip/README.md Start the FastAPI application server that handles incoming SIP calls and webhook events. The server listens on all network interfaces (0.0.0.0) on port 8000 and processes OpenAI Realtime call webhooks. ```bash uv run uvicorn examples.realtime.twilio_sip.server:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/openai/openai-agents-python/blob/main/CLAUDE.md Build and preview the documentation locally. ```bash make serve-docs ``` -------------------------------- ### Install Cloudflare Sandbox Extra Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Installs the necessary dependencies for the Cloudflare sandbox extension. ```bash uv sync --extra cloudflare ``` -------------------------------- ### Install Modal Sandbox Extra Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Installs the necessary dependencies for the Modal sandbox extension. ```bash uv sync --extra modal ``` -------------------------------- ### Install E2B Sandbox Extra Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/extensions/README.md Installs the necessary dependencies for the E2B sandbox extension. ```bash uv sync --extra e2b ``` -------------------------------- ### Create and Run a Basic Agent Source: https://github.com/openai/openai-agents-python/blob/main/docs/index.md This Python example demonstrates how to initialize a simple agent with instructions and run a synchronous task to generate a haiku. ```python from agents import Agent, Runner agent = Agent(name="Assistant", instructions="You are a helpful assistant") result = Runner.run_sync(agent, "Write a haiku about recursion in programming.") print(result.final_output) # Code within the code, # Functions calling themselves, # Infinite loop's dance. ``` -------------------------------- ### Run Dataroom Q&A using Docker Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/dataroom_qa/README.md Build the sandbox tutorial image and run the agent with Docker integration. ```bash docker build --tag sandbox-tutorials:latest examples/sandbox/tutorials uv run python examples/sandbox/tutorials/dataroom_qa/main.py --docker ``` -------------------------------- ### Install Voice Dependencies Source: https://github.com/openai/openai-agents-python/blob/main/docs/voice/quickstart.md Install the optional voice dependencies for the Agents SDK using pip. ```bash pip install 'openai-agents[voice]' ``` -------------------------------- ### Install OpenAI Agents SDK Source: https://github.com/openai/openai-agents-python/blob/main/docs/index.md Use pip to install the OpenAI Agents SDK package. ```bash pip install openai-agents ``` -------------------------------- ### Run repo code review using Docker Source: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/tutorials/repo_code_review/README.md Build the tutorial Docker image and run the review and evaluation scripts with the --docker flag. ```bash docker build -t sandbox-tutorials:latest -f examples/sandbox/tutorials/Dockerfile . uv run python examples/sandbox/tutorials/repo_code_review/main.py --docker uv run python examples/sandbox/tutorials/repo_code_review/evals.py ``` -------------------------------- ### Set up Python environment with venv Source: https://github.com/openai/openai-agents-python/blob/main/README.md Create and activate a virtual environment, then install the openai-agents package. Optional groups include 'voice' for voice support and 'redis' for Redis session support. ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install openai-agents ``` -------------------------------- ### Build Full Documentation with Translations Source: https://github.com/openai/openai-agents-python/blob/main/CLAUDE.md Run translations and build the complete documentation set. ```bash make build-full-docs ``` -------------------------------- ### Install aiosqlite for AsyncSQLiteSession Source: https://github.com/openai/openai-agents-python/blob/main/docs/sessions/index.md Installs the aiosqlite package, which is required to use AsyncSQLiteSession for asynchronous SQLite database operations. ```bash pip install aiosqlite ``` -------------------------------- ### Using WebSearchTool and FileSearchTool with an Agent Source: https://github.com/openai/openai-agents-python/blob/main/docs/tools.md This snippet demonstrates how to initialize an Agent with WebSearchTool and FileSearchTool. The FileSearchTool is configured with a maximum number of results and specific vector store IDs. It then shows how to run the agent with a query that utilizes these tools. ```python from agents import Agent, FileSearchTool, Runner, WebSearchTool agent = Agent( name="Assistant", tools=[ WebSearchTool(), FileSearchTool( max_num_results=3, vector_store_ids=["VECTOR_STORE_ID"], ), ], ) async def main(): result = await Runner.run(agent, "Which coffee shop should I go to, taking into account my preferences and the weather today in SF?") print(result.final_output) ``` -------------------------------- ### Install OpenAI Agents SDK with uv Source: https://github.com/openai/openai-agents-python/blob/main/README.md Initialize a project and add the openai-agents package using the uv package manager. Optional groups 'voice' and 'redis' can be added for extended functionality. ```bash uv init uv add openai-agents ``` -------------------------------- ### Install OpenAI Agents SDK with Docker support Source: https://github.com/openai/openai-agents-python/blob/main/docs/sandbox_agents.md Install the OpenAI Agents SDK with additional dependencies for Docker-backed sandboxes. ```bash pip install "openai-agents[docker]" ``` -------------------------------- ### Configure Realtime Runner Source: https://github.com/openai/openai-agents-python/blob/main/docs/realtime/quickstart.md Set up the RealtimeRunner with the starting agent and model configuration, including audio input/output settings. ```python runner = RealtimeRunner( starting_agent=agent, config={ "model_settings": { "model_name": "gpt-realtime-2", "audio": { "input": { "format": "pcm16", "transcription": {"model": "gpt-4o-mini-transcribe"}, "turn_detection": { "type": "semantic_vad", "interrupt_response": True, }, }, "output": { "format": "pcm16", "voice": "ash", }, }, } }, ) ```