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/mcp/sse_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, MCPServerSse
from agents.model_settings import ModelSettings
SSE_HOST = os.getenv("SSE_HOST", "127.0.0.1")
def _choo... | 110 | 3,376 |
openai-agents-python | examples/mcp/filesystem_example/main.py | .py | import asyncio
import os
import shutil
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServer, MCPServerStdio
async def run(mcp_server: MCPServer):
agent = Agent(
name="Assistant",
instructions="Use the tools to read the filesystem and answer questions based on tho... | 58 | 1,925 |
openai-agents-python | examples/mcp/git_example/main.py | .py | import asyncio
import shutil
from agents import Agent, Runner, trace
from agents.mcp import MCPServer, MCPServerStdio
from examples.auto_mode import input_with_fallback
async def run(mcp_server: MCPServer, directory_path: str):
agent = Agent(
name="Assistant",
instructions=f"Answer questions abou... | 49 | 1,504 |
openai-agents-python | examples/mcp/manager_example/app.py | .py | import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from agents import Agent, Runner
from agents.mcp import MCPServer, MCPServerManager, MCPServerStreamableHttp
from agents.model_settings import ModelSettings
MCP_SERVER_URL = os.getenv("MCP_S... | 131 | 3,918 |
openai-agents-python | examples/mcp/manager_example/smoke_test.py | .py | """Smoke test for the MCP manager example app.
This script starts the sibling Streamable HTTP MCP server on a temporary local
port, loads the app with matching environment variables, and verifies the
manager-backed endpoints without calling a model.
"""
from __future__ import annotations
import asyncio
import import... | 145 | 4,662 |
openai-agents-python | examples/mcp/manager_example/mcp_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", "8000"))
mcp = MCPServer("FastAPI Example Server")
@mcp.tool()
def add(a: int, b: int) -> int:
return a + b
@mcp.tool()
def e... | 27 | 531 |
openai-agents-python | examples/mcp/streamable_http_remote_example/main.py | .py | import asyncio
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServerStreamableHttp
async def main():
async with MCPServerStreamableHttp(
name="DeepWiki MCP Streamable HTTP Server",
params={
"url": "https://mcp.deepwiki.com/mcp",
# Allow mor... | 39 | 1,279 |
openai-agents-python | examples/mcp/tool_filter_example/main.py | .py | import asyncio
import os
import shutil
from typing import Any, cast
from agents import Agent, Runner, gen_trace_id, trace
from agents.mcp import MCPServerStdio
from agents.mcp.util import create_static_tool_filter
async def run_with_auto_approval(agent: Agent[Any], message: str) -> str | None:
"""Run and auto-ap... | 76 | 2,832 |
openai-agents-python | examples/realtime/twilio_sip/server.py | .py | """Minimal FastAPI server for handling OpenAI Realtime SIP calls with Twilio."""
from __future__ import annotations
import asyncio
import logging
import os
import websockets
from fastapi import FastAPI, HTTPException, Request, Response
from openai import APIStatusError, AsyncOpenAI, InvalidWebhookSignatureError
fro... | 212 | 8,015 |
openai-agents-python | examples/realtime/twilio_sip/agents.py | .py | """Realtime agent definitions shared by the Twilio SIP example."""
from __future__ import annotations
import asyncio
from agents.decorators import tool
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
from agents.realtime import RealtimeAgent, realtime_handoff
# --- Tools ---------------------... | 93 | 3,361 |
openai-agents-python | examples/realtime/twilio/server.py | .py | import os
from typing import TYPE_CHECKING
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import PlainTextResponse
# Import TwilioHandler class - handle both module and package use cases
if TYPE_CHECKING:
# For type checking, use the relative import
from .twilio_ha... | 81 | 2,305 |
openai-agents-python | examples/realtime/twilio/twilio_handler.py | .py | from __future__ import annotations
import asyncio
import base64
import json
import os
import time
from datetime import datetime
from typing import Any
from fastapi import WebSocket
from agents.decorators import tool
from agents.realtime import (
RealtimeAgent,
RealtimePlaybackTracker,
RealtimeRunner,
... | 300 | 11,289 |
openai-agents-python | examples/realtime/cli/demo.py | .py | import asyncio
import queue
import sys
import threading
from contextlib import suppress
from typing import Any
import numpy as np
import sounddevice as sd
from agents.decorators import tool
from agents.realtime import (
RealtimeAgent,
RealtimePlaybackTracker,
RealtimeRunner,
RealtimeSession,
Realt... | 398 | 16,292 |
openai-agents-python | examples/realtime/app/server.py | .py | import asyncio
import base64
import json
import logging
import os
import struct
from contextlib import asynccontextmanager, suppress
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Any
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import Fi... | 607 | 24,546 |
openai-agents-python | examples/realtime/app/agent.py | .py | import asyncio
from agents.decorators import tool
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
from agents.realtime import RealtimeAgent, realtime_handoff
"""
When running the UI example locally, you can edit this file to change the setup. THe server
will use the agent returned from get_star... | 106 | 3,984 |
openai-agents-python | examples/customer_service/main.py | .py | from __future__ import annotations as _annotations
import asyncio
import random
import uuid
from pydantic import BaseModel
from agents import (
Agent,
HandoffOutputItem,
ItemHelpers,
MessageOutputItem,
RunContextWrapper,
Runner,
ToolCallItem,
ToolCallOutputItem,
TResponseInputItem... | 190 | 6,864 |
openai-agents-python | examples/memory/sqlalchemy_session_example.py | .py | import asyncio
from agents import Agent, Runner
from agents.extensions.memory.sqlalchemy_session import SQLAlchemySession
async def main():
# Create an agent
agent = Agent(
name="Assistant",
instructions="Reply very concisely.",
)
# Create a session instance with a session ID.
# ... | 79 | 2,511 |
openai-agents-python | examples/memory/file_hitl_example.py | .py | """
File-backed session example with human-in-the-loop tool approval.
This mirrors the JS `file-hitl.ts` sample: a session persisted on disk and tools that
require approval before execution.
"""
from __future__ import annotations
import asyncio
import json
from typing import Any
from agents import (
Agent,
... | 157 | 5,790 |
openai-agents-python | examples/memory/encrypted_session_example.py | .py | """
Example demonstrating encrypted session memory functionality.
This example shows how to use encrypted session memory to maintain conversation history
across multiple agent runs with automatic encryption and TTL-based expiration.
The EncryptedSession wrapper provides transparent encryption over any underlying sessi... | 110 | 3,802 |
openai-agents-python | examples/memory/sqlite_session_example.py | .py | """
Example demonstrating session memory functionality.
This example shows how to use session memory to maintain conversation history
across multiple agent runs without manually handling .to_input_list().
"""
import asyncio
from agents import Agent, Runner, SQLiteSession
async def main():
# Create an agent
... | 78 | 2,364 |
openai-agents-python | examples/memory/redis_session_example.py | .py | """
Example demonstrating Redis session memory functionality.
This example shows how to use Redis-backed session memory to maintain conversation
history across multiple agent runs with persistence and scalability.
Note: This example clears the session at the start to ensure a clean demonstration.
In production, you m... | 182 | 6,002 |
openai-agents-python | examples/memory/compaction_session_example.py | .py | """
Example demonstrating OpenAI responses.compact session functionality.
This example shows how to use OpenAIResponsesCompactionSession to automatically
compact conversation history when it grows too large, reducing token usage
while preserving context.
"""
import asyncio
from agents import Agent, OpenAIResponsesCo... | 87 | 2,974 |
openai-agents-python | examples/memory/openai_session_example.py | .py | """
Example demonstrating session memory functionality.
This example shows how to use session memory to maintain conversation history
across multiple agent runs without manually handling .to_input_list().
"""
import asyncio
from agents import Agent, OpenAIConversationsSession, Runner
async def main():
# Create... | 79 | 2,393 |
openai-agents-python | examples/memory/hitl_session_scenario.py | .py | """
Scenario that exercises HITL approvals, rehydration, and rejections across sessions.
"""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from openai.types.shared import Reasonin... | 413 | 13,496 |
openai-agents-python | examples/memory/openai_session_hitl_example.py | .py | """
Example demonstrating OpenAI Conversations session with human-in-the-loop (HITL) tool approval.
This example shows how to use OpenAI Conversations session memory combined with
human-in-the-loop tool approval. The session maintains conversation history while
requiring approval for specific tool calls.
"""
import a... | 125 | 3,831 |
openai-agents-python | examples/memory/advanced_sqlite_session_example.py | .py | """
Comprehensive example demonstrating AdvancedSQLiteSession functionality.
This example shows both basic session memory features and advanced conversation
branching capabilities, including usage statistics, turn-based organization,
and multi-timeline conversation management.
"""
import asyncio
from agents import (... | 283 | 10,634 |
openai-agents-python | examples/memory/file_session.py | .py | """
Simple file-backed session implementation for examples.
Persists conversation history as JSON on disk so runs can resume across processes.
"""
from __future__ import annotations
import asyncio
import json
from datetime import datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
from a... | 125 | 4,980 |
openai-agents-python | examples/memory/memory_session_hitl_example.py | .py | """
Example demonstrating SQLite in-memory session with human-in-the-loop (HITL) tool approval.
This example shows how to use SQLite in-memory session memory combined with
human-in-the-loop tool approval. The session maintains conversation history while
requiring approval for specific tool calls.
"""
import asyncio
... | 127 | 3,900 |
openai-agents-python | examples/memory/compaction_session_stateless_example.py | .py | """
Example demonstrating stateless compaction with store=False.
In auto mode, OpenAIResponsesCompactionSession uses input-based compaction when
responses are not stored on the server.
"""
import asyncio
from agents import Agent, ModelSettings, OpenAIResponsesCompactionSession, Runner, SQLiteSession
async def main... | 86 | 2,810 |
openai-agents-python | examples/memory/dapr_session_example.py | .py | """
Example demonstrating Dapr State Store session memory functionality.
This example shows how to use Dapr-backed session memory to maintain conversation
history across multiple agent runs with support for various backend stores
(Redis, PostgreSQL, MongoDB, etc.).
WHAT IS DAPR?
Dapr (https://dapr.io) is a portable, ... | 587 | 23,447 |
openai-agents-python | examples/memory/mongodb_session_example.py | .py | """
Example demonstrating MongoDB session memory with a shared AsyncMongoClient.
In production you should create one AsyncMongoClient and pass it to all sessions
so they share the same connection pool.
"""
import asyncio
from typing import Any
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from agen... | 73 | 2,327 |
openai-agents-python | examples/financial_research_agent/main.py | .py | import asyncio
from examples.auto_mode import input_with_fallback
from .manager import FinancialResearchManager
# Entrypoint for the financial bot example.
# Run this as `python -m examples.financial_research_agent.main` and enter a
# financial research query, for example:
# "Write up an analysis of Apple Inc.'s mo... | 24 | 719 |
openai-agents-python | examples/financial_research_agent/manager.py | .py | from __future__ import annotations
import asyncio
import json
import time
from collections.abc import Sequence
from datetime import datetime, timezone
from pydantic import BaseModel
from rich.console import Console
from agents import Runner, RunResult, RunResultStreaming, custom_span, gen_trace_id, trace
from exampl... | 279 | 11,078 |
openai-agents-python | examples/financial_research_agent/agents/search_agent.py | .py | from pydantic import BaseModel
from agents import Agent, ModelSettings, WebSearchTool
# Given a search term, use web search to pull back a brief summary.
# Summaries should be concise but capture the main financial points.
INSTRUCTIONS = (
"You are a research assistant specializing in financial topics. "
"Giv... | 28 | 922 |
openai-agents-python | examples/financial_research_agent/agents/verifier_agent.py | .py | from typing import Literal
from pydantic import BaseModel
from agents import Agent
# Agent to sanity‑check a synthesized report for consistency and recall.
# This can be used to flag potential gaps or obvious mistakes.
VERIFIER_PROMPT = (
"You are a meticulous evidence auditor. You will receive an original reque... | 52 | 2,044 |
openai-agents-python | examples/financial_research_agent/agents/writer_agent.py | .py | from pydantic import BaseModel
from agents import Agent
# Writer agent brings together the raw search results and optionally calls out
# to sub‑analyst tools for specialized commentary, then returns a cohesive markdown report.
WRITER_PROMPT = (
"You are a senior financial analyst. You will be provided with the or... | 45 | 1,960 |
openai-agents-python | examples/financial_research_agent/agents/financials_agent.py | .py | from pydantic import BaseModel
from agents import Agent
# A sub‑agent focused on analyzing a company's fundamentals.
FINANCIALS_PROMPT = (
"You are a financial analyst focused on company fundamentals such as revenue, "
"profit, margins and growth trajectory. Given a collection of web (and optional file) "
... | 24 | 739 |
openai-agents-python | examples/financial_research_agent/agents/planner_agent.py | .py | from pydantic import BaseModel
from agents import Agent
# Generate a plan of searches to ground the financial analysis.
# For a given financial question or company, we want to search for
# recent news, official filings, analyst commentary, and other
# relevant background.
PROMPT = (
"You are a financial research ... | 36 | 1,068 |
openai-agents-python | examples/financial_research_agent/agents/risk_agent.py | .py | from pydantic import BaseModel
from agents import Agent
# A sub‑agent specializing in identifying risk factors or concerns.
RISK_PROMPT = (
"You are a risk analyst looking for potential red flags in a company's outlook. "
"Given background research, produce a short analysis of risks such as competitive threat... | 23 | 655 |
openai-agents-python | examples/handoffs/message_filter_streaming.py | .py | from __future__ import annotations
import json
import random
from agents import (
Agent,
HandoffInputData,
Runner,
handoff,
trace,
)
from agents.decorators import tool
from agents.extensions import handoff_filters
from agents.models import is_gpt_5_default
@tool
def random_number_tool(max: int) ... | 195 | 6,084 |
openai-agents-python | examples/handoffs/message_filter.py | .py | from __future__ import annotations
import json
import random
from agents import (
Agent,
HandoffInputData,
Runner,
handoff,
trace,
)
from agents.decorators import tool
from agents.extensions import handoff_filters
from agents.models import is_gpt_5_default
@tool
def random_number_tool(max: int) ... | 195 | 6,102 |
openai-agents-python | examples/agent_patterns/agents_as_tools_streaming.py | .py | import asyncio
from agents import (
Agent,
AgentToolStreamEvent,
ModelSettings,
Runner,
trace,
)
from agents.decorators import tool
@tool(
name_override="billing_status_checker",
description_override="Answer questions about customer billing status.",
)
def billing_status_checker(customer_... | 67 | 2,230 |
openai-agents-python | examples/agent_patterns/streaming_guardrails.py | .py | from __future__ import annotations
import asyncio
from openai.types.responses import ResponseTextDeltaEvent
from pydantic import BaseModel, Field
from agents import Agent, Runner
"""
This example shows how to use guardrails as the model is streaming. Output guardrails run after the
final output has been generated; ... | 94 | 3,305 |
openai-agents-python | examples/agent_patterns/agents_as_tools_conditional.py | .py | import asyncio
from pydantic import BaseModel
from agents import Agent, AgentBase, ModelSettings, RunContextWrapper, Runner, trace
from agents.decorators import tool
from examples.auto_mode import confirm_with_fallback, input_with_fallback, is_auto_mode
"""
This example demonstrates the agents-as-tools pattern with ... | 160 | 6,001 |
openai-agents-python | examples/agent_patterns/human_in_the_loop_custom_rejection.py | .py | """Human-in-the-loop example with a custom rejection message.
This example is intentionally minimal:
1. A single sensitive tool requires human approval.
2. The first turn always issues that tool call.
3. ``tool_error_formatter`` defines the universal fallback message shape.
4. A per-call ``rejection_message`` passed t... | 108 | 3,790 |
openai-agents-python | examples/agent_patterns/input_guardrails.py | .py | from __future__ import annotations
import asyncio
from pydantic import BaseModel
from agents import (
Agent,
GuardrailFunctionOutput,
InputGuardrailTripwireTriggered,
RunContextWrapper,
Runner,
TResponseInputItem,
)
from agents.decorators import input_guardrail
from examples.auto_mode import ... | 123 | 3,755 |
openai-agents-python | examples/agent_patterns/human_in_the_loop_stream.py | .py | """Human-in-the-loop example with streaming.
This example demonstrates the human-in-the-loop (HITL) pattern with streaming.
The agent will pause execution when a tool requiring approval is called,
allowing you to approve or reject the tool call before continuing.
The streaming version provides real-time feedback as t... | 124 | 3,531 |
openai-agents-python | examples/agent_patterns/forcing_tool_use.py | .py | from __future__ import annotations
import asyncio
from typing import Any, Literal
from pydantic import BaseModel
from agents import (
Agent,
FunctionToolResult,
ModelSettings,
RunContextWrapper,
Runner,
ToolsToFinalOutputFunction,
ToolsToFinalOutputResult,
)
from agents.decorators import ... | 113 | 3,609 |
openai-agents-python | examples/agent_patterns/deterministic.py | .py | import asyncio
from pydantic import BaseModel
from agents import Agent, Runner, trace
from examples.auto_mode import input_with_fallback
"""
This example demonstrates a deterministic flow, where each step is performed by an agent.
1. The first agent generates a story outline
2. We feed the outline into the second ag... | 85 | 2,622 |
openai-agents-python | examples/agent_patterns/output_guardrails.py | .py | from __future__ import annotations
import asyncio
import json
from pydantic import BaseModel, Field
from agents import (
Agent,
GuardrailFunctionOutput,
OutputGuardrailTripwireTriggered,
RunContextWrapper,
Runner,
)
from agents.decorators import output_guardrail
"""
This example shows how to use... | 81 | 2,379 |
openai-agents-python | examples/agent_patterns/llm_as_a_judge.py | .py | from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Literal
from agents import Agent, ItemHelpers, Runner, TResponseInputItem, trace
from examples.auto_mode import input_with_fallback, is_auto_mode
"""
This example shows the LLM as a judge pattern. The first agent g... | 90 | 2,866 |
openai-agents-python | examples/agent_patterns/human_in_the_loop.py | .py | """Human-in-the-loop example with tool approval.
This example demonstrates how to:
1. Define tools that require approval before execution
2. Handle interruptions when tool approval is needed
3. Serialize/deserialize run state to continue execution later
4. Approve or reject tool calls based on user input
"""
import a... | 143 | 4,010 |
openai-agents-python | examples/agent_patterns/agents_as_tools.py | .py | import asyncio
from agents import Agent, ItemHelpers, MessageOutputItem, Runner, trace
from examples.auto_mode import input_with_fallback
"""
This example shows the agents-as-tools pattern. The frontline agent receives a user message and
then picks which agents to call, as tools. In this case, it picks from a set of ... | 84 | 2,725 |
openai-agents-python | examples/agent_patterns/parallelization.py | .py | import asyncio
from agents import Agent, ItemHelpers, Runner, trace
from examples.auto_mode import input_with_fallback
"""
This example shows the parallelization pattern. We run the agent three times in parallel, and pick
the best result.
"""
spanish_agent = Agent(
name="spanish_agent",
instructions="You tra... | 66 | 1,696 |
openai-agents-python | examples/agent_patterns/agents_as_tools_structured.py | .py | import asyncio
from pydantic import BaseModel, Field
from agents import Agent, Runner
"""
This example shows structured input for agent-as-tool calls.
"""
class TranslationInput(BaseModel):
text: str = Field(description="Text to translate.")
source: str = Field(description="Source language code or name.")
... | 65 | 1,976 |
openai-agents-python | examples/agent_patterns/hosted_multi_agent_beta.py | .py | # Copy/paste command (does not modify uv.lock):
# uv run -m examples.agent_patterns.hosted_multi_agent_beta --mode stream
import argparse
import asyncio
from collections.abc import Mapping
from typing import Any
from agents import (
Agent,
Runner,
)
from agents.decorators import tool
from agents.extensions.ex... | 97 | 3,222 |
openai-agents-python | examples/agent_patterns/routing.py | .py | import asyncio
import uuid
from openai.types.responses import ResponseContentPartDoneEvent, ResponseTextDeltaEvent
from agents import Agent, RawResponsesStreamEvent, Runner, TResponseInputItem, trace
from examples.auto_mode import input_with_fallback, is_auto_mode
"""
This example shows the handoffs/routing pattern.... | 78 | 2,502 |
openai-agents-python | examples/research_bot/main.py | .py | import asyncio
from examples.auto_mode import input_with_fallback
from .manager import ResearchManager
async def main() -> None:
query = input_with_fallback(
"What would you like to research? ",
"Impact of electric vehicles on the grid.",
)
await ResearchManager().run(query)
if __name_... | 18 | 361 |
openai-agents-python | examples/research_bot/manager.py | .py | from __future__ import annotations
import asyncio
import time
from rich.console import Console
from agents import Runner, custom_span, gen_trace_id, trace
from .agents.planner_agent import WebSearchItem, WebSearchPlan, planner_agent
from .agents.search_agent import search_agent
from .agents.writer_agent import Repo... | 132 | 4,914 |
openai-agents-python | examples/research_bot/printer.py | .py | from typing import Any
from rich.console import Console, Group
from rich.live import Live
from rich.spinner import Spinner
class Printer:
def __init__(self, console: Console):
self.live = Live(console=console)
self.items: dict[str, tuple[str, bool]] = {}
self.hide_done_ids: set[str] = set... | 42 | 1,320 |
openai-agents-python | examples/research_bot/agents/search_agent.py | .py | from agents import Agent, WebSearchTool
INSTRUCTIONS = (
"You are a research assistant. Given a search term, you search the web for that term and "
"produce a concise summary of the results. The summary must be 2-3 paragraphs and less than 300 "
"words. Capture the main points. Write succinctly, no need to... | 18 | 708 |
openai-agents-python | examples/research_bot/agents/writer_agent.py | .py | # Agent used to synthesize a final report from the individual summaries.
from openai.types.shared.reasoning import Reasoning
from pydantic import BaseModel
from agents import Agent, ModelSettings
PROMPT = (
"You are a senior researcher tasked with writing a cohesive report for a research query. "
"You will be... | 36 | 1,207 |
openai-agents-python | examples/research_bot/agents/planner_agent.py | .py | from openai.types.shared.reasoning import Reasoning
from pydantic import BaseModel
from agents import Agent, ModelSettings
PROMPT = (
"You are a helpful research assistant. Given a query, come up with a set of web searches "
"to perform to best answer the query. Output between 5 and 20 terms to query for."
)
... | 32 | 846 |
openai-agents-python | src/agents/agent_tool_state.py | .py | from __future__ import annotations
import weakref
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from ._tool_invocation import tool_invocation_identity_and_scope
if TYPE_CHECKING:
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
from .result im... | 277 | 10,189 |
openai-agents-python | src/agents/_httpx_compat.py | .py | from __future__ import annotations
import sys
from functools import cache
from importlib import import_module
from types import ModuleType
from typing import Any, cast
@cache
def _load_legacy_httpx() -> ModuleType | None:
try:
return import_module("httpx")
except ModuleNotFoundError as exc:
i... | 40 | 1,210 |
openai-agents-python | src/agents/logger.py | .py | import logging
from collections.abc import Callable, Mapping
from types import TracebackType
from . import _debug
logger = logging.getLogger("openai.agents")
_DiagnosticExtra = Callable[[], Mapping[str, object]]
_DiagnosticArgs = Callable[[], tuple[object, ...]]
_DIAGNOSTIC_CONTEXT_FIELD = "openai_agents_diagnostic_... | 267 | 7,309 |
openai-agents-python | src/agents/run_context.py | .py | from __future__ import annotations
import copy
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Generic
from uuid import uuid4
from typing_extensions import TypeVar
from ._tool_identity import (
FunctionToolLookupKey,
HostedMCPAppro... | 1,371 | 58,338 |
openai-agents-python | src/agents/stream_events.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal, TypeAlias
from .agent import Agent
from .items import RunItem, TResponseStreamEvent
@dataclass
class RawResponsesStreamEvent:
"""Streaming event from the LLM. These are 'raw' events, i.e. they are directly pass... | 63 | 1,759 |
openai-agents-python | src/agents/exceptions.py | .py | from __future__ import annotations
import asyncio
import builtins
import sys
import traceback
import types
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, NoReturn, cast
if sys.version_info < (3, 11):
from exceptiongroup import BaseEx... | 573 | 20,329 |
openai-agents-python | src/agents/editor.py | .py | from __future__ import annotations
import sys
from dataclasses import dataclass
from typing import Literal, Protocol, runtime_checkable
from .run_context import RunContextWrapper
from .util._types import MaybeAwaitable
ApplyPatchOperationType = Literal["create_file", "update_file", "delete_file"]
_DATACLASS_KWARGS ... | 49 | 1,377 |
openai-agents-python | src/agents/_config_coercion.py | .py | from __future__ import annotations
from dataclasses import fields, is_dataclass
from types import UnionType
from typing import Any, TypeVar, Union, cast, get_args, get_origin, get_type_hints
from pydantic import AliasChoices, BaseModel
ConfigT = TypeVar("ConfigT")
DataclassConfigT = TypeVar("DataclassConfigT")
Pydan... | 98 | 3,472 |
openai-agents-python | src/agents/lifecycle.py | .py | from typing import Any, Generic
from typing_extensions import TypeVar
from .agent import Agent, AgentBase
from .items import ModelResponse, TResponseInputItem
from .run_context import AgentHookContext, RunContextWrapper, TContext
from .tool import Tool
TAgent = TypeVar("TAgent", bound=AgentBase, default=AgentBase)
... | 208 | 6,603 |
openai-agents-python | src/agents/_tool_identity.py | .py | from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Literal, cast
from typing_extensions import Required, TypedDict
from . import _debug
from .exceptions import UserError
from .logger import logger
BareFunctionToolLookupKey = tuple[Litera... | 684 | 26,665 |
openai-agents-python | src/agents/_config.py | .py | from typing import Any, Literal
from openai import AsyncOpenAI
from .models import _openai_shared
from .models.openai_agent_registration import (
OpenAIAgentRegistrationConfig,
set_default_openai_agent_registration_config,
)
from .tracing import set_tracing_export_api_key
def set_default_openai_key(key: str... | 56 | 1,726 |
openai-agents-python | src/agents/__init__.py | .py | import logging
import sys
import threading
from typing import TYPE_CHECKING, Any, Literal
from openai import AsyncOpenAI
from . import _config, sandbox
from .agent import (
Agent,
AgentBase,
AgentToolStreamEvent,
StopAtTools,
ToolsToFinalOutputFunction,
ToolsToFinalOutputResult,
)
from .agent_... | 615 | 17,275 |
openai-agents-python | src/agents/responses_websocket_session.py | .py | from __future__ import annotations
from collections.abc import AsyncIterator, Mapping
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from .agent import Agent
from .items import TResponseInputItem
from .models.multi_provider import (
MultiProvider... | 143 | 5,538 |
openai-agents-python | src/agents/run_state.py | .py | """RunState class for serializing and resuming agent runs with human-in-the-loop support."""
from __future__ import annotations
import asyncio
import copy
import dataclasses
import json
import math
import threading
from collections import deque
from collections.abc import Callable, Collection, Iterator, Mapping, Sequ... | 5,496 | 224,292 |
openai-agents-python | src/agents/_tool_invocation.py | .py | from __future__ import annotations
import hashlib
import json
from collections.abc import Mapping, Sequence
from typing import Any, TypeGuard
from pydantic import BaseModel
from ._tool_identity import (
FunctionToolLookupKey,
get_function_tool_lookup_key_for_call,
get_hosted_mcp_approval_request_identity... | 317 | 10,610 |
openai-agents-python | src/agents/function_schema.py | .py | from __future__ import annotations
import contextlib
import inspect
import logging
import re
from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated, Any, Literal, get_args, get_origin, get_type_hints
# griffelib exposes the `griffe` package at runtime but currently does no... | 488 | 19,403 |
openai-agents-python | src/agents/run.py | .py | from __future__ import annotations
import asyncio
import contextlib
import warnings
from typing import TYPE_CHECKING, Any, cast
from typing_extensions import Unpack
from . import _debug
from .agent import Agent
from .agent_tool_state import set_agent_tool_state_scope
from .exceptions import (
AgentsException,
... | 2,290 | 115,561 |
openai-agents-python | src/agents/run_config.py | .py | from __future__ import annotations
import os
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import PurePath
from typing import TYPE_CHECKING, Any, Generic, Literal
from pydantic import TypeAdapter
from typing_extensions import NotRequired, TypedDict
from ._config_coercion ... | 572 | 23,300 |
openai-agents-python | src/agents/version.py | .py | import importlib.metadata
try:
__version__ = importlib.metadata.version("openai-agents")
except importlib.metadata.PackageNotFoundError:
# Fallback if running from source without being installed
__version__ = "0.0.0"
| 8 | 230 |
openai-agents-python | src/agents/usage.py | .py | from __future__ import annotations
import copy
import json
from collections.abc import Mapping
from dataclasses import field
from typing import Annotated, Any, cast
from openai.types.completion_usage import CompletionTokensDetails, PromptTokensDetails
from openai.types.responses.response_usage import InputTokensDetai... | 497 | 20,133 |
openai-agents-python | src/agents/result.py | .py | from __future__ import annotations
import abc
import asyncio
import copy
import weakref
from collections.abc import AsyncIterator
from dataclasses import InitVar, dataclass, field, replace
from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast
from pydantic import GetCoreSchemaHandler
from pydantic_core import... | 1,190 | 50,925 |
openai-agents-python | src/agents/computer.py | .py | import abc
from typing import Literal
Environment = Literal["mac", "windows", "ubuntu", "browser"]
Button = Literal["left", "right", "wheel", "back", "forward"]
class Computer(abc.ABC):
"""A computer implemented with sync operations.
Subclasses provide the local runtime behind `ComputerTool`. Mouse action m... | 134 | 4,356 |
openai-agents-python | src/agents/repl.py | .py | from __future__ import annotations
from typing import Any
from openai.types.responses.response_text_delta_event import ResponseTextDeltaEvent
from .agent import Agent
from .items import TResponseInputItem
from .result import RunResultBase
from .run import DEFAULT_MAX_TURNS, Runner
from .run_context import TContext
f... | 77 | 2,843 |
openai-agents-python | src/agents/retry.py | .py | from __future__ import annotations
import dataclasses
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from inspect import isawaitable
from typing import Any, TypeAlias
from pydantic import Field
from pydantic.dataclasses import dataclass as pydantic_dataclass
from .util._types... | 465 | 16,533 |
openai-agents-python | src/agents/tool_context.py | .py | from __future__ import annotations
from dataclasses import dataclass, field, fields
from typing import TYPE_CHECKING, Any, cast
from openai.types.responses import ResponseFunctionToolCall
from ._tool_identity import HostedMCPApprovalKey, get_tool_call_namespace, tool_trace_name
from ._tool_invocation import tool_inv... | 293 | 11,445 |
openai-agents-python | src/agents/decorators.py | .py | """Public decorators for defining Agents SDK components.
`tool` is an alias for `function_tool`.
"""
from .guardrail import input_guardrail, output_guardrail
from .tool import function_tool
from .tool_guardrails import tool_input_guardrail, tool_output_guardrail
tool = function_tool
__all__ = [
"function_tool",... | 20 | 439 |
openai-agents-python | src/agents/_mcp_tool_metadata.py | .py | from __future__ import annotations
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from typing import Any
@dataclass(frozen=True)
class MCPToolMetadata:
"""Resolved display metadata for an MCP tool."""
description: str | None = None
title: str | None = None
def _get_map... | 88 | 2,972 |
openai-agents-python | src/agents/apply_diff.py | .py | """Utility for applying V4A diffs against text inputs."""
from __future__ import annotations
import re
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from typing import Literal
ApplyDiffMode = Literal["default", "create"]
@dataclass
class Chunk:
orig_index: int
del_lines: ... | 401 | 12,360 |
openai-agents-python | src/agents/_public_agent.py | .py | """Helpers for preserving the user-visible agent identity during execution rewrites."""
from __future__ import annotations
from .agent import Agent
_PUBLIC_AGENT_ATTR = "_agents_public_agent"
def set_public_agent(execution_agent: Agent, public_agent: Agent) -> Agent:
"""Tag an execution-only clone with the age... | 22 | 736 |
openai-agents-python | src/agents/tool.py | .py | from __future__ import annotations
import ast
import asyncio
import copy
import functools
import inspect
import json
import math
import typing
import weakref
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from enum import Enum
from types import FunctionType, UnionType... | 2,833 | 107,374 |
openai-agents-python | src/agents/agent_output.py | .py | import abc
from dataclasses import dataclass
from typing import Any, cast, get_args, get_origin
from pydantic import BaseModel, TypeAdapter
from typing_extensions import TypedDict
from .exceptions import (
ModelBehaviorError,
UserError,
_detach_data_redacted_error_traceback,
_is_error_data_redacted,
... | 219 | 7,899 |
openai-agents-python | src/agents/tool_guardrails.py | .py | from __future__ import annotations
import inspect
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Generic, Literal, overload
from typing_extensions import TypedDict, TypeVar
from .exceptions import UserError
from .tool_context import Too... | 280 | 8,454 |
openai-agents-python | src/agents/prompts.py | .py | from __future__ import annotations
import inspect
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast
from openai.types.responses.response_prompt_param import (
ResponsePromptParam,
Variables as ResponsesPromptVariables,
)
from typing_extensions i... | 83 | 2,475 |
openai-agents-python | src/agents/_debug.py | .py | import os
def _debug_flag_enabled(flag: str, default: bool = False) -> bool:
flag_value = os.getenv(flag)
if flag_value is None:
return default
else:
return flag_value == "1" or flag_value.lower() == "true"
def _load_dont_log_model_data() -> bool:
return _debug_flag_enabled("OPENAI_A... | 29 | 856 |
openai-agents-python | src/agents/strict_schema.py | .py | from __future__ import annotations
import copy
from typing import Any, TypeGuard, cast
from openai import NOT_GIVEN
from .exceptions import UserError
_EMPTY_SCHEMA = {
"additionalProperties": False,
"type": "object",
"properties": {},
"required": [],
}
# Upper bound on how many schema nodes strict ... | 534 | 19,042 |
openai-agents-python | src/agents/agent_tool_input.py | .py | from __future__ import annotations
import inspect
import json
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, TypedDict, cast
from pydantic import BaseModel
from .items import TResponseInputItem
STRUCTURED_INPUT_PREAMBLE = (
"You are being called as a to... | 269 | 8,507 |
openai-agents-python | src/agents/guardrail.py | .py | from __future__ import annotations
import inspect
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Generic, overload
from typing_extensions import TypeVar
from .exceptions import UserError
from .items import TResponseInputItem
from .run_context ... | 344 | 10,225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.