For translation, open lesson in new tab and use Chrome translate
The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.
The filesystem backends from the last lesson give the agent file tools: ls, read_file, write_file, edit_file, glob, grep. LocalShellBackend and sandbox backends add one more: execute, which runs shell commands.
execute toolShell-capable backends expose an execute(command) tool. The agent calls it to run scripts it has written, invoke CLI tools, and compile and test code. The combined command output, exit code, and execution metadata come back as a tool result on the next LLM call.
Two shell-capable backends are available: LocalShellBackend and sandbox backends. The deciding factor is isolation.
Use a sandbox. Agent generated code and packages the agent may load are untrusted by nature. Use a sandbox to isolate that code from your infrastructure.
Use LocalShellBackend when building a local tool where the agent working directly on your machine is the point, such as a coding assistant or desktop agent. It is not appropriate for production or untrusted input.
A sandbox is a temporary, isolated workspace containing a filesystem, command execution environment, and other resources. Sandbox backends run commands inside that workspace instead of on your host machine.
There are two models for using a sandbox with an agent:
Agent in Sandbox: The agent itself runs inside the sandbox. The LLM API key(s) live inside the sandbox. To update the agent, you must rebuild the sandbox image. This is useful when you want the execution environment to mirror your production infrastructure.
Sandbox as a Tool: The agent runs outside and calls the sandbox via execute and filesystem tools. The LLM API keys stay on your host, agent code is easy to update, and sandbox failures don't affect agent state. This is the model used in this course.
Sandbox-as-a-tool keeps the LLM API key on the host, away from the untrusted code running in the sandbox. But an agent often needs other keys too, to reach services on the user's behalf. LangSmith Sandboxes can attach those keys to outgoing requests without exposing them to the code the agent runs. The slideshow below shows how:
The auth proxy pattern above is specific to LangSmith Sandboxes. The proxy sidecar holds the secrets inside the sandbox, but the code the agent writes and runs never sees them, so the code cannot exfiltrate them.
Here's an example of a LangSmith sandbox being configured as a backend:
# python/m2/m2.3_sandbox_agent.py
from uuid import uuid4
from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient
client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name} (id: {ls_sandbox.id})")
backend = LangSmithSandbox(sandbox=ls_sandbox)
agent = create_deep_agent(
model=model,
backend=backend,
)
try:
result = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
print(result["messages"][-1].text)
finally:
client.delete_sandbox(ls_sandbox.name)
// typescript/m2/m2.3_sandbox_agent.ts
import { randomUUID } from "node:crypto";
import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";
const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name} (id: ${ls_sandbox.id})`);
const backend = new LangSmithSandbox({ sandbox: ls_sandbox });
const agent = createDeepAgent({
model,
backend,
});
try {
const result = await agent.invoke({ messages: [{ role: "user", content: "..." }] });
console.log(result.messages.at(-1)?.text);
} finally {
await client.deleteSandbox(ls_sandbox.name);
}
The try/finally block ensures the sandbox is deleted even if the agent raises. Sandboxes are billed resources; always clean them up.
create_sandbox(...) provisions a fresh sandbox workspace. Files persist within that sandbox until it is deleted; a newly created sandbox starts empty unless you upload files first.
createSandbox(...) provisions a fresh sandbox workspace. Files persist within that sandbox until it is deleted; a newly created sandbox starts empty unless you upload files first.
LocalShellBackend runs commands directly on the host machine. It can scope filesystem tools to a root_dir, but execute itself runs with host permissions; no process isolation is applied.
virtual_mode=True is the default: filesystem tools (ls, read_file, write_file, etc.) are path-scoped under root_dir, and paths resolving outside it are rejected. Pass virtual_mode=False to allow absolute host paths instead. Either way, root_dir does not restrict the execute tool. Shell commands run with host permissions and can access paths outside the filesystem-tool root. That's why LocalShellBackend is unsuitable for production or untrusted input.
LocalShellBackend runs commands directly on the host machine. It can scope filesystem tools to a rootDir, but execute itself runs with host permissions; no process isolation is applied.
In TypeScript, virtualMode defaults to false (unlike Python), so pass virtualMode: true explicitly: filesystem tools (ls, read_file, write_file, etc.) are then path-scoped under rootDir, and paths resolving outside it are rejected. With the default virtualMode: false, absolute host paths are allowed. Either way, rootDir does not restrict the execute tool. Shell commands run with host permissions and can access paths outside the filesystem-tool root. That's why LocalShellBackend is unsuitable for production or untrusted input.
This backend grants agents direct filesystem read/write access and unrestricted shell execution on your host. Use with extreme caution and only in appropriate environments.
Appropriate use cases:
Inappropriate use cases:
Security risks:
.env files)Recommended safeguards:
Note: virtual_mode=TruevirtualMode: true provides no security with shell access enabled, since commands can access any path on the system.
execute is added by shell-capable backends on top of the standard filesystem surfaceexecute is available when the backend supports shell executionComplete the Labs and Quiz above, then continue to the next lesson on the interpreter and how the agent writes and executes code directly in the main loop.
Documentation:
Go deeper: read the source (optional)
The lesson shows how to use this. To see how it's implemented, start with these files:
backends/sandbox.py: BaseSandbox, which builds every file operation on top of execute()backends/local_shell.py: LocalShellBackendbackends/langsmith.py: LangSmithSandboxDocumentation:
Go deeper: read the source (optional)
The lesson shows how to use this. To see how it's implemented, start with these files:
backends/sandbox.ts: BaseSandbox, which builds every file operation on top of execute()backends/local-shell.ts: LocalShellBackendbackends/langsmith.ts: LangSmithSandboxBlog:
The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.
Inspect your own run in LangSmith. Notice the write → execute sequence running as isolated tool calls inside the LangSmith sandbox.
Build an agent that writes a Python script to a sandbox, executes it, and reports the output. You will see the write → execute sequence in LangSmith as a chain of tool calls.
This lab uses LangSmithSandbox; commands run in an isolated LangSmith-managed environment, not on your local machine.
Note: Sandboxes are available on every LangSmith plan, including the free Developer tier, which comes with a monthly sandbox allowance. You can cap what you spend under Settings → Billing and Usage → Usage limits.
Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the Python environment.
# python/m2/m2.3_sandbox_agent.py
from uuid import uuid4
from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient
from models import model
client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name} (id: {ls_sandbox.id})")
backend = LangSmithSandbox(sandbox=ls_sandbox)
agent = create_deep_agent(
model=model,
backend=backend,
system_prompt=(
"You are a coding assistant. When asked to run code, write the script "
"to a file first, then execute it. Show the output in your final answer."
),
)
try:
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": (
"Write a Python script that prints the first 15 Fibonacci numbers, "
"save it to fib.py, and run it."
),
}
]
}
)
print(result["messages"][-1].text)
finally:
client.delete_sandbox(ls_sandbox.name)
From the repo root:
cd python
uv run ./m2/m2.3_sandbox_agent.py
Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the TypeScript environment.
// typescript/m2/m2.3_sandbox_agent.ts
import { randomUUID } from "node:crypto";
import { context } from "langchain";
import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";
import { model } from "../models.js";
const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name} (id: ${ls_sandbox.id})`);
const backend = new LangSmithSandbox({ sandbox: ls_sandbox });
const agent = createDeepAgent({
model,
backend,
systemPrompt: context`
You are a coding assistant. When asked to run code, write the script
to a file first, then execute it. Show the output in your final answer.`,
});
try {
const result = await agent.invoke({
messages: [
{
role: "user",
content: context`
Write a Python script that prints the first 15 Fibonacci numbers,
save it to fib.py, and run it.`,
},
],
});
console.log(result.messages.at(-1)?.text);
} finally {
await client.deleteSandbox(ls_sandbox.name);
}
From the repo root:
cd typescript
pnpm tsx ./m2/m2.3_sandbox_agent.ts
What to check:
Open LangSmith and look at the tool call sequence:
write_file: agent writes fib.py into the sandboxexecute: agent runs python fib.py inside the sandboxIf the script had an error, you will see the agent call edit_file to fix it and execute again. Shell execution enables this self-correction loop; the sandbox makes it safer to run.
Try a different task:
"Write a Python script that counts word frequencies in a short paragraph of your choice, save it to wordcount.py, and run it.""Write a Python script that generates a multiplication table for numbers 1 to 5, save it to times_table.py, and run it."The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.
Inspect your own run in LangSmith. Notice the file upload to the sandbox, the query and chart-generation steps, and the file read back at the end.
Build an agent that queries the Chinook music store database inside a sandbox and generates a chart. The agent installs its own dependencies, writes and runs Python, and you retrieve the output file from the sandbox.
This lab introduces two new patterns: uploading files to a sandbox before the agent runs, and reading files back from the sandbox after it finishes.
Note: Sandboxes are available on every LangSmith plan, including the free Developer tier, which comes with a monthly sandbox allowance. You can cap what you spend under Settings → Billing and Usage → Usage limits.
timeout= (set in models.py) won't help; it only bounds the LLM API call, not sandbox operations. Sandbox timing has separate knobs:
client.create_sandbox(..., timeout=30)), then raises a resource-timeout error.execute defaults to a 30-minute overall command timeout.pip install plus chart generation is the most likely to hit the idle timeout. Check the LangSmith trace for the specific error before assuming the model's timeout= is the cause.
Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the Python environment.
# python/m2/m2.3_sales_agent.py
from pathlib import Path
from uuid import uuid4
from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient
from models import model
DB_PATH = Path(__file__).resolve().parent / "chinook.db"
client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name} (id: {ls_sandbox.id})")
backend = LangSmithSandbox(sandbox=ls_sandbox)
with open(DB_PATH, "rb") as f:
upload_results = backend.upload_files([("/chinook.db", f.read())])
for upload_result in upload_results:
if upload_result.error:
raise RuntimeError(f"Failed to upload {upload_result.path}: {upload_result.error}")
agent = create_deep_agent(
model=model,
backend=backend,
system_prompt=(
"You are a sales data analyst with access to the Chinook music store database "
"at /chinook.db. Use sqlite3 and matplotlib to answer questions with charts. "
"This sandbox Python is externally managed, so install packages with "
"`pip install --break-system-packages <package>` (e.g. `pip install "
"--break-system-packages matplotlib`). sqlite3 is stdlib, so do not install it. "
"When asked to produce a chart, write a Python script, execute it, and confirm "
"the output file was created."
),
)
try:
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": (
"Query the Chinook database at /chinook.db to get total revenue "
"by genre. Create a clean donut chart showing each genre's share "
"of total sales revenue. Group any genres that individually "
"account for less than 3% of total revenue into a single 'Other' "
"slice. Label each slice with the genre name and percentage. "
"Use a visually distinct color palette, leave a white center hole, "
"and make sure no labels overlap with each other or with the title. "
"Add enough top padding so the title is fully visible. "
"Save the chart to /genre_revenue.png."
),
}
]
}
)
print(result["messages"][-1].text)
png_bytes = ls_sandbox.read("/genre_revenue.png")
out_path = Path(__file__).parent / "genre_revenue.png"
out_path.write_bytes(png_bytes)
print(f"Chart saved to {out_path}")
finally:
client.delete_sandbox(ls_sandbox.name)
From the repo root:
cd python
uv run ./m2/m2.3_sales_agent.py
open m2/genre_revenue.png
Expected output:
Sandbox: lca-deepagents-lab (id: 510c7cfa-7809-4317-a272-715c05221a24) Done! I've successfully created your donut chart showing revenue by genre. Data Summary: - Total Revenue: $2,328.60 - Rock: 35.5% ($826.65) - Latin: 16.4% ($382.14) - Metal: 11.2% ($261.36) - Alternative & Punk: 10.4% ($241.56) - TV Shows: 4.0% ($93.53) - Jazz: 3.4% ($79.20) - Other (<3%): 19.1% ($444.16) Chart saved to python/m2/genre_revenue.png
The chart is saved locally as genre_revenue.png. Open it with open m2/genre_revenue.png.
Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the TypeScript environment.
// typescript/m2/m2.3_sales_agent.ts
import { randomUUID } from "node:crypto";
import { dirname, join } from "node:path";
import { writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { context } from "langchain";
import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";
import { model } from "../models.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DB_PATH = join(__dirname, "chinook.db");
const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name} (id: ${ls_sandbox.id})`);
const backend = new LangSmithSandbox({ sandbox: ls_sandbox });
// Upload the Chinook database into the sandbox.
const dbBytes = await readFile(DB_PATH);
const uploadResults = await backend.uploadFiles([["/chinook.db", dbBytes]]);
for (const result of uploadResults) {
if (result.error) {
throw new Error(`Failed to upload ${result.path}: ${result.error}`);
}
}
const agent = createDeepAgent({
model,
backend,
systemPrompt: context`
You are a sales data analyst with access to the Chinook music store database
at /chinook.db. Use sqlite3 and matplotlib to answer questions with charts.
This sandbox Python is externally managed, so install packages with
\`pip install --break-system-packages <package>\` (e.g. \`pip install
--break-system-packages matplotlib\`). sqlite3 is stdlib, so do not install it.
When asked to produce a chart, write a Python script, execute it, and confirm
the output file was created.`,
});
try {
const result = await agent.invoke({
messages: [
{
role: "user",
content: context`
Query the Chinook database at /chinook.db to get total revenue
by genre. Create a clean donut chart showing each genre's share
of total sales revenue. Group any genres that individually
account for less than 3% of total revenue into a single 'Other'
slice. Label each slice with the genre name and percentage.
Use a visually distinct color palette, leave a white center hole,
and make sure no labels overlap with each other or with the title.
Add enough top padding so the title is fully visible.
Save the chart to /genre_revenue.png.`,
},
],
});
console.log(result.messages.at(-1)?.text);
const pngBytes = await ls_sandbox.read("/genre_revenue.png");
const outPath = join(__dirname, "genre_revenue.png");
writeFileSync(outPath, pngBytes);
console.log(`Chart saved to ${outPath}`);
} finally {
await client.deleteSandbox(ls_sandbox.name);
}
From the repo root:
cd typescript
pnpm tsx ./m2/m2.3_sales_agent.ts
open m2/genre_revenue.png
Expected output:
Sandbox: lca-deepagents-lab (id: 510c7cfa-7809-4317-a272-715c05221a24) Done! I've successfully created your donut chart showing revenue by genre. Data Summary: - Total Revenue: $2,328.60 - Rock: 35.5% ($826.65) - Latin: 16.4% ($382.14) - Metal: 11.2% ($261.36) - Alternative & Punk: 10.4% ($241.56) - TV Shows: 4.0% ($93.53) - Jazz: 3.4% ($79.20) - Other (<3%): 19.1% ($444.16) Chart saved to typescript/m2/genre_revenue.png
The chart is saved locally as genre_revenue.png. Open it with open m2/genre_revenue.png.

