Skip to content

Commit a66d239

Browse files
feat(examples): OpenAI Agents SDK local-sandbox tutorials (sync + async + temporal) (#377)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent ab5a7d9 commit a66d239

46 files changed

Lines changed: 3512 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Python
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
*.so
6+
.Python
7+
build/
8+
develop-eggs/
9+
dist/
10+
downloads/
11+
eggs/
12+
.eggs/
13+
lib/
14+
lib64/
15+
parts/
16+
sdist/
17+
var/
18+
wheels/
19+
*.egg-info/
20+
.installed.cfg
21+
*.egg
22+
23+
# Environments
24+
.env**
25+
.venv
26+
env/
27+
venv/
28+
ENV/
29+
env.bak/
30+
venv.bak/
31+
32+
# IDE
33+
.idea/
34+
.vscode/
35+
*.swp
36+
*.swo
37+
38+
# Git
39+
.git
40+
.gitignore
41+
42+
# Misc
43+
.DS_Store
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# syntax=docker/dockerfile:1.3
2+
FROM python:3.12-slim
3+
COPY --from=ghcr.io/astral-sh/uv:0.6.4 /uv /uvx /bin/
4+
5+
# Install system dependencies
6+
RUN apt-get update && apt-get install -y \
7+
htop \
8+
vim \
9+
curl \
10+
tar \
11+
python3-dev \
12+
postgresql-client \
13+
build-essential \
14+
libpq-dev \
15+
gcc \
16+
cmake \
17+
netcat-openbsd \
18+
&& apt-get clean \
19+
&& rm -rf /var/lib/apt/lists/*
20+
21+
RUN uv pip install --system --upgrade pip setuptools wheel
22+
23+
ENV UV_HTTP_TIMEOUT=1000
24+
25+
# Copy pyproject.toml and README.md to install dependencies
26+
COPY 00_sync/050_openai_agents_local_sandbox/pyproject.toml /app/050_openai_agents_local_sandbox/pyproject.toml
27+
COPY 00_sync/050_openai_agents_local_sandbox/README.md /app/050_openai_agents_local_sandbox/README.md
28+
29+
WORKDIR /app/050_openai_agents_local_sandbox
30+
31+
# Copy the project code
32+
COPY 00_sync/050_openai_agents_local_sandbox/project /app/050_openai_agents_local_sandbox/project
33+
34+
# Copy the test files
35+
COPY 00_sync/050_openai_agents_local_sandbox/tests /app/050_openai_agents_local_sandbox/tests
36+
37+
# Copy shared test utilities
38+
COPY test_utils /app/test_utils
39+
40+
# Install the required Python packages with dev dependencies
41+
RUN uv pip install --system .[dev]
42+
43+
# Set environment variables
44+
ENV PYTHONPATH=/app
45+
46+
# Set test environment variables
47+
ENV AGENT_NAME=s050-openai-agents-local-sandbox
48+
49+
# Run the agent using uvicorn
50+
CMD ["uvicorn", "project.acp:acp", "--host", "0.0.0.0", "--port", "8000"]
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Tutorial 050: Sync OpenAI Agents SDK with a Local Sandbox
2+
3+
This tutorial demonstrates how to build a **synchronous** agent on AgentEx using the
4+
[OpenAI Agents SDK](https://developers.openai.com/api/docs/guides/agents) and its
5+
**sandbox** runtime, running with the **local** (`unix_local`) backend.
6+
7+
The agent is a "local sandbox assistant": it answers questions by actually running
8+
real shell commands (e.g. `python3 --version`, `ls /tmp`, `python3 -c "..."`)
9+
instead of guessing.
10+
11+
## Key Concepts
12+
13+
### Sync ACP
14+
The sync ACP model uses HTTP request/response for communication. The
15+
`@acp.on_message_send` handler receives a message, runs the agent, and returns the
16+
agent's final answer as a `TextContent`.
17+
18+
### OpenAI Agents SDK Sandbox
19+
The OpenAI Agents SDK ships `agents.sandbox`, which lets you give an agent
20+
**capabilities** (instead of hand-written tools) that the runtime turns into real
21+
tools backed by a sandbox:
22+
23+
- **`SandboxAgent`**: an `Agent` that is granted sandbox capabilities.
24+
- **Capabilities** (`from agents.sandbox.capabilities import Shell, Filesystem, Memory`):
25+
each capability expands into a set of real tools. This tutorial uses `Shell`, which
26+
lets the model run real shell commands.
27+
- **`SandboxRunConfig`** + a sandbox **client**: tells the runtime *where* the tools
28+
actually execute.
29+
30+
### The LOCAL sandbox (`UnixLocalSandboxClient`)
31+
This tutorial uses the local backend
32+
(`from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient, UnixLocalSandboxClientOptions`),
33+
`backend_id="unix_local"`. The local sandbox runs shell commands **ON THE HOST**
34+
the agent's own container/process. There is **no Docker, no Temporal, and no remote
35+
sandbox infrastructure** involved. This makes it the simplest way to give an agent a
36+
real shell.
37+
38+
The sandbox is wired up through the SDK's `RunConfig`:
39+
40+
```python
41+
from agents import Runner, set_tracing_disabled
42+
from agents.run_config import RunConfig
43+
from agents.sandbox import SandboxAgent, SandboxRunConfig
44+
from agents.sandbox.capabilities import Shell
45+
from agents.sandbox.sandboxes.unix_local import (
46+
UnixLocalSandboxClient,
47+
UnixLocalSandboxClientOptions,
48+
)
49+
50+
set_tracing_disabled(True) # avoid api.openai.com tracing 401 behind a gateway
51+
52+
agent = SandboxAgent(
53+
name="Local Sandbox Assistant",
54+
instructions="...use the shell tools to actually run commands...",
55+
capabilities=[Shell()],
56+
)
57+
run_config = RunConfig(
58+
sandbox=SandboxRunConfig(
59+
client=UnixLocalSandboxClient(),
60+
options=UnixLocalSandboxClientOptions(),
61+
)
62+
)
63+
result = await Runner.run(agent, input="what's the python version?", run_config=run_config)
64+
print(result.final_output)
65+
```
66+
67+
`Runner.run` drives the full tool-call loop internally: the model issues shell
68+
commands, the local sandbox runs them on the host, the output is fed back, and the
69+
loop continues until the model produces a final answer.
70+
71+
## Files
72+
73+
| File | Description |
74+
|------|-------------|
75+
| `project/acp.py` | ACP server and message handler (runs the sandbox agent) |
76+
| `project/agent.py` | `SandboxAgent` + `RunConfig(sandbox=...)` wiring + `run_agent` |
77+
| `project/tools.py` | Sandbox capability factory (`Shell`) |
78+
| `tests/test_agent.py` | Integration tests |
79+
| `manifest.yaml` | Agent configuration |
80+
81+
## Running Locally
82+
83+
```bash
84+
# From this directory
85+
agentex agents run
86+
```
87+
88+
Set `OPENAI_API_KEY` (or `LITELLM_API_KEY` if you're behind the Scale LiteLLM
89+
gateway) in your environment or in a `.env` file in `project/` so the agent can call
90+
the model.
91+
92+
## Running Tests
93+
94+
```bash
95+
pytest tests/test_agent.py -v
96+
```
97+
98+
## Notes
99+
100+
- **No infra required.** Because this uses the `unix_local` backend, the shell tools
101+
run directly in the agent's process — no Docker daemon, no Temporal, no remote
102+
sandbox. Swap the client for a remote/containerized backend to isolate execution.
103+
- **Tracing.** `set_tracing_disabled(True)` turns off the OpenAI Agents SDK's native
104+
tracer (which would otherwise try to ship traces to `api.openai.com`). The manifest
105+
also sets `OPENAI_AGENTS_DISABLE_TRACING=1`. AgentEx/SGP tracing still runs via the
106+
tracing manager configured in `acp.py` when SGP credentials are present.
107+
- **Capabilities are the tools.** To let the agent do more, add capabilities in
108+
`project/tools.py` (e.g. `Filesystem()`, `Memory()`).
109+
110+
## Further Reading
111+
112+
- OpenAI Agents SDK guide: https://developers.openai.com/api/docs/guides/agents
113+
- The next evolution of the Agents SDK: https://openai.com/index/the-next-evolution-of-the-agents-sdk/
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
build:
2+
context:
3+
root: ../../
4+
include_paths:
5+
- 00_sync/050_openai_agents_local_sandbox
6+
- test_utils
7+
dockerfile: 00_sync/050_openai_agents_local_sandbox/Dockerfile
8+
dockerignore: 00_sync/050_openai_agents_local_sandbox/.dockerignore
9+
10+
local_development:
11+
agent:
12+
port: 8000
13+
host_address: host.docker.internal
14+
paths:
15+
acp: project/acp.py
16+
17+
agent:
18+
acp_type: sync
19+
name: s050-openai-agents-local-sandbox
20+
description: A sync OpenAI Agents SDK agent using a local (unix_local) sandbox
21+
22+
temporal:
23+
enabled: false
24+
25+
credentials:
26+
- env_var_name: OPENAI_API_KEY
27+
secret_name: openai-api-key
28+
secret_key: api-key
29+
- env_var_name: REDIS_URL
30+
secret_name: redis-url-secret
31+
secret_key: url
32+
- env_var_name: SGP_API_KEY
33+
secret_name: sgp-api-key
34+
secret_key: api-key
35+
- env_var_name: SGP_ACCOUNT_ID
36+
secret_name: sgp-account-id
37+
secret_key: account-id
38+
- env_var_name: SGP_CLIENT_BASE_URL
39+
secret_name: sgp-client-base-url
40+
secret_key: url
41+
42+
env:
43+
OPENAI_AGENTS_DISABLE_TRACING: "1"
44+
45+
deployment:
46+
image:
47+
repository: ""
48+
tag: "latest"
49+
50+
global:
51+
agent:
52+
name: "s050-openai-agents-local-sandbox"
53+
description: "A sync OpenAI Agents SDK agent using a local (unix_local) sandbox"
54+
replicaCount: 1
55+
resources:
56+
requests:
57+
cpu: "500m"
58+
memory: "1Gi"
59+
limits:
60+
cpu: "1000m"
61+
memory: "2Gi"

examples/tutorials/00_sync/050_openai_agents_local_sandbox/project/__init__.py

Whitespace-only changes.
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""ACP (Agent Communication Protocol) handler for Agentex.
2+
3+
This is the API layer — it owns the agent lifecycle and runs the OpenAI Agents
4+
SDK *sandbox* agent for each incoming message, returning the agent's final
5+
answer to the Agentex frontend.
6+
7+
The agent uses the LOCAL sandbox backend (``UnixLocalSandboxClient``), which runs
8+
shell commands on the host (this process/container). The OpenAI Agents SDK runs
9+
its tool-call loop internally via ``Runner.run`` and returns the final output, so
10+
this sync handler returns a single ``TextContent`` rather than streaming tokens.
11+
"""
12+
13+
from __future__ import annotations
14+
15+
import os
16+
17+
from dotenv import load_dotenv
18+
19+
load_dotenv()
20+
21+
from agentex.lib import adk
22+
from project.agent import run_agent
23+
from agentex.lib.types.acp import SendMessageParams
24+
from agentex.lib.types.tracing import SGPTracingProcessorConfig
25+
from agentex.lib.utils.logging import make_logger
26+
from agentex.types.text_content import TextContent
27+
from agentex.lib.sdk.fastacp.fastacp import FastACP
28+
from agentex.types.task_message_content import TaskMessageContent
29+
from agentex.lib.core.tracing.tracing_processor_manager import (
30+
add_tracing_processor_config,
31+
)
32+
33+
logger = make_logger(__name__)
34+
35+
# LiteLLM proxy auth: copy LITELLM_API_KEY to OPENAI_API_KEY for OpenAI client
36+
# compatibility, so the same example works behind the Scale LiteLLM gateway.
37+
_litellm_key = os.environ.get("LITELLM_API_KEY")
38+
if _litellm_key and not os.environ.get("OPENAI_API_KEY"):
39+
os.environ["OPENAI_API_KEY"] = _litellm_key
40+
41+
SGP_API_KEY = os.environ.get("SGP_API_KEY", "")
42+
SGP_ACCOUNT_ID = os.environ.get("SGP_ACCOUNT_ID", "")
43+
SGP_CLIENT_BASE_URL = os.environ.get("SGP_CLIENT_BASE_URL", "")
44+
45+
if SGP_API_KEY and SGP_ACCOUNT_ID:
46+
add_tracing_processor_config(
47+
SGPTracingProcessorConfig(
48+
sgp_api_key=SGP_API_KEY,
49+
sgp_account_id=SGP_ACCOUNT_ID,
50+
sgp_base_url=SGP_CLIENT_BASE_URL,
51+
)
52+
)
53+
54+
acp = FastACP.create(acp_type="sync")
55+
56+
57+
@acp.on_message_send
58+
async def handle_message_send(
59+
params: SendMessageParams,
60+
) -> TaskMessageContent:
61+
"""Handle incoming messages by running the local-sandbox agent."""
62+
task_id = params.task.id
63+
user_message = params.content.content
64+
logger.info(f"Processing message for task {task_id}")
65+
66+
async with adk.tracing.span(
67+
trace_id=task_id,
68+
task_id=task_id,
69+
name="message",
70+
input={"message": user_message},
71+
data={"__span_type__": "AGENT_WORKFLOW"},
72+
) as turn_span:
73+
final_output = await run_agent(user_message)
74+
if turn_span:
75+
turn_span.output = {"final_output": final_output}
76+
77+
return TextContent(author="agent", content=final_output)

0 commit comments

Comments
 (0)