PAI-Instant Service は、一般的なエージェントシナリオ向けに、事前構築済みのパブリックテンプレートを提供します。対象シナリオは、コード実行、ブラウザ自動化、デスクトップ自動化、AI コーディングです。ユースケースに基づいてテンプレートを選択し、追加設定なしでインスタンスを作成できます。
概要
パブリックテンプレートは EAS プラットフォームによって事前構築されており、追加設定なしで任意のインスタントサービスワークベンチで使用できます。各テンプレートは、特定のエージェントシナリオ向けにランタイム環境を事前設定しており、事前インストール済みのライブラリ、事前起動済みのサービス、事前設定済みのポートが含まれます。
テンプレートの比較
|
エージェントシナリオ |
推奨テンプレート |
主な機能 |
|
コードインタープリター / データ分析 |
|
Python 3.11 (numpy、pandas、matplotlib、sklearn を含む)、JavaScript、TypeScript |
|
ブラウザ自動化 / Web 検索 |
|
Playwright と MCP のデュアルプロトコルアクセスに対応した Chromium |
|
デスクトップ GUI 自動化 / スクリーンショット |
|
リモートデスクトップと UI 自動化 SDK を備えた Ubuntu 22.04 |
|
AI コーディング (Claude) |
|
Bailian API アクセスを備えた Claude CLI |
|
AI コーディング (オープンソース) |
|
opencode と opencode サーバー |
|
汎用タスクエージェント |
|
Bailian API アクセスを備えた汎用タスクエージェントフレームワーク |
前提条件
パブリックテンプレートを使用する前に:
-
インスタントサービスを作成します。
-
[Template Details] ページで、右上の [SDK Access] をクリックし、E2B_DOMAIN、E2B_API_KEY、およびテンプレート ID を取得します。
説明パブリックテンプレートでは、インスタントサービスワークベンチレベルのトークンを E2B_API_KEY として使用します。インスタントサービスワークベンチの作成時にカスタムトークンを設定して、自動生成されたトークンを置き換えることもできます。
-
E2B SDK をインストールします (v2.25.0 より前のバージョンのみサポート):
pip install "e2b<2.25.0"。
code-interpreter
code-interpreter のパブリックテンプレートは、Python 3.11、JavaScript、TypeScript を備えた開発環境を提供します。 e2b_code_interpreter SDK を使用して、コードを実行し、ファイルを管理できます。
pip install e2b_code_interpreter
import os
import time
from e2b_code_interpreter import Sandbox
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
sandbox = Sandbox.create(template="code-interpreter", timeout=300000)
# サンドボックスの準備が完了するまで待機します
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
# Python のコード実行
execution = sandbox.run_code("print('hello world')")
print(execution.logs)
sandbox.run_code("x = 42")
execution = sandbox.run_code("print(f'x = {x}')")
print(execution.logs.stdout)
# JavaScript
result = sandbox.commands.run("node -e \"console.log('Hello from Node.js')\"")
print(result.stdout)
# TypeScript
result = sandbox.commands.run("tsx -e \"const msg: string = 'Hello from TypeScript'; console.log(msg)\"")
print(result.stdout)
# ファイル操作
entries = sandbox.files.list("/home/user")
for e in entries:
print(f"{e.type}\t{e.name}")
sandbox.files.write("/home/user/hello.txt", "Hello from sandbox")
content = sandbox.files.read("/home/user/hello.txt")
print(content)
browser
browser のパブリックテンプレートには、事前インストール済みの Chromium ブラウザが含まれており、2 つのアクセス方法を提供します。8080 番ポートの CDP (Chrome DevTools Protocol) と、50005 番ポートの MCP です。エージェントは、これらのインターフェイスを使用して、Playwright または MCP によりブラウザ操作を自動化できます。
オプション 1:Playwright
クライアントに Playwright をインストールします:
pip install playwright
CDP WebSocket エンドポイント経由でインスタンスのブラウザに接続し、Playwright API を使用して、ページ遷移、スクリーンショット、要素抽出を実行します:
import asyncio
import os
import time
from urllib.parse import quote_plus
import httpx
from e2b import Sandbox
from playwright.async_api import async_playwright
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
GATEWAY_PORT = 8080
sandbox = Sandbox.create(template="browser", timeout=300000)
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
# 認証ヘッダー (すべてのリクエストで必須)
def _auth_headers():
return {
"X-Access-Token": getattr(sandbox, '_SandboxBase__envd_access_token', None),
"E2b-Sandbox-Id": sandbox.sandbox_id,
}
# CDP WebSocket URL を取得します
def get_cdp_url():
gateway_host = sandbox.get_host(GATEWAY_PORT)
resp = httpx.get(
f"https://{gateway_host}/json/version",
headers=_auth_headers(), timeout=10, verify=False,
)
resp.raise_for_status()
guid = resp.json()["webSocketDebuggerUrl"].rsplit("/", 1)[-1]
return f"wss://{gateway_host}/devtools/browser/{guid}"
async def search_with_playwright(query: str):
cdp_url = get_cdp_url()
print(f"CDP URL: {cdp_url}")
async with async_playwright() as p:
browser = await p.chromium.connect_over_cdp(cdp_url, headers=_auth_headers())
if browser.contexts and browser.contexts[0].pages:
page = browser.contexts[0].pages[0]
else:
page = await (await browser.new_context()).new_page()
# 遷移
search_url = f"https://www.bing.com/search?q={quote_plus(query)}"
await page.goto(search_url, wait_until="load", timeout=30000)
print(f"Navigated to: {search_url}")
# 検索結果がレンダリングされるまで待機
try:
await page.wait_for_selector("li.b_algo", timeout=10000)
except Exception:
await page.wait_for_timeout(3000)
# スクリーンショットを取得
with open("screenshot.png", "wb") as f:
f.write(await page.screenshot(full_page=True))
print("Screenshot saved: screenshot.png")
# 検索結果を抽出
results = await page.evaluate("""() => {
const items = document.querySelectorAll('li.b_algo h2 a');
return Array.from(items).slice(0, 5).map(a => ({
title: a.textContent || '',
url: a.href || ''
}));
}""")
await browser.close()
return results
if __name__ == "__main__":
results = asyncio.run(search_with_playwright("Python latest release"))
for i, r in enumerate(results, 1):
print(f" {i}. {r['title']} — {r['url']}")
オプション 2:MCP
クライアントに MCP をインストールします:
pip install mcp
ページオブジェクトを直接管理せずに、MCP プロトコルを使用してセマンティックなブラウザツールを利用します:
import asyncio
import os
import time
from urllib.parse import quote_plus
import httpx
from e2b import Sandbox
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
MCP_PORT = 50005
sandbox = Sandbox.create(template="browser", timeout=300000)
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
def _auth_headers():
return {
"X-Access-Token": getattr(sandbox, '_SandboxBase__envd_access_token', None),
"E2b-Sandbox-Id": sandbox.sandbox_id,
}
def get_mcp_url():
return f"https://{sandbox.get_host(MCP_PORT)}/mcp"
async def search_with_mcp(query: str):
mcp_url = get_mcp_url()
print(f"MCP URL: {mcp_url}")
client = httpx.AsyncClient(headers=_auth_headers(), verify=False)
async with client:
async with streamable_http_client(mcp_url, http_client=client) as (
read_stream, write_stream, _,
):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
print("MCP session initialized")
# 遷移
search_url = f"https://www.bing.com/search?q={quote_plus(query)}"
await session.call_tool("browser_navigate", {"url": search_url})
print(f"Navigated to: {search_url}")
# ページの読み込みを待機
await session.call_tool("browser_wait_for", {"time": 2})
# ページスナップショットを取得
snap = await session.call_tool("browser_snapshot", {})
result_text = " ".join(
getattr(item, "text", "") for item in snap.content
)
return result_text
if __name__ == "__main__":
text = asyncio.run(search_with_mcp("Python latest release"))
print(f"Result:\n{text}")
desktop
desktop のパブリックテンプレートは Ubuntu 22.04 を実行します。 e2b_desktop SDK を使用して、インスタンス内の UI 操作を自動化できます。
pip install e2b_desktop
import os
import time
from e2b_desktop import Sandbox
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
create_kwargs = {
"timeout": 3600,
"resolution": (1920, 1080),
"dpi": 96,
"template": "desktop",
}
desktop = Sandbox.create(
**create_kwargs,
headers={"X-Sandbox-Create-Timeout": "100"},
)
print(f"Waiting for sandbox {desktop.sandbox_id} to be ready...")
for _ in range(30):
try:
if desktop.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
# UI 操作
print("Moving mouse to (100, 100)...")
desktop.move_mouse(100, 100)
time.sleep(0.5)
print("Left clicking...")
desktop.left_click()
time.sleep(0.5)
print("Typing 'Hello'...")
desktop.write("Hello")
time.sleep(0.5)
print("Pressing Enter...")
desktop.press("enter")
time.sleep(0.5)
print("Opening browser to example.com...")
desktop.open("https://example.com")
time.sleep(2)
# スクリーンショットを取得してダウンロード
print("Taking screenshot...")
screenshot = desktop.screenshot("bytes")
if screenshot:
screenshot_path = "/tmp/desktop_screenshot.png"
with open(screenshot_path, "wb") as f:
f.write(screenshot)
print(f"Screenshot saved to {screenshot_path}")
else:
print("Screenshot returned empty")
インスタンス詳細ページで、[Open VNC] をクリックして、インスタンスの GUI にリモート接続します。
claude-code
claude-code のパブリックテンプレートには Claude CLI が含まれています。このテンプレートからインスタンスを作成し、ANTHROPIC の環境変数を設定することで、分離された環境でコーディングタスク向けに Claude を実行できます。
import os
import time
from e2b import Sandbox
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
sandbox = Sandbox.create(
template="claude-code",
timeout=300000,
envs={
"ANTHROPIC_AUTH_TOKEN": "<YOUR-TOKEN>",
"ANTHROPIC_BASE_URL": "<YOUR-BASE-URL>",
"ANTHROPIC_MODEL": "<YOUR-MODEL>",
},
)
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
result = sandbox.commands.run(
'claude -p "Write a Python program to calculate Fibonacci numbers"',
)
print(result.stdout)
opencode
opencode のパブリックテンプレートには opencode が同梱されており、4096 番ポートで opencode サーバーを起動します。
opencode 設定ファイル /root/.config/opencode/opencode.json には、Alibaba Cloud Bailian Token Plan、Coding Plan、および従量課金モード用のプリセットモデル設定が含まれています。インスタンスを作成する際、BAILIAN-TOKEN-PLAN-KEY、BAILIAN-CODING-PLAN-KEY、または BAILIAN-API-KEY 環境変数を介してキーを指定します。その後、E2B SDK または HTTP リクエストを使用して、インスタンス内でコーディングタスク用に opencode を実行できます。
import os
import time
import requests
from e2b import Sandbox
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
OPENCODE_SERVER_PORT = 4096
sandbox = Sandbox.create(
template="opencode",
timeout=300000,
envs={"BAILIAN-API-KEY": os.getenv("BAILIAN-API-KEY")},
)
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
# e2b SDK 経由で opencode CLI を呼び出す
result = sandbox.commands.run(
'opencode run --model=bailian-payg/qwen3.7-max "Write a Python program to calculate Fibonacci numbers"',
timeout=120,
)
print(result.stdout)
# opencode サーバー API 経由で呼び出す
BASE_URL = f"https://{sandbox.get_host(4096)}"
H = {"X-Access-Token": getattr(sandbox, '_SandboxBase__envd_access_token', None)}
# API キーを設定 (opencode サーバーは {env:...} テンプレートを自動的に解析しません)
api_key = sandbox.commands.run("printenv BAILIAN-API-KEY").stdout.strip()
requests.patch(f"{BASE_URL}/global/config", headers=H, json={
"provider": {"bailian-payg": {"options": {
"apiKey": api_key,
"baseURL": "https://dashscope.aliyuncs.com/apps/anthropic/v1",
}}}
})
# セッションを作成 (モデルを指定)
session = requests.post(f"{BASE_URL}/session", headers=H, json={
"model": {"id": "qwen3.7-max", "providerID": "bailian-payg"},
}).json()
session_id = session["id"]
print(f"Session: {session_id}")
# コーディングタスクを送信 (完全な応答を同期的に待機)
resp = requests.post(f"{BASE_URL}/session/{session_id}/message", headers=H, json={
"parts": [{"type": "text", "text": "Write a Fibonacci program in Python, save it to /workspace/fibonacci.py and run it to verify"}]
}, timeout=300).json()
# アシスタントの応答を出力
for part in resp.get("parts", []):
if part["type"] == "text":
print(part["text"])
elif part["type"] == "tool":
print(f" [tool: {part.get('name')}]")
# 生成されたファイルを検証
print("\n--- fibonacci.py ---")
print(sandbox.commands.run("cat /workspace/fibonacci.py").stdout)
print("--- run ---")
print(sandbox.commands.run("python3 /workspace/fibonacci.py", timeout=30).stdout)
openclaw
openclaw パブリックテンプレートには、openclaw サービスが含まれています。インスタンス内の openclaw サービスのアクセス URL を取得するには、次のコードを使用します。
from e2b import Sandbox
import os
import time, httpx
from urllib.parse import urlparse, parse_qs
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
OPENCLAW_GATEWAY_PORT = 18789
def get_gateway_token(sandbox_id, api_key, domain):
"""API 経由でゲートウェイ認証トークンを取得します"""
url = f"https://api.{domain}/sandboxes/{sandbox_id}"
headers = {
"X-API-KEY": api_key,
"X-Generate-Dashboard-Url": "true",
}
resp = httpx.get(url, headers=headers, timeout=10)
if resp.status_code != 200:
return None
data = resp.json()
dashboard_url = None
if "metadata" in data and isinstance(data["metadata"], dict):
meta = data["metadata"]
dashboard_url = meta.get("sandbox.alicloud.com/dashboard-url") or meta.get("dashboard_url")
if not dashboard_url:
dashboard_url = data.get("dashboard_url")
if dashboard_url:
parsed = urlparse(dashboard_url)
qs = parse_qs(parsed.query)
return qs.get("token", [None])[0]
return None
sandbox = Sandbox.create(
template="openclaw",
timeout=300000,
)
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
gateway_token = get_gateway_token(
sandbox.sandbox_id, os.environ["E2B_API_KEY"], os.environ["E2B_DOMAIN"]
)
url = f"https://{sandbox.get_host(OPENCLAW_GATEWAY_PORT)}?token={gateway_token}"
print(f" Sandbox Access URL: {url}")
qwenpaw
qwenpaw のパブリックテンプレートには qwenpaw サービスが含まれており、自動的に起動します。次のコードを使用して、インスタンス内の qwenpaw サービスのアクセス URL を取得します。
import os
import time
from urllib.parse import urlparse, parse_qs
import httpx
from e2b import Sandbox
os.environ["E2B_DOMAIN"] = "<YOUR-DOMAIN>"
os.environ["E2B_API_KEY"] = "<YOUR-API-KEY>"
QWENPAW_PORT = 8088
def get_gateway_token(sandbox_id, api_key, domain):
"""API 経由でゲートウェイ認証トークンを取得します"""
url = f"https://api.{domain}/sandboxes/{sandbox_id}"
headers = {
"X-API-KEY": api_key,
"X-Generate-Dashboard-Url": "true",
}
resp = httpx.get(url, headers=headers, timeout=10)
if resp.status_code != 200:
return None
data = resp.json()
dashboard_url = None
if "metadata" in data and isinstance(data["metadata"], dict):
meta = data["metadata"]
dashboard_url = meta.get("sandbox.alicloud.com/dashboard-url") or meta.get("dashboard_url")
if not dashboard_url:
dashboard_url = data.get("dashboard_url")
if dashboard_url:
parsed = urlparse(dashboard_url)
qs = parse_qs(parsed.query)
return qs.get("token", [None])[0]
return None
sandbox = Sandbox.create(
template="qwenpaw",
timeout=300000,
)
# サンドボックスの準備が完了するまで待機します
print(f"Waiting for sandbox {sandbox.sandbox_id} to be ready...")
for _ in range(30):
try:
if sandbox.is_running():
print("Sandbox is ready.")
break
except Exception:
pass
time.sleep(2)
gateway_token = get_gateway_token(
sandbox.sandbox_id, os.environ["E2B_API_KEY"], os.environ["E2B_DOMAIN"]
)
url = f"https://{sandbox.get_host(QWENPAW_PORT)}?token={gateway_token}"
print(f"Sandbox Access URL: {url}")