Chapter 04 · Sandbox execution and the shell tool
When an agent installs dependencies, runs tests, or invokes CLIs, it needs shell execution. Sandbox backends provide the execute tool, containing system side effects in an isolated environment.
Mechanics and design choices
deepagents.backends.LocalShellBackend is a local shell backend: it confines the execute tool to root_dir and controls blast radius via timeout and max_output_bytes. Production environments more often use remote sandboxes such as LangSmith, AgentCore, Daytona, or E2B, which need extra credentials and network reachability.
Example
import os
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model=os.environ["MODEL_ID"],
api_key=os.environ["DEEPAGENT_API_KEY"],
base_url=os.environ.get("DEEPAGENT_BASE_URL", "https://api.openai.com/v1"),
)
import shutil, tempfile
from deepagents import create_deep_agent
from deepagents.backends import LocalShellBackend
root = tempfile.mkdtemp(prefix="deepagents-shell-")
try:
agent = create_deep_agent(
model=model,
backend=LocalShellBackend(root_dir=root, virtual_mode=True, timeout=60),
system_prompt="When asked to run a command, use the execute tool.",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "Run: echo hello-from-shell > out.txt and then cat out.txt."}]},
{"configurable": {"thread_id": "ch04"}},
)
print(result["messages"][-1].content)
finally:
shutil.rmtree(root, ignore_errors=True)Run and verify
API key required. Acceptance: the final message contains hello-from-shell and the temp directory is cleaned up without leftovers.
Pitfalls
execute is a system-level side effect; keep the sandbox root/network/credentials boundaries intact. Do not let execute and declarative permissions substitute for each other. LocalShellBackend runs on the host and suits learning or offline tests; use remote sandboxes in production and audit them separately.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. Who provides execute?
2. Is LocalShellBackend suitable for production?
3. What does timeout control?
4. Can execute bypass permissions?
Hands-on exercises
- Run a failing command (exit 1) and observe the tool result.
- Lower timeout to 5 seconds and create a long task.
- Compare credential isolation between local and remote sandboxes.
Official references
Verified on 2026-09-17 with Deep Agents 0.7.15.