Lab 1 ran one script in a sandbox. In this homework, you'll send two separate tasks to the same sandbox, one after the other, to prove that its filesystem persists between invoke() calls instead of resetting each time. Lab 2 relies on this too: it uploads a database before the agent runs and reads a chart back after it finishes.
Open python/m2/m2.3_homework.py.
pip install --break-system-packages <package>, as in Lab 2, because this sandbox's Python is externally managed and matplotlib isn't preinstalledCHART_PATH at the exact path you told the agent to save the chart to in TASK_TWO, so the script can read the image back from the sandbox, the same way Lab 2 does.cd python
uv run ./m2/m2.3_homework.py
open m2/homework_chart.png
Stuck, or want to see the finished shape before you start? m2.3_homework_filled.py is a reference copy with every TODO filled in (using a made-up monthly rainfall dataset charted as a bar chart, with a data-visualization-assistant persona); run it the same way to see what "done" looks like end to end.
Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.
What you'll build: proof that root_dir/virtual_mode on LocalShellBackend restricts the filesystem tools but never execute, watched safely by gating execute behind your approval instead of letting it run unattended.
LocalShellBackend, which executes directly on your own machine with no isolation. The approval step below is your only safeguard, so only approve a command you would be comfortable running yourself.Requirements:
create_deep_agent(model=model, backend=LocalShellBackend(root_dir=..., virtual_mode=True), interrupt_on={"execute": {"allowed_decisions": ["approve", "reject"]}}, checkpointer=MemorySaver()) call from scratch, in a new file under python/m2/. Point root_dir at a fresh scratch directory you create just for this exercise, e.g. Path(__file__).parent / "sandbox_scratch". No file in this module uses LocalShellBackend directly, so check its own docstring for the exact root_dir/virtual_mode semantics rather than looking for a worked example nearby.write_file inside the scratch directory (ungated, confined to root_dir).execute on a harmless, read-only target OUTSIDE root_dir (e.g. pwd, or listing your home directory). When the interrupt fires, read the exact command before approving it, then confirm it succeeds anyway, proving virtual_mode never scoped execute in the first place.execute call once and see the agent respond to your rejection message instead of the command's real output.Lab 1 ran one script in a sandbox. In this homework, you'll send two separate tasks to the same sandbox, one after the other, to prove that its filesystem persists between invoke() calls instead of resetting each time. Lab 2 relies on this too: it uploads a database before the agent runs and reads a chart back after it finishes.
Open typescript/m2/m2.3_homework.ts.
pip install --break-system-packages <package>, as in Lab 2, because this sandbox's Python is externally managed and matplotlib isn't preinstalledCHART_PATH at the exact path you told the agent to save the chart to in TASK_TWO, so the script can read the image back from the sandbox, the same way Lab 2 does.cd typescript
pnpm tsx ./m2/m2.3_homework.ts
open m2/homework_chart.png
Stuck, or want to see the finished shape before you start? m2.3_homework_filled.ts is a reference copy with every TODO filled in (using a made-up monthly rainfall dataset charted as a bar chart, with a data-visualization-assistant persona); run it the same way to see what "done" looks like end to end.
Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.
What you'll build: proof that rootDir/virtualMode on LocalShellBackend restricts the filesystem tools but never execute, watched safely by gating execute behind your approval instead of letting it run unattended.
LocalShellBackend, which executes directly on your own machine with no isolation. The approval step below is your only safeguard, so only approve a command you would be comfortable running yourself.Requirements:
createDeepAgent({ model, backend: new LocalShellBackend({ rootDir: ..., virtualMode: true }), interruptOn: { execute: { allowedDecisions: ["approve", "reject"] } }, checkpointer: new MemorySaver() }) call from scratch, in a new file under typescript/m2/. Point rootDir at a fresh scratch directory you create just for this exercise. No file in this module uses LocalShellBackend directly, so check its own docstring for the exact rootDir/virtualMode semantics rather than looking for a worked example nearby.write_file inside the scratch directory (ungated, confined to rootDir).execute on a harmless, read-only target OUTSIDE rootDir (e.g. pwd, or listing your home directory). When the interrupt fires, read the exact command before approving it, then confirm it succeeds anyway, proving virtualMode never scoped execute in the first place.execute call once and see the agent respond to your rejection message instead of the command's real output.