Skip to content

Commit d3dc43c

Browse files
feat: add self-hosted sandbox example (#1027)
1 parent 9892925 commit d3dc43c

27 files changed

Lines changed: 2268 additions & 2 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,8 @@ cython_debug/
205205
.trae
206206
.claude
207207
.agents
208+
.adk/
209+
**/.adk/
208210
# AgentKit deploy config (contains account-specific secrets)
209211
agentkit.yaml
210212
agentkit*.yaml

‎docs/content/docs/framework/agent/runtime.en.mdx‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,31 @@ agent = Agent(
6363

6464
Codex-native lifecycle notifications and ADK Function/MCP tool calls are converted into ADK Events. Runtime logs use stable `codex_*` event names and attribution fields such as `invocation_id`, `call_id`, `tool`, `status`, and `duration_ms`. Tool arguments, tool results, API tokens, credentials, and backend addresses are not logged. Token usage is exposed through `codex_event_type=token_usage` events and the corresponding log entry.
6565

66+
## Choose where each tool runs
67+
68+
`RuntimeProvider` leaves the Agent's model reasoning loop unchanged and only decides where individual tool calls execute. `DispatchRuntimeProvider` can send selected tools to a remote runtime while falling back to their original ADK implementation for all other tools:
69+
70+
```python title="agent.py"
71+
from veadk import Agent, Runner
72+
from veadk.runtime import DispatchRuntimeProvider
73+
74+
async def dispatch_task(tool_call):
75+
return await remote_client.dispatch(
76+
tool_call.name,
77+
tool_call.arguments,
78+
dispatch_id=tool_call.id,
79+
)
80+
81+
agent = Agent(name="assistant", tools=[bash, read_file])
82+
runtime_provider = DispatchRuntimeProvider(
83+
dispatch_task,
84+
dispatchable_tools=None, # dispatch every non-MCP tool
85+
)
86+
runner = Runner(agent=agent, plugins=[runtime_provider])
87+
```
88+
89+
In this example, every non-MCP tool only goes through `dispatch_task` and its local function is not invoked a second time. MCP tools retain their original ADK implementation. Pass a set of names to dispatch only those non-MCP tools. The dispatcher may be synchronous or asynchronous.
90+
6691
## Request processing
6792

6893
Insert shared, cross-cutting processing into every run — auth, logging, retries, performance monitoring — without touching business logic. Pass a processor to `run_processor`, for example to enforce login via identity auth:

‎docs/content/docs/framework/agent/runtime.mdx‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,31 @@ agent = Agent(
6363

6464
Codex 原生生命周期和 ADK Function/MCP 工具调用都会转换为 ADK Event。运行日志使用稳定的 `codex_*` 事件名,并包含 `invocation_id`、`call_id`、`tool`、`status`、`duration_ms` 等可归因字段。日志不会记录工具参数、工具结果、API Token、凭证或后端地址;Token Usage 通过 `codex_event_type=token_usage` 事件及对应日志提供。
6565

66+
## 按工具选择执行位置
67+
68+
`RuntimeProvider` 不替换智能体的模型推理循环,只决定单次工具调用在哪里执行。`DispatchRuntimeProvider` 可以把指定工具派发到远端,其余工具回退到原本的 ADK 本地实现:
69+
70+
```python title="agent.py"
71+
from veadk import Agent, Runner
72+
from veadk.runtime import DispatchRuntimeProvider
73+
74+
async def dispatch_task(tool_call):
75+
return await remote_client.dispatch(
76+
tool_call.name,
77+
tool_call.arguments,
78+
dispatch_id=tool_call.id,
79+
)
80+
81+
agent = Agent(name="assistant", tools=[bash, read_file])
82+
runtime_provider = DispatchRuntimeProvider(
83+
dispatch_task,
84+
dispatchable_tools=None, # 派发所有非 MCP 工具
85+
)
86+
runner = Runner(agent=agent, plugins=[runtime_provider])
87+
```
88+
89+
上例中所有非 MCP 工具只会经过 `dispatch_task`,不会再次执行本地函数;MCP 工具保留原本的 ADK 实现。传入具体工具名集合时,只派发集合中的非 MCP 工具。派发函数可以是同步或异步函数。
90+
6691
## 请求处理
6792

6893
在不侵入业务逻辑的前提下,可为每次执行插入统一的横切处理——鉴权、日志、重试、性能监控等。把处理器传入 `run_processor` 即可,例如接入身份认证做登录态校验:

‎docs/content/docs/framework/memory/short-term/index.en.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ stm = ShortTermMemory(backend="sqlite", local_database_path="./stm.db")
3131
| `db_kwargs` | `dict` | `{}` | Extra args forwarded to the underlying database session service/driver (e.g. connection pool settings). |
3232
| `local_database_path` | `str` | `/tmp/veadk_local_database.db` | Local DB file path, used only by `sqlite`. |
3333
| `after_load_memory_callback` | `Callable \| None` | `None` | Callback invoked after a session is loaded; receives the loaded `Session`. |
34+
| `after_create_session_callback` | `Callable \| None` | `None` | Synchronous or asynchronous callback invoked after a new session is created; receives the new `Session` and is not invoked when an existing session is reused. |
3435

3536
<Callout type="warn">
3637
If a username or password in the connection string contains special characters such as `@` or `:`, URL-encode it with `urllib.parse.quote_plus` first (e.g. `p@ssword` → `p%40ssword`), otherwise parsing fails.
@@ -102,6 +103,19 @@ You rarely create or manage a `Session` directly; instead you use `session_servi
102103

103104
Under a database backend, `ShortTermMemory.create_session()` first lists and reuses an existing session with the same `session_id` to avoid duplicates.
104105

106+
To provision resources, record an audit event, or synchronize an external system after a session is first created, register `after_create_session_callback`:
107+
108+
```python
109+
async def after_create_session(session):
110+
await provision_external_resources(session.id)
111+
112+
stm = ShortTermMemory(
113+
after_create_session_callback=after_create_session,
114+
)
115+
```
116+
117+
The callback runs only when a new session is actually created. If it raises an exception, that exception is propagated to the caller and agent execution does not continue.
118+
105119
## Context compaction
106120

107121
As a conversation grows, the history keeps expanding, increasing what the model must process and slowing responses. Context compaction summarizes the history with a sliding window: when the history exceeds a threshold, older events are compacted automatically.

‎docs/content/docs/framework/memory/short-term/index.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ stm = ShortTermMemory(backend="sqlite", local_database_path="./stm.db")
3131
| `db_kwargs` | `dict` | `{}` | 透传给底层数据库会话服务/驱动的额外参数(如连接池配置)。 |
3232
| `local_database_path` | `str` | `/tmp/veadk_local_database.db` | 仅 `sqlite` 使用的本地数据库文件路径。 |
3333
| `after_load_memory_callback` | `Callable \| None` | `None` | 读取会话后触发的回调,入参为加载到的 `Session`。 |
34+
| `after_create_session_callback` | `Callable \| None` | `None` | 新会话创建成功后触发的同步或异步回调,入参为新建的 `Session`;复用已有会话时不触发。 |
3435

3536
<Callout type="warn">
3637
当连接串里的用户名或密码包含 `@`、`:` 等特殊字符时,请先用 `urllib.parse.quote_plus` 编码(例如 `p@ssword` → `p%40ssword`),否则解析会出错。
@@ -102,6 +103,19 @@ asyncio.run(main())
102103

103104
`ShortTermMemory.create_session()` 在数据库后端下会先列出并复用同 `session_id` 的已有会话,避免重复创建。
104105

106+
如果需要在会话首次创建后执行资源准备、审计或外部系统同步,可以注册 `after_create_session_callback`:
107+
108+
```python
109+
async def after_create_session(session):
110+
await provision_external_resources(session.id)
111+
112+
stm = ShortTermMemory(
113+
after_create_session_callback=after_create_session,
114+
)
115+
```
116+
117+
回调只在真正创建新会话时执行。如果回调抛出异常,异常会传递给调用方,Agent 不会继续执行。
118+
105119
## 上下文压缩
106120

107121
随着会话进行,历史会不断增长,导致模型处理的数据变多、响应变慢。上下文压缩用滑动窗口汇总历史:当会话历史超过设定阈值时,自动压缩较早的事件。
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Copy this file to `.env` and fill in your values:
2+
# cp examples/16_self_host_sandbox/.env.example examples/16_self_host_sandbox/.env
3+
4+
# --- Managed Runtime connection ---
5+
# BOE Runtime 7hw8g3yr exposes its Managed Sessions gateway through this URL.
6+
ANTHROPIC_BASE_URL=https://<runtime-apig-domain>.apigateway-cn-beijing.volceapi.com
7+
ANTHROPIC_ENVIRONMENT_ID=env_your_runtime_environment_id
8+
ANTHROPIC_ENVIRONMENT_KEY=your_runtime_environment_key
9+
SANDBOX_AGENT_ID=agent_your_managed_agent_id
10+
X_TOP_ACCOUNT_ID=your_volcengine_account_id
11+
12+
# --- Web Server Configuration ---
13+
PORT=8067
14+
# Comma-separated origins when the Dev UI is accessed through another origin.
15+
# ALLOW_ORIGINS=http://localhost:3000,https://your-dev-proxy.example.com
16+
17+
# Maximum time to wait for a remote Runtime turn, including tool execution.
18+
# SANDBOX_TIMEOUT_SECONDS=300
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
FROM python:3.12-slim-bookworm
2+
3+
ENV PYTHONUNBUFFERED=1 \
4+
PYTHONDONTWRITEBYTECODE=1 \
5+
UV_COMPILE_BYTECODE=1 \
6+
UV_LINK_MODE=copy \
7+
PORT=8067
8+
9+
WORKDIR /app
10+
11+
# Install this checkout so the image contains the same VeADK implementation as
12+
# the example. The sandbox extra supplies the Anthropic managed-session client.
13+
COPY --from=ghcr.io/astral-sh/uv:0.11.28 /uv /uvx /bin/
14+
COPY pyproject.toml uv.lock README.md LICENSE ./
15+
COPY veadk ./veadk
16+
COPY frontend ./frontend
17+
RUN uv sync --frozen --no-dev --extra sandbox
18+
19+
COPY examples/16_self_host_sandbox ./examples/16_self_host_sandbox
20+
RUN chmod +x ./examples/16_self_host_sandbox/run.sh \
21+
&& useradd --create-home --uid 10001 veadk \
22+
&& chown -R veadk:veadk /app
23+
24+
USER veadk
25+
EXPOSE 8067
26+
27+
CMD ["bash", "examples/16_self_host_sandbox/run.sh", "--web", "--host", "0.0.0.0", "--port", "8067"]
28+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
.git
2+
.github
3+
.venv
4+
**/.env
5+
**/.env.*
6+
!**/.env.example
7+
**/__pycache__
8+
**/*.py[cod]
9+
**/.pytest_cache
10+
**/.ruff_cache
11+
**/node_modules
12+
docs
13+
tests
14+
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# 16. Self-Hosted Sandbox Agent Demo
2+
3+
This example runs the conversation and model loop in `veadk web`. Each new VeADK Web session creates exactly one remote Managed Session. Only VeADK-generated `agent.tool_use` events are sent to the Self-Hosted Runtime dispatcher, which creates a TAE Tool session for the configured Sandbox.
4+
5+
---
6+
7+
## 🎯 Architecture
8+
9+
```text
10+
[ User Prompt ]
11+
│
12+
▼
13+
┌───────────────────────┐
14+
│ VeADK Web │
15+
│ model + agent loop │
16+
└──────────┬────────────┘
17+
│ POST agent.tool_use
18+
▼
19+
┌───────────────────────────┐
20+
│ Runtime 7hw8g3yr │
21+
│ dispatcher only │
22+
└──────────┬────────────────┘
23+
│ creates one tool session
24+
▼
25+
┌────────────────────────────────────────┐
26+
│ TAE Sandbox Tool m3m24zxs │
27+
│ executes the Runtime's tool calls │
28+
└────────────────────────────────────────┘
29+
```
30+
31+
---
32+
33+
## 🚀 Quick Start
34+
35+
### 1. Configure Environment Variables
36+
37+
Copy the example environment configuration file and update it with your credentials:
38+
39+
```bash
40+
cp examples/16_self_host_sandbox/.env.example examples/16_self_host_sandbox/.env
41+
```
42+
43+
Alternatively, export variables directly:
44+
45+
```bash
46+
export ANTHROPIC_BASE_URL="https://<runtime-gateway>"
47+
export ANTHROPIC_ENVIRONMENT_ID="env_01SLqXHseguCmohifEqeUAYu"
48+
export ANTHROPIC_ENVIRONMENT_KEY="your-runtime-token"
49+
export SANDBOX_AGENT_ID="agent_your_managed_agent_id"
50+
export X_TOP_ACCOUNT_ID="your-account-id"
51+
```
52+
53+
The local VeADK process needs its normal model configuration. Model reasoning happens in VeADK; only tool execution is delegated to the remote Runtime and Sandbox.
54+
55+
56+
### 2. Run the Demo
57+
58+
#### Option A: Web UI Mode (`veadk web`)
59+
60+
Run the visual web debugging interface in your browser (defaults to port **8067**, configurable via `PORT` in `.env` or `--port`):
61+
62+
```bash
63+
# Via run.sh helper (automatically switches to agents dir and applies port 8067)
64+
bash examples/16_self_host_sandbox/run.sh --web
65+
66+
# Or directly in the agents directory
67+
cd examples/16_self_host_sandbox/agents
68+
veadk web --port 8067
69+
```
70+
71+
72+
73+
74+
#### Option B: CLI Mode
75+
76+
```bash
77+
# Run with run.sh helper
78+
bash examples/16_self_host_sandbox/run.sh
79+
80+
# Or using uv
81+
uv run --extra sandbox python examples/16_self_host_sandbox/main.py
82+
83+
# Or select an existing local-to-remote session mapping
84+
python examples/16_self_host_sandbox/main.py \
85+
--session-id "my-local-session" \
86+
--prompt "Create a Python script in /workspace and run it with pytest."
87+
```
88+
89+
90+
`ShortTermMemory.after_create_session_callback` creates one remote Managed Session
91+
for each newly created VeADK session. VeADK handles the user message and model
92+
loop locally. `DispatchRuntimeProvider` intercepts each model tool call, posts an
93+
`agent.tool_use`, waits for its matching tool result, and returns that result to
94+
the local VeADK model loop.
95+
96+
## Docker and Kubernetes deployment
97+
98+
Use the repository root as the Docker build context:
99+
100+
```bash
101+
docker build \
102+
-f examples/16_self_host_sandbox/Dockerfile \
103+
-t <registry>/veadk-self-host-sandbox:<tag> \
104+
.
105+
docker push <registry>/veadk-self-host-sandbox:<tag>
106+
```
107+
108+
Replace the image and Ingress host in `k8s.yaml` for the target environment. Then
109+
create an allowlisted Secret from the local `.env` and deploy the workload:
110+
111+
```bash
112+
set -a
113+
source examples/16_self_host_sandbox/.env
114+
set +a
115+
116+
kubectl create secret generic veadk-self-host-sandbox-env \
117+
--from-literal=ANTHROPIC_BASE_URL="$ANTHROPIC_BASE_URL" \
118+
--from-literal=ANTHROPIC_ENVIRONMENT_ID="$ANTHROPIC_ENVIRONMENT_ID" \
119+
--from-literal=ANTHROPIC_ENVIRONMENT_KEY="$ANTHROPIC_ENVIRONMENT_KEY" \
120+
--from-literal=SANDBOX_AGENT_ID="$SANDBOX_AGENT_ID" \
121+
--from-literal=X_TOP_ACCOUNT_ID="$X_TOP_ACCOUNT_ID" \
122+
--dry-run=client -o yaml | kubectl apply -f -
123+
124+
kubectl apply -f examples/16_self_host_sandbox/k8s.yaml
125+
kubectl rollout status deployment/veadk-self-host-sandbox
126+
```
127+
128+
Do not create the Secret from the entire `.env`. The Deployment only injects
129+
the allowlisted Runtime connection values above.
130+
131+
## Development verification
132+
133+
The repository virtual environment may omit test dependencies when it was
134+
created for runtime use only. Install the development dependency group before
135+
running the focused dispatch tests:
136+
137+
```bash
138+
uv sync --group dev --extra sandbox
139+
uv run pytest -q tests/runtime/test_self_host_sandbox_client.py \
140+
tests/runtime/test_self_host_sandbox_agent.py
141+
```

0 commit comments

Comments
 (0)