62 Commits

Author SHA1 Message Date
wesleyzhangwq 08fa43c099 docs: fix spelling in GPT-5 example (#4168) 2026-08-04 05:31:05 +00:00
Kazuhiro Sera b5944a42bd docs: improve example code details 2026-08-02 12:06:22 +09:00
Kazuhiro Sera a6ce52d255 docs: use decorators module throughout examples (#3946) 2026-07-28 07:57:19 +09:00
Kazuhiro Sera 28026bcd01 docs: stabilize tool guardrail and web search examples 2026-07-10 08:24:36 +09:00
Kazuhiro Sera 133208381c feat: add GPT-5.6 model defaults and migrate examples (#3774) 2026-07-10 07:58:22 +09:00
Kazuhiro Sera 921135630b fix: #3512 type tool-end hook results as object (#3518) 2026-05-28 17:57:33 +09:00
Kazuhiro Sera a6a4cc5143 feat: improve examples auto-run coverage and artifact handling (#3328) 2026-05-10 14:25:47 +09:00
Abdulrahman Alfozan c88f339d32 Update examples and defaults to GPT-5.5 (#3016) 2026-04-25 10:31:54 +09:00
Steve Coffey 2d665c9a67 Sandbox Agents (#2889)
### Sandbox Agents

This release adds **Sandbox Agents**, a beta SDK surface for running
agents with a persistent, isolated workspace. Sandbox agents keep the
normal `Agent` and `Runner` flow, but add workspace manifests,
sandbox-native capabilities, sandbox clients, snapshots, and resume
support so agents can work over real files, run commands, edit
repositories, generate artifacts, and continue work across runs.

Key pieces:

- `SandboxAgent`: an `Agent` with sandbox defaults such as
`default_manifest`, sandbox instructions, capabilities, and `run_as`.
- `Manifest`: a fresh-workspace contract for files, directories, local
files, local directories, Git repos, environment, users, groups, and
mounts.
- `SandboxRunConfig`: per-run sandbox wiring for client creation, live
session injection, serialized session resume, manifest overrides,
snapshots, and materialization concurrency limits.
- Built-in capabilities for shell access, filesystem editing and image
inspection, skills, memory, and compaction.
- Workspace snapshots and serialized sandbox session state for
reconnecting to existing work or seeding a fresh sandbox from saved
contents.

### Sandbox clients and hosted providers

Sandbox agents now support local, containerized, and hosted execution
backends:

- `UnixLocalSandboxClient` for fast local development.
- `DockerSandboxClient` for container isolation and image parity.
- Hosted sandbox clients for Blaxel, Cloudflare, Daytona, E2B, Modal,
Runloop, and Vercel through optional extras.

The release also adds provider-specific examples and mount strategies
for common storage backends, including S3, Cloudflare R2, Google Cloud
Storage, Azure Blob Storage, and S3 Files where supported by the
selected backend.

### Sandbox memory

Adds a sandbox memory capability that lets future sandbox-agent runs
learn from prior runs. Memory stores extracted lessons in the sandbox
workspace, injects a concise summary into later runs, and uses
progressive disclosure so agents can search deeper rollout summaries
only when useful.

Memory supports:

- Read-only or generate-only modes.
- Live updates when the agent discovers stale memory.
- Multi-turn grouping through `conversation_id`, SDK `Session`,
`RunConfig.group_id`, or generated run IDs.
- Separate memory layouts for isolating memory across agents or
workflows.
- S3-backed examples for persisted memory across runs.

### Workspace mounts, snapshots, and resume

This release adds a full workspace entry and mount model for sandbox
sessions:

- Local files and directories.
- Synthetic files and directories.
- Git repository entries.
- Remote storage mounts for S3, R2, GCS, Azure Blob Storage, and S3
Files.
- Provider-specific mount strategies across Docker, Modal, Cloudflare,
Blaxel, Daytona, E2B, and Runloop.
- Portable snapshots with path normalization, symlink preservation,
mount-safe snapshotting, and remote snapshot support.
- Resume paths through runner-managed `RunState`, explicit
`SandboxSessionState`, or saved snapshots.

### Examples and tutorials

Adds a large `examples/sandbox/` suite covering:

- Local Unix and Docker sandbox runners.
- Docker mount smoke tests for S3, GCS, Azure Blob Storage, and S3
Files.
- Sandbox coding tasks with skills.
- Sandbox agents as tools and handoff patterns.
- Memory examples, including multi-agent/multi-turn memory and S3-backed
memory.
- Tax-prep and healthcare-support workflows.
- Dataroom QA and metric extraction tutorials.
- Repository code review tutorial.
- Vision website clone tutorial.
- Provider examples for Blaxel, Cloudflare, Daytona, E2B, Modal,
Runloop, Temporal, and Vercel.

### Runtime, tracing, and model plumbing

The release includes the runtime plumbing needed to make sandbox agents
work naturally inside the existing SDK:

- Runner-managed sandbox preparation, capability binding, session
lifecycle, state serialization, and resume behavior.
- Sandbox-aware `RunState` serialization.
- Unified sandbox tracing with SDK spans.
- Token usage on tracing spans.
- Runner-managed prompt cache key defaults.
- OpenAI agent registration and harness ID configuration.
- Safer redaction of sensitive MCP tool outputs when sensitive tracing
is disabled.
- Additional OpenAI client/model utilities and Chat Completions
coverage.


## Documentation & Other Changes

- docs: add Asqav to external tracing processors list.
- docs: update translated document pages.

Co-authored-by: Abdulrahman Alfozan <alfozan@openai.com>
Co-authored-by: Aditya Singh <60082699+adityasingh2400@users.noreply.github.com>
Co-authored-by: Andi Liu <andi@openai.com>
Co-authored-by: Aron <263346377+aron-cf@users.noreply.github.com>
Co-authored-by: ashwinnathan-openai <ashwinnathan@openai.com>
Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: cploujoux <cploujoux@blaxel.ai>
Co-authored-by: elainegan-openai <168589666+elainegan-openai@users.noreply.github.com>
Co-authored-by: Elias Freider <freider@users.noreply.github.com>
Co-authored-by: Erik Dunteman <erik@erikds-macbook-air.local>
Co-authored-by: Jason Liu <jasonliu@openai.com>
Co-authored-by: Jason Steving <32336750+jasonsteving99@users.noreply.github.com>
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
Co-authored-by: Lovre Pešut <lovre.pesut@gmail.com>
Co-authored-by: Lucas Wang <lucas_wang@lucas-futures.com>
Co-authored-by: Matt Brockman <matt.brockman@e2b.dev>
Co-authored-by: Mish Ushakov <mishushakov@users.noreply.github.com>
Co-authored-by: Naresh <ghostwriternr@gmail.com>
Co-authored-by: nicholasclark-openai <nicholasclark@openai.com>
Co-authored-by: qiyaoq-oai <qiyaoq@openai.com>
Co-authored-by: Scott Trinh <scott@scotttrinh.com>
Co-authored-by: tode-rl <tony@runloop.ai>
Co-authored-by: Wendy Jiao <wendyjiao@openai.com>
2026-04-15 10:00:40 -07:00
Kazuhiro Sera 3a5267340a feat: add opt-in model retry policies (#2651) 2026-03-12 12:32:54 +09:00
Kazuhiro Sera 8d1094d21b docs: refresh docs and examples to gpt-5.4 (#2615) 2026-03-07 01:45:49 +09:00
Kazuhiro Sera 9b1f6eddc8 docs: improve examples for auto runs 2026-03-06 17:59:35 +09:00
Kazuhiro Sera c4a2fcb750 feat: add Responses websocket model and stream_ws example (#2530) 2026-02-24 07:08:06 +09:00
Kazuhiro Sera c06a8bb42a feat: add examples auto-run skill and refresh example scripts (#2303)
see also: https://github.com/openai/openai-agents-js/pull/848
2026-01-13 22:59:15 +09:00
Kazuhiro Sera f8153b95a2 Update examples (#2300) 2026-01-13 12:09:03 +09:00
Kazuhiro Sera 8bc42640f8 Add runner script for examples and refresh sample outputs (#2289) 2026-01-10 17:08:00 +09:00
Wen-Tien Chang 659f706d56 Add AgentHookContext with turn_input for agent hooks (#2213) 2025-12-22 09:51:37 +09:00
Hassan Abu Alhaj 71fa12cd87 Print called tool's name in examples/basic/stream_items.py (#2174) 2025-12-12 10:03:36 +09:00
Hassan Abu Alhaj 69c3357e8f Docs: Add per-request usage to docs and example script (#2026) 2025-11-05 14:29:58 +09:00
Wen-Tien Chang d659a738da docs: clarify on_tool_start and on_tool_end hooks for local tools only (#2037) 2025-11-04 12:16:42 +09:00
Kazuhiro Sera 4ba2e8af4f docs: improve typing in lifecycle hook example code (#2002) 2025-10-28 18:08:51 +09:00
Rohan Mehta 680554cc92 Image, file output types for functions (#1898)
To allow the new output types for image/file, you can now return one of
the three new types (or lists of those types, or even a typed dict
version). If you use those, we'll convert to the correct tool call
output type.

Resolves #1850
2025-10-16 13:11:02 -04:00
steven10a 22a63aad8b Adding tool input and output guardrails (#1792)
- This PR was started from [PR 1606: Tool
Guardrails](https://github.com/openai/openai-agents-python/pull/1606)
- It adds input and output guardrails at the tool level which can
trigger `ToolInputGuardrailTripwireTriggered` and
`ToolOutputGuardrailTripwireTriggered` exceptions
- It includes updated documentation, a runnable example, and unit tests
- `make check` and unit tests all pass

## Edits since last review:
- Extracted nested tool running logic in `_run_impl.py`
- Added rejecting tool call or tool call output and returning a message
to the model (rather than only raising an exception)
- Added the tool guardrail results to the `RunResult`
- Removed docs
2025-09-26 11:41:41 -04:00
Kazuhiro Sera ac64c02745 Add agent hooks to lifecycle_example (#1809) 2025-09-26 15:48:45 +09:00
Wen-Tien Chang 5e1db14da5 Add tool call arguments in ToolContext for RunHooks (#1765)
## Background 

Currently, the `RunHooks` lifecycle (`on_tool_start`, `on_tool_end`)
exposes the `Tool` and `ToolContext`, but does not include the actual
arguments passed to the tool call.

resolves https://github.com/openai/openai-agents-python/issues/939

## Solution

This implementation is inspired by [PR
#1598](https://github.com/openai/openai-agents-python/pull/1598).

* Add a new `tool_arguments` field to `ToolContext` and populate it via
from_agent_context with tool_call.arguments.
* Update `lifecycle_example.py` to demonstrate tool_arguments in hooks
* Unlike the proposal in [PR
#253](https://github.com/openai/openai-agents-python/issues/253), this
solution is not expected to introduce breaking changes, making it easier
to adopt.
2025-09-22 19:05:23 -04:00
Hamza Sheikh d91e39cd3a Update dynamic_system_prompt.py example to use dataclass for simiplicity (#1774)
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
2025-09-22 15:35:11 +09:00
Hassaan Arain 566b188fb5 Enhance function tool schemas with Annotated types (#1777)
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
2025-09-22 15:17:15 +09:00
Kazuhiro Sera aed6359047 feat: #1731 Enable developers to use Annotated types for function tool param description (#1753)
This pull request resolves #1731
2025-09-17 14:08:54 -04:00
Rohan Mehta efa88f79e7 Wait for input guardrails in streaming runs (#1730) 2025-09-12 18:29:39 -04:00
Erik Anstine 6904dcbbdb fix(run): fire on_llm_start / on_llm_end in Runner.run() for streaming & non-streaming (aligns with docs) (#1619) 2025-09-02 12:32:17 +09:00
Kazuhiro Sera 164acb59d9 Fix #1564 Add conversations API support (#1587)
This pull request resolves #1564

---------

Co-authored-by: Rohan Mehta <rm@openai.com>
2025-08-29 10:06:36 -04:00
Hassan Abu Alhaj e8d311bf9c Fix: Emit tool_called events immediately in streaming runs (#1300)
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
2025-08-25 10:48:32 +09:00
Hassan Abu Alhaj dcf9cf7e60 Add SQLAlchemy session backend for conversation history management (#1357)
Resolves #1328
2025-08-21 23:10:30 +09:00
Hassan Abu Alhaj ebc5443b0b Add documentation for token usage tracking (#1518)
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
2025-08-19 02:19:39 +00:00
Kazuhiro Sera 762447a10c Add local_file example to align with TS SDK repo (#1514) 2025-08-18 11:50:20 +09:00
Kazuhiro Sera cb72933fdd Rename gpt-5 example file for consistency 2025-08-16 11:20:44 +09:00
Abbas Asad 90a57d0965 Docs: Add missing docstring to how_many_jokes tool (#1479) 2025-08-15 08:35:19 +09:00
Abbas Asad a6378ce05a Docs: Add missing docstring to get_weather function (#1478) 2025-08-15 08:32:23 +09:00
Abbas Asad 4b229d1001 Add input validation and type conversion for user input (#1476) 2025-08-15 08:31:30 +09:00
Abbas Asad cec3a9af94 Fix: Clarify random_number function docstring for inclusive range (#1475) 2025-08-15 08:30:40 +09:00
Abbas Asad 65cb91ce26 Add input validation and type conversion for user input (#1462)
## Summary

Fixed a type safety issue where user input was being used as a string
without conversion to integer, which could cause runtime errors and type
mismatches.

## Problem

The code was using `input()` which returns a string, but then using it
directly in the f-string without converting it to an integer. This could
cause:
- Type mismatches when the string is passed to functions expecting
integers
- Runtime errors when users enter non-numeric input
- Inconsistent behavior with the function signature expectations

## Changes Made

Added proper input validation and type conversion:
- Wrapped the input processing in a try-except block
- Convert user input to integer using `int(user_input)`
- Added error handling for invalid input with user-friendly message
- Used the converted integer value in the f-string instead of raw string
input

This ensures type safety and provides better user experience with proper
error handling.
2025-08-14 12:33:22 +09:00
Abbas Asad e4699c358b Fix: Clarify random_number function docstring for inclusive range (#1461) 2025-08-14 12:32:24 +09:00
Kazuhiro Sera 4c436b7bde Add a simple gpt-oss example (#1440)
This pull request adds a simple gpt-oss example app
2025-08-14 12:21:09 +09:00
Kazuhiro Sera e3b4856a20 Fix #1407 Add reasoning.effort="minimal" and "verbosity" params to ModelSettings (#1439)
This pull request resolves #1407 ; the "minimal" reasoning effort param
is already supported.
2025-08-13 10:00:13 -04:00
devtalker cb0125c18e Add streaming function call arguments example (#1052)
Co-authored-by: Kazuhiro Sera <seratch@openai.com>
2025-08-11 15:51:53 +09:00
Adeniji Adekunle James 3a16a24dac Examples: use agent to interact with Remote PDF Documents (#1319) 2025-07-31 01:34:24 +00:00
Stephan Fitzpatrick 6b94ad0f85 Add Sessions for Automatic Conversation History Management (#752)
# Overview

Resolves #745

This PR introduces **Sessions**, a new core feature that automatically
maintains conversation history across multiple agent runs, eliminating
the need to manually handle `.to_input_list()` between turns.

## Key Features

### 🧠 Automatic Memory Management
- **Zero-effort conversation continuity**: Agents automatically remember
previous context without manual state management
- **Session-based organization**: Each conversation is isolated by
unique session IDs
- **Seamless integration**: Works with existing `Runner.run()`,
`Runner.run_sync()`, and `Runner.run_streamed()` methods

### 🔌 Extensible Session Protocol
- **Library-agnostic design**: Clean protocol interface allows any
storage backend
- **Drop-in implementations**: Easy integration with Redis, PostgreSQL,
MongoDB, or any custom storage
- **Production-ready interface**: Async-first design with proper error
handling and type safety
- **Vendor flexibility**: Library authors can provide their own Session
implementations

### 💾 Built-in SQLite Implementation
- **In-memory SQLite**: Perfect for temporary conversations during
development
- **Persistent SQLite**: File-based storage for conversations that
survive application restarts
- **Thread-safe operations**: Production-ready with connection pooling
and proper concurrency handling

### 🔧 Simple API
```python
# Before: Manual conversation management
result1 = await Runner.run(agent, "What's the weather?")
new_input = result1.to_input_list() + [{"role": "user", "content": "How about tomorrow?"}]
result2 = await Runner.run(agent, new_input)

# After: Automatic with Sessions
session = SQLiteSession("user_123")

result1 = await Runner.run(agent, "What's the weather?", session=session)
result2 = await Runner.run(agent, "How about tomorrow?", session=session)  # Remembers context automatically
```

## What's Included

### Core Session Protocol
- **`Session` Protocol**: Clean, async interface that any storage
backend can implement
- **Type-safe design**: Full type hints and runtime validation
- **Standard operations**: `get_items()`, `add_items()`, `pop_item()`,
`clear_session()`
- **Extensibility-first**: Designed for third-party implementations

### Reference Implementation
- **`SQLiteSession` Class**: Production-ready SQLite implementation
- **Automatic schema management**: Creates tables and indexes
automatically
- **Connection pooling**: Thread-safe operations with proper resource
management
- **Flexible storage**: In-memory or persistent file-based databases

### Runner Integration
- **New `session` parameter**: Drop-in addition to existing `Runner`
methods
- **Backward compatibility**: Zero breaking changes to existing code
- **Automatic history management**: Prepends conversation history before
each run

## Session Protocol for Library Authors

The Session protocol provides a clean interface for implementing custom
storage backends:

```python
from agents.memory import Session
from typing import List

class MyCustomSession:
    """Custom session implementation following the Session protocol."""

    def __init__(self, session_id: str):
        self.session_id = session_id
        # Your initialization here

    async def get_items(self, limit: int | None = None) -> List[dict]:
        """Retrieve conversation history for this session."""
        # Your implementation here
        pass

    async def add_items(self, items: List[dict]) -> None:
        """Store new items for this session."""
        # Your implementation here
        pass

    async def pop_item(self) -> dict | None:
        """Remove and return the most recent item from this session."""
        # Your implementation here
        pass

    async def clear_session(self) -> None:
        """Clear all items for this session."""
        # Your implementation here
        pass

# Works seamlessly with any custom implementation
result = await Runner.run(agent, "Hello", session=MyCustomSession("session_123"))
```

### Example Third-Party Implementations

```python
# Redis-based session (hypothetical library implementation)
from redis_sessions import RedisSession
session = RedisSession("user_123", redis_url="redis://localhost:6379")

# PostgreSQL-based session (hypothetical library implementation) 
from postgres_sessions import PostgreSQLSession
session = PostgreSQLSession("user_123", connection_string="postgresql://...")

# Cloud-based session (hypothetical library implementation)
from cloud_sessions import CloudSession
session = CloudSession("user_123", api_key="...", region="us-east-1")

# All work identically with the Runner
result = await Runner.run(agent, "Hello", session=session)
```

## Benefits

### For Application Developers
- **Reduces boilerplate**: No more manual `.to_input_list()` management
- **Prevents memory leaks**: Automatic cleanup and organized storage
- **Easier debugging**: Clear conversation history tracking
- **Flexible storage**: Choose the right backend for your needs

### For Library Authors
- **Clean integration**: Simple protocol to implement for any storage
backend
- **Type safety**: Full type hints and runtime validation
- **Async-first**: Modern async/await design throughout
- **Documentation**: Comprehensive examples and API reference

### For Applications
- **Better user experience**: Seamless conversation continuity
- **Scalable architecture**: Support for multiple concurrent
conversations
- **Flexible deployment**: In-memory for development, production storage
for scale
- **Multi-agent support**: Same conversation history can be shared
across different agents

## Usage Examples

### Basic Usage with SQLiteSession
```python
from agents import Agent, Runner, SQLiteSession

agent = Agent(name="Assistant", instructions="Reply concisely.")
session = SQLiteSession("conversation_123")

# Conversation flows naturally
await Runner.run(agent, "Hi, I'm planning a trip to Japan", session=session)
await Runner.run(agent, "What's the best time to visit?", session=session)
await Runner.run(agent, "How about cherry blossom season?", session=session)
```

### Multiple Sessions with Isolation
```python
# Different users get separate conversation histories
session_alice = SQLiteSession("user_alice")
session_bob = SQLiteSession("user_bob")

# Completely isolated conversations
await Runner.run(agent, "I like pizza", session=session_alice)
await Runner.run(agent, "I like sushi", session=session_bob)
```

### Persistent vs In-Memory Storage
```python
# In-memory database (lost when process ends)
session = SQLiteSession("user_123")

# Persistent file-based database
session = SQLiteSession("user_123", "conversations.db")
```

### Session Management Operations
```python
session = SQLiteSession("user_123")

# Get all items in a session
items = await session.get_items()

# Add new items to a session
new_items = [
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi there!"}
]
await session.add_items(new_items)

# Remove and return the most recent item (useful for corrections)
last_item = await session.pop_item()

# Clear all items from a session
await session.clear_session()
```

### Message Correction Pattern
```python
# User wants to correct their last question
user_message = await session.pop_item()  # Remove user's question
assistant_message = await session.pop_item()  # Remove agent's response

# Ask a corrected question
result = await Runner.run(
    agent,
    "What's 2 + 3?",  # Corrected question
    session=session
)
```

## Technical Details

### Session Protocol Design
- **Async-first**: All operations are async for non-blocking I/O
- **Type-safe**: Full type hints with runtime validation
- **Error handling**: Graceful degradation and detailed error messages
- **Resource management**: Proper cleanup and connection handling

### SQLiteSession Implementation
- **Thread-safe operations** with connection pooling
- **Automatic schema management** with proper indexing
- **JSON serialization** for message storage
- **Memory-efficient** conversation retrieval and storage
- **Cross-platform compatibility**

## Breaking Changes

None. This is a purely additive feature that doesn't affect existing
functionality.

## Documentation

- Updated core concepts in `docs/index.md` to highlight Sessions as a
key primitive
- New comprehensive guide at `docs/sessions.md` with protocol
implementation examples
- Enhanced `docs/running_agents.md` with automatic vs manual
conversation management
- Full API reference integration via `docs/ref/memory.md`
- Implementation guide for library authors

Sessions represent a significant architectural improvement for building
conversational AI applications with the Agents SDK. The extensible
Session protocol enables the ecosystem to provide specialized storage
backends while maintaining a consistent, simple API for application
developers.

---------

Co-authored-by: Rohan Mehta <rm@openai.com>
2025-07-10 12:18:49 -04:00
Daniel Hashmi f09874c6be Fix agent lifecycle example output to reflect correct hook execution order (#1015)
**Problem:**
The expected output in the agent lifecycle example incorrectly shows
agent start hooks (`on_start`) running after tool execution and multiple
times for the same agent. This misleads developers about when these
lifecycle events actually occur.

**Solution:**
Updated the expected output to accurately reflect the OpenAI Agents
framework behavior:
- Agent start hooks run immediately when an agent begins execution
- Start hooks only run once per agent activation, controlled by the
`should_run_agent_start_hooks` flag
- After handoffs, the new agent's start hook runs as the first event
2025-07-08 11:14:16 -04:00
CCM 0475450d59 replace .py file with .ipynb for Jupyter example (#262)
Co-authored-by: chenchaomin <chenchaomin@guazi.com>
2025-06-27 10:39:49 -04:00
Rohan Mehta 2b9b8f7e73 Prompts support (#876)
Add support for the new openai prompts feature.
2025-06-16 15:47:48 -04:00