repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
openai-agents-python | examples/sandbox/extensions/vercel_runner.py | .py | """
Minimal Vercel-backed sandbox example for manual validation.
This mirrors the other cloud extension examples: it creates a tiny workspace,
verifies stop/resume persistence, then asks a sandboxed agent to inspect the
workspace through one shell tool.
"""
from __future__ import annotations
import argparse
import a... | 425 | 14,093 |
openai-agents-python | examples/sandbox/extensions/blaxel_runner.py | .py | """
Blaxel-backed sandbox example for manual validation.
This example mirrors the other cloud extension runners. It supports:
- Standard agent run (non-streaming and streaming).
- PTY interactive session demo (agent-driven).
- Blaxel Drive mount demo (persistent storage).
Prerequisites:
uv sync --extra blaxel
exp... | 467 | 15,732 |
openai-agents-python | examples/sandbox/extensions/temporal/local_hello_workflow.py | .py | """Minimal local Temporal SandboxAgent workflow example.
This example is intentionally smaller than ``temporal_sandbox_agent.py``. It starts a local
Temporal test server through the Temporal Python SDK, runs a ``SandboxAgent`` workflow against
the local Unix sandbox backend, and then shuts everything down.
It does no... | 151 | 5,593 |
openai-agents-python | examples/sandbox/extensions/temporal/temporal_sandbox_agent.py | .py | """Temporal Sandbox agent example.
Runs a SandboxAgent as a durable Temporal workflow. The workflow is long-lived
and conversational: after processing each turn it idles waiting for the next
user message. Workflows persist indefinitely in Temporal. A separate session
manager workflow (``temporal_session_manager.py`... | 723 | 25,999 |
openai-agents-python | examples/sandbox/extensions/temporal/temporal_sandbox_tui.py | .py | # mypy: ignore-errors
# standalone example with sys.path sibling imports that mypy cannot follow
"""Textual TUI for the Temporal Sandbox agent conversation client.
Sessions are managed entirely via Temporal — no filesystem persistence.
A central SessionManagerWorkflow tracks all active agent sessions. The
TUI connect... | 1,205 | 45,011 |
openai-agents-python | examples/sandbox/extensions/temporal/temporal_session_manager.py | .py | # mypy: ignore-errors
# standalone example with sys.path sibling imports that mypy cannot follow
"""Temporal session manager workflow.
A long-lived singleton workflow that acts as the sole orchestrator for agent
session lifecycles. It starts and stops agent workflows, and maintains a
registry of active sessions so th... | 407 | 14,990 |
openai-agents-python | examples/sandbox/extensions/temporal/_worker_setup.py | .py | """Worker startup diagnostics."""
from __future__ import annotations
YELLOW = "\033[1;33m"
RESET = "\033[0m"
def print_backend_warnings(registered_names: set[str]) -> None:
"""Print a prominent warning banner for any unconfigured sandbox backends."""
import docker # type: ignore[import-untyped]
backen... | 40 | 1,230 |
openai-agents-python | examples/sandbox/extensions/runloop/runner.py | .py | """
Minimal Runloop-backed sandbox example for manual validation.
This mirrors the other cloud extension examples: it creates a tiny workspace, asks a sandboxed
agent to inspect it through one shell tool, and prints a short answer.
"""
import argparse
import asyncio
import os
import sys
from pathlib import Path
from... | 173 | 5,811 |
openai-agents-python | examples/sandbox/extensions/runloop/capabilities.py | .py | from __future__ import annotations
import argparse
import asyncio
import io
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from typing import Any, Literal, cast
from urllib.parse import urljoin
from openai.types.responses import ResponseText... | 1,016 | 36,151 |
openai-agents-python | examples/sandbox/extensions/daytona/daytona_runner.py | .py | """
Minimal Daytona-backed sandbox example for manual validation.
This mirrors the E2B and Modal extension examples: it creates a tiny workspace,
asks a sandboxed agent to inspect it through one shell tool, and prints a short
answer.
"""
import argparse
import asyncio
import os
import sys
from pathlib import Path
fr... | 206 | 7,116 |
openai-agents-python | examples/sandbox/extensions/daytona/usaspending_text2sql/sql_capability.py | .py | from __future__ import annotations
import textwrap
from typing import Any, Literal
from agents.sandbox import Capability, ExecTimeoutError, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.tool import FunctionTool
# Python script executed inside the sandbox to run SQL q... | 177 | 6,272 |
openai-agents-python | examples/sandbox/extensions/daytona/usaspending_text2sql/setup_db.py | .py | #!/usr/bin/env python3
"""Download NASA spending data from USAspending.gov and build a SQLite database.
This script is designed to run inside a sandbox environment with only Python
stdlib available. It fetches data via the USAspending bulk download API,
parses the resulting CSVs, and creates a local SQLite database.
... | 719 | 26,411 |
openai-agents-python | examples/sandbox/extensions/daytona/usaspending_text2sql/agent.py | .py | """NASA spending text-to-SQL agent.
Multi-turn conversational agent that translates natural-language questions
about NASA federal spending into SQL queries, executes them against a
USAspending SQLite database, and returns structured results.
Usage:
uv run python -m examples.sandbox.extensions.daytona.usaspending_... | 541 | 19,164 |
openai-agents-python | examples/sandbox/docker/docker_runner.py | .py | """
Start here if you are new to Docker-backed sandbox examples.
This file keeps the flow explicit:
1. Build a manifest for the files that should appear in the sandbox workspace.
2. Create a sandbox agent that can inspect that workspace through one shell tool.
3. Start a Docker-backed sandbox session, stream the run,... | 166 | 6,952 |
openai-agents-python | examples/sandbox/docker/mounts/s3_mount_read_write.py | .py | from __future__ import annotations
import asyncio
import os
import sys
from pathlib import Path
if __package__ is None or __package__ == "":
sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
from agents.sandbox.entries import (
DockerVolumeMountStrategy,
S3Mount,
)
from examples.sandbox.docker... | 53 | 1,438 |
openai-agents-python | examples/sandbox/docker/mounts/gcs_mount_read_write.py | .py | from __future__ import annotations
import asyncio
import os
import sys
from pathlib import Path
if __package__ is None or __package__ == "":
sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
from agents.sandbox.entries import (
DockerVolumeMountStrategy,
GCSMount,
)
from examples.sandbox.docke... | 64 | 1,850 |
openai-agents-python | examples/sandbox/docker/mounts/mount_smoke.py | .py | from __future__ import annotations
import os
import uuid
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
import docker # type: ignore[import-untyped]
from agents import ModelSettings, Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, Sandbox... | 154 | 4,732 |
openai-agents-python | examples/sandbox/docker/mounts/azure_mount_read_write.py | .py | from __future__ import annotations
import asyncio
import os
import sys
from pathlib import Path
if __package__ is None or __package__ == "":
sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
from agents.sandbox.entries import (
AzureBlobMount,
DockerVolumeMountStrategy,
)
from examples.sandbox... | 56 | 1,472 |
openai-agents-python | examples/sandbox/tutorials/misc.py | .py | import json
import os
import subprocess
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any, Literal, TypeAlias, cast
from openai.types.responses import (
ResponseComputerToolCall,
ResponseFileSearchToolCall,
ResponseFunctionToolCall,
ResponseFunctionWebSearc... | 398 | 14,261 |
openai-agents-python | examples/sandbox/tutorials/dataroom_qa/main.py | .py | """
Answer questions over a synthetic dataroom.
"""
import argparse
import asyncio
import sys
from pathlib import Path
from textwrap import dedent
from agents import Runner, RunResultStreaming, TResponseInputItem
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from... | 147 | 4,568 |
openai-agents-python | examples/sandbox/tutorials/vision_website_clone/main.py | .py | """
Clone a reference app screenshot as static HTML/CSS with the sandbox filesystem tools.
"""
from __future__ import annotations
import argparse
import asyncio
import os
import sys
from pathlib import Path
from textwrap import dedent
from agents import ModelSettings, Runner
from agents.run import RunConfig
from age... | 254 | 8,519 |
openai-agents-python | examples/sandbox/tutorials/dataroom_metric_extract/main.py | .py | """
Extract structured financial metrics from a synthetic 10-K dataroom and write a
JSONL or CSV artifact.
"""
import argparse
import asyncio
import csv
import json
import sys
from collections.abc import Sequence
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Literal, cast
from... | 275 | 9,589 |
openai-agents-python | examples/sandbox/tutorials/dataroom_metric_extract/evals.py | .py | from __future__ import annotations
import argparse
import csv
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, TypeAlias
if __package__ is None or __package__ == "":
sys.path.insert(0, str(Path(__file__).resolve().parent))
if TYPE_CHECKING or __package__:
... | 316 | 10,648 |
openai-agents-python | examples/sandbox/tutorials/dataroom_metric_extract/schemas.py | .py | from typing import Literal
from pydantic import BaseModel, Field
class FinancialMetric(BaseModel):
source_file: str = Field(
description="Workspace-relative source path under data/, such as data/10-k-mdna-overview.txt."
)
filing_section: Literal[
"Part II, Item 7. Management's Discussion ... | 34 | 1,445 |
openai-agents-python | examples/sandbox/tutorials/repo_code_review/main.py | .py | """
Review a small GitHub repository and produce sandbox-generated findings artifacts.
"""
import argparse
import asyncio
import json
import sys
from pathlib import Path
from textwrap import dedent
from typing import cast
from pydantic import BaseModel, Field
from agents import ModelSettings, Runner
from agents.run ... | 174 | 6,264 |
openai-agents-python | examples/sandbox/tutorials/repo_code_review/evals.py | .py | """Evaluate the repo code-review demo outputs."""
import argparse
import json
from pathlib import Path
EXPECTED_FINDING_PATHS = {
"repo/.github/workflows/test.yml",
"repo/src/sample/simple.py",
}
def load_findings(findings_path: Path) -> list[dict[str, object]]:
return [
json.loads(line)
... | 80 | 2,789 |
openai-agents-python | examples/sandbox/tutorials/sandbox_resume/main.py | .py | """
Show the smallest Unix-local sandbox flow with workspace instructions.
The manifest includes an AGENTS.md file that tells the agent how to build the
app, and the prompt asks for a tiny FastAPI operations status API with a health
check.
"""
import argparse
import asyncio
import sys
from pathlib import Path
from te... | 146 | 4,872 |
openai-agents-python | examples/sandbox/tutorials/data/dataroom/setup.py | .py | """Generate the synthetic dataroom fixture files."""
from pathlib import Path
def pdf_escape(text: str) -> str:
return text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
def write_plain_pdf(path: Path, lines: list[str]) -> None:
content_lines = ["BT", "/F1 11 Tf", "50 760 Td", "14 TL"]
... | 241 | 7,828 |
openai-agents-python | examples/sandbox/docs/coding_task.py | .py | """Runnable sandbox coding example used by docs/sandbox_agents.md.
This example gives the model a tiny repo plus one lazy-loaded skill, then
verifies that the agent edited the repo and ran the targeted test command.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
from col... | 261 | 9,383 |
openai-agents-python | examples/sandbox/misc/reference_policy_mcp_server.py | .py | from mcp.server.mcpserver import MCPServer
mcp = MCPServer("Reference Policy Server")
@mcp.tool()
def get_policy_reference(topic: str) -> str:
"""Return short internal policy guidance for a supported topic."""
normalized = topic.strip().lower()
if "discount" in normalized:
return (
"D... | 26 | 883 |
openai-agents-python | examples/sandbox/misc/example_support.py | .py | from __future__ import annotations
from collections.abc import Mapping
from agents.sandbox import Manifest
from agents.sandbox.entries import File
def text_manifest(files: Mapping[str, str]) -> Manifest:
"""Build a manifest from in-memory UTF-8 text files."""
return Manifest(
entries={path: File(co... | 34 | 914 |
openai-agents-python | examples/sandbox/misc/workspace_shell.py | .py | from __future__ import annotations
from agents.sandbox import Capability, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.tool import (
ShellCallOutcome,
ShellCommandOutput,
ShellCommandRequest,
ShellResult,
ShellTool,
Tool,
)
class WorkspaceShe... | 55 | 2,134 |
openai-agents-python | examples/sandbox/misc/workspace_apply_patch.py | .py | from __future__ import annotations
import io
from pathlib import Path
from agents import ApplyPatchTool, apply_diff
from agents.editor import ApplyPatchOperation, ApplyPatchResult
from agents.sandbox import Capability, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.too... | 79 | 3,106 |
openai-agents-python | examples/tools/shell_human_in_the_loop.py | .py | import argparse
import asyncio
import os
from collections.abc import Sequence
from pathlib import Path
from agents import (
Agent,
ModelSettings,
Runner,
ShellCallOutcome,
ShellCommandOutput,
ShellCommandRequest,
ShellResult,
ShellTool,
trace,
)
from agents.items import ToolApproval... | 156 | 5,096 |
openai-agents-python | examples/tools/apply_patch.py | .py | import argparse
import asyncio
import hashlib
import os
import tempfile
from pathlib import Path
from agents import Agent, ApplyPatchTool, ModelSettings, Runner, apply_diff, trace
from agents.editor import ApplyPatchOperation, ApplyPatchResult
from examples.auto_mode import confirm_with_fallback, is_auto_mode
class ... | 171 | 7,060 |
openai-agents-python | examples/tools/codex_same_thread.py | .py | import asyncio
from collections.abc import Mapping
from datetime import datetime
from pydantic import BaseModel
from agents import Agent, ModelSettings, Runner, gen_trace_id, trace
# This tool is still in experimental phase and the details could be changed until being GAed.
from agents.extensions.experimental.codex ... | 133 | 4,791 |
openai-agents-python | examples/tools/codex.py | .py | import asyncio
from datetime import datetime
from agents import Agent, Runner, gen_trace_id, trace
# This tool is still in experimental phase and the details could be changed until being GAed.
from agents.extensions.experimental.codex import (
CodexToolStreamEvent,
CommandExecutionItem,
ErrorItem,
Fil... | 168 | 5,967 |
openai-agents-python | examples/tools/container_shell_inline_skill.py | .py | import argparse
import asyncio
import base64
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZIP_DEFLATED, ZipFile
from openai.types.responses import ResponseFunctionShellToolCall
from openai.types.responses.response_container_reference import ResponseContainerReference
from agent... | 118 | 3,930 |
openai-agents-python | examples/tools/container_shell_skill_reference.py | .py | import argparse
import asyncio
import os
from openai.types.responses import ResponseFunctionShellToolCall
from openai.types.responses.response_container_reference import ResponseContainerReference
from agents import Agent, Runner, ShellTool, ShellToolSkillReference, trace
from agents.items import ModelResponse
SHELL... | 113 | 3,711 |
openai-agents-python | examples/tools/code_interpreter.py | .py | import asyncio
from collections.abc import Mapping
from typing import Any
from agents import Agent, CodeInterpreterTool, Runner, trace
def _get_field(obj: Any, key: str) -> Any:
if isinstance(obj, Mapping):
return obj.get(key)
return getattr(obj, key, None)
async def main():
agent = Agent(
... | 64 | 2,217 |
openai-agents-python | examples/tools/programmatic_tool_calling.py | .py | import asyncio
from typing import Literal
from openai.types.responses import ResponseFunctionToolCall
from openai.types.responses.response_output_item import Program
from pydantic import BaseModel
from agents import (
Agent,
ModelSettings,
ProgrammaticToolCallingTool,
Runner,
ToolCallItem,
)
from ... | 130 | 3,884 |
openai-agents-python | examples/tools/image_generator.py | .py | import asyncio
import base64
import os
import subprocess
import sys
import tempfile
from collections.abc import Mapping
from typing import Any
from agents import Agent, ImageGenerationTool, Runner, trace
from examples.auto_mode import is_auto_mode
def _get_field(obj: Any, key: str) -> Any:
if isinstance(obj, Map... | 79 | 2,433 |
openai-agents-python | examples/tools/computer_use.py | .py | # How to run this example:
# uv run python -m playwright install chromium
# uv run -m examples.tools.computer_use
import asyncio
import base64
import os
import sys
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any, Literal
from playwright.async_api import Brow... | 312 | 10,024 |
openai-agents-python | examples/tools/web_search.py | .py | import asyncio
from agents import Agent, Runner, WebSearchTool, trace
async def main():
agent = Agent(
name="Web searcher",
instructions="You are a helpful agent.",
tools=[WebSearchTool(user_location={"type": "approximate", "city": "New York"})],
)
with trace("Web search example"... | 24 | 671 |
openai-agents-python | examples/tools/local_shell_skill.py | .py | import argparse
import asyncio
from pathlib import Path
from agents import Agent, Runner, ShellTool, ShellToolLocalSkill, trace
from examples.tools.shell import ShellExecutor
SKILL_NAME = "csv-workbench"
SKILL_DIR = Path(__file__).resolve().parent / "skills" / SKILL_NAME
def build_local_skill() -> ShellToolLocalSki... | 79 | 2,314 |
openai-agents-python | examples/tools/file_search.py | .py | import asyncio
from openai import AsyncOpenAI
from agents import Agent, FileSearchTool, Runner, trace
async def main():
file_id: str | None = None
vector_store_id: str | None = None
async with AsyncOpenAI() as client:
try:
print("### Preparing vector store:\n")
# Create ... | 86 | 3,174 |
openai-agents-python | examples/tools/web_search_filters.py | .py | import asyncio
from urllib.parse import unquote, urlsplit, urlunsplit
from openai.types.responses.web_search_tool import Filters
from openai.types.shared.reasoning import Reasoning
from agents import Agent, ModelSettings, Runner, WebSearchTool, trace
from examples.web_search_utils import extract_url_citations, extrac... | 148 | 4,649 |
openai-agents-python | examples/tools/tool_search.py | .py | import asyncio
import json
import sys
from collections.abc import Mapping
from typing import Annotated, Any
from agents import (
Agent,
ModelSettings,
Runner,
ToolSearchTool,
tool_namespace,
trace,
)
from agents.decorators import tool
CUSTOMER_PROFILES = {
"customer_42": {
"custome... | 220 | 6,317 |
openai-agents-python | examples/tools/shell.py | .py | import argparse
import asyncio
import os
from collections.abc import Sequence
from pathlib import Path
from agents import (
Agent,
ModelSettings,
Runner,
ShellCallOutcome,
ShellCommandOutput,
ShellCommandRequest,
ShellResult,
ShellTool,
trace,
)
from agents.items import ToolApproval... | 143 | 4,721 |
openai-agents-python | examples/reasoning_content/main.py | .py | """
Example demonstrating how to access reasoning summaries when a model returns them.
Some models, like gpt-5.6, provide reasoning summaries in addition to the regular content.
This example shows how to access that content from both streaming and non-streaming responses,
and verifies that the requested summary was re... | 140 | 4,968 |
openai-agents-python | examples/reasoning_content/gpt_oss_stream.py | .py | import asyncio
import os
from openai import AsyncOpenAI
from openai.types.shared import Reasoning
from agents import (
Agent,
ModelSettings,
OpenAIChatCompletionsModel,
Runner,
set_tracing_disabled,
)
set_tracing_disabled(True)
# import logging
# logging.basicConfig(level=logging.DEBUG)
gpt_oss... | 55 | 1,474 |
openai-agents-python | examples/reasoning_content/__init__.py | .py | """
Examples demonstrating how to use models that provide reasoning content.
"""
| 4 | 81 |
openai-agents-python | examples/reasoning_content/runner_example.py | .py | """
Example demonstrating how to use the reasoning content feature with the Runner API.
This example shows how to extract and use reasoning content from responses when using
the Runner API, which is the most common way users interact with the Agents library.
To run this example, you need to:
1. Set your OPENAI_API_KE... | 88 | 3,410 |
openai-agents-python | examples/basic/lifecycle_example.py | .py | import asyncio
import random
from typing import Any, cast
from pydantic import BaseModel
from agents import (
Agent,
AgentHookContext,
AgentHooks,
RunContextWrapper,
RunHooks,
Runner,
Tool,
Usage,
)
from agents.decorators import tool
from agents.items import ModelResponse, TResponseInp... | 190 | 7,578 |
openai-agents-python | examples/basic/prompt_template.py | .py | import argparse
import asyncio
import random
from agents import Agent, GenerateDynamicPromptData, Runner
"""
NOTE: This example will not work out of the box, because the default prompt ID will not be available
in your project.
To use it, please:
1. Go to https://platform.openai.com/playground/prompts
2. Create a new... | 80 | 2,129 |
openai-agents-python | examples/basic/retry_litellm.py | .py | import asyncio
import inspect
from agents import (
Agent,
ModelRetrySettings,
ModelSettings,
RetryDecision,
RunConfig,
Runner,
retry_policies,
)
def format_error(error: object) -> str:
if not isinstance(error, BaseException):
return "Unknown error"
return str(error) or err... | 115 | 3,778 |
openai-agents-python | examples/basic/remote_image.py | .py | import asyncio
from agents import Agent, Runner
URL = "https://images.unsplash.com/photo-1505761671935-60b3a7427bad?auto=format&fit=crop&w=400&q=80"
async def main():
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
)
result = await Runner.run(
agent... | 32 | 706 |
openai-agents-python | examples/basic/stream_items.py | .py | import asyncio
import random
from agents import (
Agent,
ItemHelpers,
Runner,
)
from agents.decorators import tool
@tool
def how_many_jokes() -> int:
"""Return a random integer of jokes to tell between 1 and 10 (inclusive)."""
return random.randint(1, 10)
async def main():
agent = Agent(
... | 72 | 2,071 |
openai-agents-python | examples/basic/non_strict_output_type.py | .py | import asyncio
import json
from dataclasses import dataclass
from typing import Any
from agents import (
Agent,
AgentOutputSchema,
AgentOutputSchemaBase,
ModelBehaviorError,
Runner,
UserError,
)
"""This example demonstrates how to use an output type that is not in strict mode. Strict mode
allo... | 93 | 2,735 |
openai-agents-python | examples/basic/usage_tracking.py | .py | import asyncio
from pydantic import BaseModel
from agents import (
Agent,
Runner,
Usage,
)
from agents.decorators import tool
class Weather(BaseModel):
city: str
temperature_range: str
conditions: str
@tool
def get_weather(city: str) -> Weather:
"""Get the current weather information f... | 53 | 1,299 |
openai-agents-python | examples/basic/hello_world_gpt_5.py | .py | import asyncio
from openai.types.shared import Reasoning
from agents import Agent, ModelSettings, Runner
# If you have a certain reason to use Chat Completions, you can configure the model this way,
# and then you can pass the chat_completions_model to the Agent constructor.
# from openai import AsyncOpenAI
# client... | 31 | 1,072 |
openai-agents-python | examples/basic/image_tool_output.py | .py | import asyncio
from agents import (
Agent,
Runner,
ToolOutputImage,
ToolOutputImageDict,
)
from agents.decorators import tool
return_typed_dict = True
URL = "https://images.unsplash.com/photo-1505761671935-60b3a7427bad?auto=format&fit=crop&w=400&q=80"
@tool
def fetch_random_image() -> ToolOutputIma... | 44 | 1,023 |
openai-agents-python | examples/basic/stream_ws.py | .py | """Responses websocket streaming example with function tools, agent-as-tool, and approval.
This example shows a user-facing websocket workflow using
`responses_websocket_session(...)`:
- Streaming output (including reasoning summary deltas when available)
- Regular function tools
- An `Agent.as_tool(...)` specialist a... | 237 | 8,198 |
openai-agents-python | examples/basic/dynamic_system_prompt.py | .py | import asyncio
import random
from dataclasses import dataclass
from typing import Literal
from agents import Agent, RunContextWrapper, Runner
@dataclass
class CustomContext:
style: Literal["haiku", "pirate", "robot"]
def custom_instructions(
run_context: RunContextWrapper[CustomContext], agent: Agent[Custo... | 71 | 1,668 |
openai-agents-python | examples/basic/agent_lifecycle_example.py | .py | import asyncio
import random
from typing import Any
from pydantic import BaseModel
from agents import (
Agent,
AgentHookContext,
AgentHooks,
RunContextWrapper,
Runner,
Tool,
)
from agents.decorators import tool
from examples.auto_mode import input_with_fallback, is_auto_mode
class CustomAgen... | 141 | 4,445 |
openai-agents-python | examples/basic/retry.py | .py | import asyncio
import inspect
from agents import (
Agent,
ModelRetrySettings,
ModelSettings,
RetryDecision,
RunConfig,
Runner,
retry_policies,
)
def format_error(error: object) -> str:
if not isinstance(error, BaseException):
return "Unknown error"
return str(error) or err... | 113 | 3,652 |
openai-agents-python | examples/basic/local_file.py | .py | import asyncio
import base64
import os
from agents import Agent, Runner
FILEPATH = os.path.join(os.path.dirname(__file__), "media/partial_o3-and-o4-mini-system-card.pdf")
def file_to_base64(file_path: str) -> str:
with open(file_path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
async... | 46 | 1,131 |
openai-agents-python | examples/basic/tool_guardrails.py | .py | import asyncio
import json
from agents import (
Agent,
Runner,
ToolGuardrailFunctionOutput,
ToolInputGuardrailData,
ToolOutputGuardrailData,
ToolOutputGuardrailTripwireTriggered,
)
from agents.decorators import (
tool,
tool_input_guardrail,
tool_output_guardrail,
)
@tool
def send_... | 178 | 6,386 |
openai-agents-python | examples/basic/tools.py | .py | import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agents import (
Agent,
Runner,
)
from agents.decorators import tool
class Weather(BaseModel):
city: str = Field(description="The city name")
temperature_range: str = Field(description="The temperature range in Cel... | 41 | 1,012 |
openai-agents-python | examples/basic/local_image.py | .py | import asyncio
import base64
import os
from agents import Agent, Runner
FILEPATH = os.path.join(os.path.dirname(__file__), "media/image_bison.jpg")
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return ... | 49 | 1,133 |
openai-agents-python | examples/basic/stream_function_call_args.py | .py | import asyncio
from typing import Annotated, Any
from openai.types.responses import ResponseFunctionCallArgumentsDeltaEvent
from agents import (
Agent,
Runner,
)
from agents.decorators import tool
@tool
def write_file(filename: Annotated[str, "Name of the file"], content: str) -> str:
"""Write content t... | 92 | 3,514 |
openai-agents-python | examples/basic/stream_text.py | .py | import asyncio
from openai.types.responses import ResponseTextDeltaEvent
from agents import Agent, Runner
async def main():
agent = Agent(
name="Joker",
instructions="You are a helpful assistant.",
)
result = Runner.run_streamed(agent, input="Please tell me 5 jokes.")
async for even... | 22 | 556 |
openai-agents-python | examples/basic/remote_pdf.py | .py | import asyncio
from agents import Agent, Runner
URL = "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
async def main():
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
)
result = await Runner.run(
agent,
[
{
... | 32 | 646 |
openai-agents-python | examples/basic/hello_world.py | .py | import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(
name="Assistant",
instructions="You only respond in haikus.",
)
result = await Runner.run(agent, "Tell me about recursion in programming.")
print(result.final_output)
# Function calls itself,
# L... | 21 | 424 |
openai-agents-python | examples/basic/previous_response_id.py | .py | import asyncio
from agents import Agent, Runner
from examples.auto_mode import input_with_fallback, is_auto_mode
"""This demonstrates usage of the `previous_response_id` parameter to continue a conversation.
The second run passes the previous response ID to the model, which allows it to continue the
conversation with... | 75 | 2,398 |
openai-agents-python | examples/basic/hello_world_gpt_oss.py | .py | import asyncio
from openai import AsyncOpenAI
from agents import Agent, OpenAIChatCompletionsModel, Runner, set_tracing_disabled
set_tracing_disabled(True)
# import logging
# logging.basicConfig(level=logging.DEBUG)
# This is an example of how to use gpt-oss with Ollama.
# Refer to https://cookbook.openai.com/arti... | 40 | 1,255 |
openai-agents-python | examples/hosted_mcp/simple.py | .py | import argparse
import asyncio
from agents import Agent, HostedMCPTool, ModelSettings, Runner, RunResult, RunResultStreaming
"""This example demonstrates how to use the hosted MCP support in the OpenAI Responses API, with
approvals not required for any tools. You should only use this for trusted MCP servers."""
asy... | 57 | 2,083 |
openai-agents-python | examples/hosted_mcp/connectors.py | .py | import argparse
import asyncio
import json
import os
from datetime import datetime
from agents import Agent, HostedMCPTool, Runner, RunResult, RunResultStreaming
# import logging
# logging.basicConfig(level=logging.DEBUG)
async def main(verbose: bool, stream: bool):
# 1. Visit https://developers.google.com/oaut... | 64 | 2,381 |
openai-agents-python | examples/hosted_mcp/on_approval.py | .py | import argparse
import asyncio
import json
from typing import Literal
from agents import (
Agent,
HostedMCPTool,
MCPToolApprovalFunctionResult,
MCPToolApprovalRequest,
Runner,
RunResult,
RunResultStreaming,
)
from examples.auto_mode import confirm_with_fallback
def prompt_approval(request... | 87 | 2,804 |
openai-agents-python | examples/hosted_mcp/human_in_the_loop.py | .py | import argparse
import asyncio
import json
from typing import Literal
from agents import (
Agent,
HostedMCPTool,
ModelSettings,
RunConfig,
Runner,
RunResult,
RunResultStreaming,
)
from agents.model_settings import MCPToolChoice
from examples.auto_mode import confirm_with_fallback
def prom... | 134 | 4,510 |
openai-agents-python | examples/model_providers/any_llm_auto.py | .py | from __future__ import annotations
import asyncio
from pydantic import BaseModel
from agents import (
Agent,
ModelSettings,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
"""This example uses the built-in any-llm routing through OpenRouter.
Set OPENROUTER_API_KEY before running ... | 57 | 1,220 |
openai-agents-python | examples/model_providers/litellm_auto.py | .py | from __future__ import annotations
import asyncio
from pydantic import BaseModel
from agents import (
Agent,
ModelSettings,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
"""This example uses the built-in support for LiteLLM through OpenRouter.
Set OPENROUTER_API_KEY before runn... | 61 | 1,362 |
openai-agents-python | examples/model_providers/custom_example_provider.py | .py | from __future__ import annotations
import asyncio
import os
from openai import AsyncOpenAI
from agents import (
Agent,
Model,
ModelProvider,
OpenAIChatCompletionsModel,
RunConfig,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
BASE_URL = os.getenv("EXAMPLE_BASE_URL") ... | 78 | 2,269 |
openai-agents-python | examples/model_providers/custom_example_global.py | .py | import asyncio
import os
from openai import AsyncOpenAI
from agents import (
Agent,
Runner,
set_default_openai_api,
set_default_openai_client,
set_tracing_disabled,
)
from agents.decorators import tool
BASE_URL = os.getenv("EXAMPLE_BASE_URL") or ""
API_KEY = os.getenv("EXAMPLE_API_KEY") or ""
MOD... | 64 | 1,769 |
openai-agents-python | examples/model_providers/any_llm_provider.py | .py | from __future__ import annotations
import asyncio
import os
from agents import (
Agent,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
from agents.extensions.models.any_llm_model import AnyLLMModel
"""This example uses the AnyLLMModel directly.
You can run it like this:
uv run exampl... | 64 | 1,760 |
openai-agents-python | examples/model_providers/litellm_provider.py | .py | from __future__ import annotations
import asyncio
import os
from agents import (
Agent,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
from agents.extensions.models.litellm_model import LitellmModel
"""This example uses the LitellmModel directly, to hit any model provider.
You can run... | 65 | 1,924 |
openai-agents-python | examples/model_providers/custom_example_agent.py | .py | import asyncio
import os
from openai import AsyncOpenAI
from agents import (
Agent,
OpenAIChatCompletionsModel,
Runner,
set_tracing_disabled,
)
from agents.decorators import tool
BASE_URL = os.getenv("EXAMPLE_BASE_URL") or ""
API_KEY = os.getenv("EXAMPLE_API_KEY") or ""
MODEL_NAME = os.getenv("EXAMPL... | 62 | 1,845 |
openai-agents-python | examples/voice/static/main.py | .py | import asyncio
import random
import numpy as np
from agents import Agent
from agents.decorators import tool
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
from agents.voice import (
AudioInput,
SingleAgentVoiceWorkflow,
SingleAgentWorkflowCallbacks,
VoicePipeline,
)
fro... | 90 | 2,766 |
openai-agents-python | examples/voice/static/util.py | .py | import curses
import time
import numpy as np
import numpy.typing as npt
import sounddevice as sd
def _record_audio(screen: curses.window) -> npt.NDArray[np.float32]:
screen.nodelay(True) # Non-blocking input
screen.clear()
screen.addstr(
"Press <spacebar> to start recording. Press <spacebar> aga... | 70 | 2,068 |
openai-agents-python | examples/voice/streamed/main.py | .py | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
import numpy as np
import sounddevice as sd
from textual import events
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.reactive import reactive
from textual.widgets import Button, RichLo... | 234 | 6,747 |
openai-agents-python | examples/voice/streamed/my_workflow.py | .py | import random
from collections.abc import AsyncIterator, Callable
from agents import (
Agent,
Runner,
TResponseInputItem,
)
from agents.decorators import tool
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
from agents.voice import VoiceWorkflowBase, VoiceWorkflowHelper
@too... | 86 | 2,724 |
openai-agents-python | examples/mcp/streamablehttp_example/server.py | .py | import os
import random
import requests
from mcp.server.mcpserver import MCPServer
STREAMABLE_HTTP_HOST = os.getenv("STREAMABLE_HTTP_HOST", "127.0.0.1")
STREAMABLE_HTTP_PORT = int(os.getenv("STREAMABLE_HTTP_PORT", "18080"))
# Create server
mcp = MCPServer("Echo Server")
@mcp.tool()
def add(a: int, b: int) -> int:
... | 48 | 1,227 |
openai-agents-python | examples/mcp/streamablehttp_example/main.py | .py | import asyncio
import os
import shutil
import socket
import subprocess
import time
from typing import Any, cast
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServer, MCPServerStreamableHttp
from agents.model_settings import ModelSettings
STREAMABLE_HTTP_HOST = os.getenv("STREAMABLE_H... | 110 | 3,685 |
openai-agents-python | examples/mcp/streamablehttp_custom_client_example/server.py | .py | import os
import random
from mcp.server.mcpserver import MCPServer
STREAMABLE_HTTP_HOST = os.getenv("STREAMABLE_HTTP_HOST", "127.0.0.1")
STREAMABLE_HTTP_PORT = int(os.getenv("STREAMABLE_HTTP_PORT", "18080"))
# Create server
mcp = MCPServer("Echo Server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two n... | 32 | 691 |
openai-agents-python | examples/mcp/streamablehttp_custom_client_example/main.py | .py | """Example demonstrating custom httpx_client_factory for MCPServerStreamableHttp.
This example shows how to configure custom HTTP client behavior for MCP StreamableHTTP
connections, including SSL certificates, proxy settings, and custom timeouts.
"""
import asyncio
import os
import shutil
import socket
import subproc... | 143 | 4,869 |
openai-agents-python | examples/mcp/sse_remote_example/main.py | .py | import asyncio
import os
import shutil
import socket
import subprocess
import time
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any, cast
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServerSse
from agents.model... | 101 | 3,032 |
openai-agents-python | examples/mcp/get_all_mcp_tools_example/main.py | .py | import asyncio
import os
import shutil
from typing import Any
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServer, MCPServerStdio
from agents.mcp.util import MCPUtil, create_static_tool_filter
from agents.run_context import RunContextWrapper
from examples.auto_mode import confirm_wit... | 138 | 5,590 |
openai-agents-python | examples/mcp/prompt_server/server.py | .py | import os
from mcp.server.mcpserver import MCPServer
STREAMABLE_HTTP_HOST = os.getenv("STREAMABLE_HTTP_HOST", "127.0.0.1")
STREAMABLE_HTTP_PORT = int(os.getenv("STREAMABLE_HTTP_PORT", "18080"))
# Create server
mcp = MCPServer("Prompt Server")
# Instruction-generating prompts (user-controlled)
@mcp.prompt()
def gen... | 47 | 1,496 |
openai-agents-python | examples/mcp/prompt_server/main.py | .py | import asyncio
import os
import shutil
import socket
import subprocess
import time
from typing import Any, cast
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServer, MCPServerStreamableHttp
from agents.model_settings import ModelSettings
STREAMABLE_HTTP_HOST = os.getenv("STREAMABLE_H... | 137 | 4,396 |
openai-agents-python | examples/mcp/sse_example/server.py | .py | import os
import random
from mcp.server.mcpserver import MCPServer
SSE_HOST = os.getenv("SSE_HOST", "127.0.0.1")
SSE_PORT = int(os.getenv("SSE_PORT", "8000"))
# Create server
mcp = MCPServer("Echo Server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
print(f"[debug-server] add({a}, {b}... | 43 | 1,172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.