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.
This lesson extends the Chinook Sales Assistant from 5.3 with two features:
This is an advanced, optional lesson, and you should feel free to bypass it. You can build very sophisticated Deep Agents without incorporating sandboxes or async subagents.
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.
This lesson moves the agent's file system into a sandbox. The slideshow below describes why:
You implement this with a few changes to the agent setup:
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.
# python/m5/sales_assistant_sandbox/agent.py
# ... MAIL_SERVER and _enable_search are omitted here; see the full file
# in the repo. _sandbox_backend_for_thread is walked through below.
@contextlib.asynccontextmanager
async def make_graph(config: RunnableConfig, runtime: ServerRuntime):
if runtime.execution_runtime:
thread_id = config.get("configurable", {}).get("thread_id")
backend = await _sandbox_backend_for_thread(thread_id)
else:
backend = StateBackend()
...
yield create_deep_agent(
...,
backend=backend,
...
)
This is the documented context manager factory pattern:
make_graph is a graph factory because the mail MCP tools and the sandbox information are not available until runtime.@contextlib.asynccontextmanager, yield instead of return) rather than a plain async def, following the documented pattern for factories that set up resources. This leaves a place after yield for teardown, if it's ever needed.runtime.execution_runtime to skip the sandbox lookup during introspection callslanggraph dev and Studio also call make_graph just to read the graph's schema or render its diagram, with no real thread running; runtime.execution_runtime is falsy during these calls. (schema/graph reads).A sandbox lives outside the graph, so make_graph has to find each thread's sandbox, start or create it as needed, and seed new ones with the agent's skills and memory files. _sandbox_backend_for_thread handles this:
# python/m5/sales_assistant_sandbox/agent.py
async def _sandbox_backend_for_thread(thread_id: str) -> LangSmithSandbox:
"""Look up (or create) this thread's sandbox and seed it if it's new."""
sandbox, freshly_created = await asyncio.to_thread(_lookup_or_create, f"thread-{thread_id}")
backend = LangSmithSandbox(sandbox)
if freshly_created:
await asyncio.to_thread(_seed_skills_and_memory, backend)
return backend
Three steps:
_lookup_or_create(f"thread-{thread_id}") to find this thread's sandbox by name. It runs in a background thread because it makes blocking sandbox-API calls. What happens next depends on the sandbox's status:ready: reuse it.stopped: restart it.provisioning: wait for it to become ready.LangSmithSandbox backend instance.freshly_created), seeds it once with /skills and /AGENTS.md from local disk via _seed_skills_and_memory, so a new thread's sandbox starts with the same playbooks the agent expects. An existing, reused sandbox skips this step, since it was already seeded when first created.Returns the ready-to-use backend, which make_graph then passes straight into create_deep_agent.
With this change, results such as plots and reports are saved to the file system on the sandbox instead of local disk. agent-chat-ui has been modified to add a file-download capability, so you can pull those files out of the sandbox to your local drive. The UI is hosted locally, and start.sh launches it alongside the mock mail server.
As you learned in the previous lesson, async subagents let a subagent work in the background while the main agent continues. This lesson turns the task of newsletter generation over to an asynchronous subagent.
When you request the newsletter:
start_async_task(subagent_type="newsletter-agent", description=...) once and returns control immediately, without waiting for the result.stream.client.runs.get()) to find its status.check_async_task(task_id) to find the subagent's status. If it has completed, it will retrieve the finished HTML and write the results to /outputs/ for you to download.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 subagent is a separate graph, registered in the same deployment, as set up in langgraph.json:
{
"dependencies": ["../.."],
"graphs": {
"agent": "./agent.py:make_graph",
"newsletter-agent": "./newsletter_agent_graph.py:graph"
},
"env": "../../.env"
}
The async subagent itself is a standard deep agent:
# python/m5/sales_assistant_sandbox/newsletter_agent_graph.py
_genre_researcher = {
"name": "genre-researcher",
"description": "Research one music genre ...",
"system_prompt": GENRE_PROMPT,
"tools": _genre_researcher_tools,
"model": model,
}
graph = create_deep_agent(
model=strong_model,
tools=[markdown_to_html],
system_prompt=NEWSLETTER_AGENT_PROMPT,
subagents=[_genre_researcher],
backend=_backend,
name="newsletter-agent",
)
Accommodating an async subagent took just a few changes to the main agent: the weekly-newsletter skill gained instructions for when to launch and when to check, and the agent's own middleware list gained AsyncSubAgentMiddleware, which gives the main agent the five async tools the prior lesson described: start_async_task, check_async_task, update_async_task, cancel_async_task, and list_async_tasks.
The relevant lines from skills/weekly-newsletter/SKILL.md:
## 2. Launch in the background
- Call `start_async_task(subagent_type="newsletter-agent", description=...)`
**once**, with the genre list in `description`. It returns a task ID
immediately; it does not block.
- Tell Jane the newsletter is being put together in the background, then
**stop**. Do not poll; check on it the next time she asks.
## 3. When asked whether it's ready
- Get the task_id: call `list_async_tasks()`.
- Call `check_async_task(task_id)`.
- If `status` isn't terminal yet, report progress to Jane and stop.
- If `status` is `success`, `result` is the finished HTML. Write it to
`/outputs/` and tell Jane where it landed.
The assistant uses the shared python/.env from the course setup. Add TAVILY_API_KEY to enable newsletter web research, if you have not already done so. Close the langgraph dev from the previous lesson first.
The chat UI for this lesson is a Next.js app, so you also need Node.js 20 or later and pnpm. To install pnpm:
npm install -g pnpm
start.sh stops with a message if either is missing.
cd python/m5/sales_assistant_sandbox
./start.sh
start.sh launches the mock mail server, then the chat UI, then langgraph dev with a larger worker pool (--n-jobs-per-worker 10). The background newsletter run needs its own slot alongside the main thread's. On exit (Ctrl-C or otherwise), it stops the mail server and UI, and stops any sandboxes it created.
This lesson's sandbox-files panel and async-task status badge are custom additions to agent-chat-ui, not available in the hosted version from 5.3, so use the self-hosted fork start.sh launches automatically, at http://localhost:3000.
The first launch installs the UI's dependencies, which can take a minute or two. Wait until the terminal shows Ready before opening http://localhost:3000.
Try the two task sequences this lesson touches:
How's my book of business looking? Give me a territory report. The chart is now agent-written matplotlib code, executed inside the sandbox; there's no dedicated chart tool anymore. Report and chart are saved under /outputs/ in the sandbox; use the download button in the chat to pull them to your machine.Write this week's "This Week in Music" newsletter. (requires TAVILY_API_KEY) This launches in the background and returns control immediately. You can work on other questions while the async subagent works on the report in the background. Watch the status badge; it tells you when research is done and it's time to ask again.The mock inbox and chinook.db reset the same way as in 5.3: re-seed the inbox, and restore data/chinook.db from git if you approved an add_customer. The sandbox adds one more thing: skills and AGENTS.md are seeded into a thread's sandbox once, when that thread is first created, so editing a skill file only takes effect in a new conversation, not an existing one. If start.sh doesn't shut down cleanly and sandboxes are left running, stop those manually too:
cd python/m5/sales_assistant_sandbox
uv run python mcp/send_to_inbox.py --reset
uv run python stop_sandboxes.py
download() path.make_graph is a graph factory because the mail MCP tools and the sandbox only exist at runtime. It skips the sandbox lookup during introspection calls.AGENTS.md. Skill edits only show up in new conversations.langgraph.json. The main agent launches it with start_async_task, keeps working, and checks on it later with check_async_task.weekly-newsletter skill tells the agent when to launch the task, when to check it, and to skip polling.AsyncSubAgentMiddleware gives the main agent the five async tools.Try sandbox operations beyond plotting.
CodeInterpreterMiddleware(ptc=["execute", "write_file"]) is already enabled in this lesson's agent.py, so write_file and execute are callable from inside the interpreter's eval tool, not just as a top-level tool call. Ask exactly: "Run a workflow that writes a customer directory: one file per customer under /outputs/customers/, with their contact info and lifetime spend." The word "workflow" is what tells the agent to orchestrate through the interpreter instead of one subagent call at a time. Watch it dispatch chinook-analyst once via the interpreter's built-in task() global to fetch the customer list, then loop over the result inside that same eval call, calling write_file once per customer instead of a separate top-level tool call for each. Open the sandbox-files panel afterward to see all of them land at once.update_async_task to redirect the same task_id rather than starting over. Then ask it to cancel the job outright and confirm check_async_task reports it stopped.The TypeScript version of this lesson was made available on September 10, 2026. Pull the latest changes from the repo root to access it:
git pull
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.
This lesson extends the Chinook Sales Assistant from 5.3 with two features:
This is an advanced, optional lesson, and you should feel free to bypass it. You can build very sophisticated Deep Agents without incorporating sandboxes or async subagents.
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.
This lesson moves the agent's file system into a sandbox. The slideshow below describes why:
You implement this with a few changes to the agent setup:
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.
// typescript/m5/sales_assistant_sandbox/agent.ts
// ... MAIL_SERVER, mailTools, and sandboxBackendForThread are omitted here;
// see the full file in the repo. sandboxBackendForThread is walked through below.
export async function graph(config: LangGraphRunnableConfig) {
const threadId = config.configurable?.thread_id as string | undefined;
const backend: AnyBackendProtocol = threadId
? await sandboxBackendForThread(threadId)
: new StateBackend();
const tools = await mailTools();
return createDeepAgent({
// ...
backend,
// ...
});
}
This is the documented graph factory pattern:
graph is a graph factory because the mail MCP tools and the sandbox information are not available until runtime.langgraph.json points at the function itself ("agent": "./agent.ts:graph"), and the server awaits it on every request that needs the graph.graph checks config.configurable?.thread_id to skip the sandbox lookup during introspection callslanggraphjs dev and Studio also call the factory just to read the graph's schema or render its diagram, with no real thread running; config.configurable.thread_id is undefined during these calls. (schema/graph reads).A sandbox lives outside the graph, so graph has to find each thread's sandbox, start or create it as needed, and seed new ones with the agent's skills and memory files. sandboxBackendForThread handles this:
// typescript/m5/sales_assistant_sandbox/agent.ts
async function sandboxBackendForThread(threadId: string): Promise<LangSmithSandbox> {
const client = new SandboxClient();
const { sandbox, freshlyCreated } = await lookupOrCreateSandbox(client, `thread-${threadId}`);
const backend = new LangSmithSandbox({ sandbox });
if (freshlyCreated) {
await seedSkillsAndMemory(backend);
}
return backend;
}
Three steps:
lookupOrCreateSandbox(thread-${threadId}) to find this thread's sandbox by name. What happens next depends on the sandbox's status:ready: reuse it.stopped: restart it.provisioning: wait for it to become ready.LangSmithSandbox backend instance.freshlyCreated), seeds it once with /skills and /AGENTS.md from local disk via seedSkillsAndMemory, so a new thread's sandbox starts with the same playbooks the agent expects. An existing, reused sandbox skips this step, since it was already seeded when first created.Returns the ready-to-use backend, which graph then passes straight into createDeepAgent.
With this change, results such as plots and reports are saved to the file system on the sandbox instead of local disk. agent-chat-ui has been modified to add a file-download capability, so you can pull those files out of the sandbox to your local drive. The UI is hosted locally, and start.sh launches it alongside the mock mail server.
As you learned in the previous lesson, async subagents let a subagent work in the background while the main agent continues. This lesson turns the task of newsletter generation over to an asynchronous subagent.
When you request the newsletter:
start_async_task({ agentName: "newsletter-agent", description: ... }) once and returns control immediately, without waiting for the result.check_async_task(taskId) to find the subagent's status. If it has completed, it will retrieve the finished HTML and write the results to /outputs/ for you to download.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 subagent is a separate graph, registered in the same deployment, as set up in langgraph.json:
{
"dependencies": ["../.."],
"graphs": {
"agent": "./agent.ts:graph",
"newsletter-agent": "./newsletter-agent.ts:graph"
},
"env": "../../.env"
}
The async subagent itself is a standard deep agent:
// typescript/m5/sales_assistant_sandbox/newsletter-agent.ts
const genreResearcher: SubAgent = {
name: "genre-researcher",
description: "Research one music genre ...",
systemPrompt: GENRE_PROMPT,
tools: genreResearcherTools,
model,
};
export const graph = createDeepAgent({
model: strongModel,
tools: [markdownToHtml],
systemPrompt: NEWSLETTER_AGENT_PROMPT,
subagents: [genreResearcher],
backend,
name: "newsletter-agent",
});
Accommodating an async subagent took just a few changes to the main agent: the weekly-newsletter skill gained instructions for when to launch and when to check, and the agent's own middleware list gained createAsyncSubAgentMiddleware, which gives the main agent the five async tools the prior lesson described: start_async_task, check_async_task, update_async_task, cancel_async_task, and list_async_tasks.
The relevant lines from skills/weekly-newsletter/SKILL.md:
## 2. Launch in the background
- Call `start_async_task` **once**, with `agentName: "newsletter-agent"` and the
genre list in `description`. It returns a task ID immediately; it does not
block.
- Tell Jane the newsletter is being put together in the background, then
**stop**. Do not poll — check on it the next time she asks.
## 3. When asked whether it's ready
- Get the taskId: call `list_async_tasks()`.
- Call `check_async_task` with that `taskId`.
- If `status` isn't terminal yet, report progress to Jane and stop.
- If `status` is `success`, `result` is the finished HTML, verbatim — no
markdown conversion needed here, newsletter-agent already did that.
The assistant uses the shared typescript/.env from the course setup. Add TAVILY_API_KEY to enable newsletter web research, if you have not already done so. Close the langgraphjs dev from the previous lesson first.
cd typescript/m5/sales_assistant_sandbox
./start.sh
start.sh launches the mock mail server, then the chat UI, then pnpm exec langgraphjs dev. The background newsletter run needs its own slot alongside the main thread's. On exit (Ctrl-C or otherwise), it stops the mail server and UI, and stops any sandboxes it created.
This lesson's sandbox-files panel is a custom addition to agent-chat-ui, not available in the hosted version from 5.3, so use the self-hosted fork start.sh launches automatically, at http://localhost:3000.
The first launch installs the UI's dependencies, which can take a minute or two. Wait until the terminal shows Ready before opening http://localhost:3000.
Try the two task sequences this lesson touches:
How's my book of business looking? Give me a territory report. The chart is now agent-written matplotlib code, executed inside the sandbox; there's no dedicated chart tool anymore. Report and chart are saved under /outputs/ in the sandbox; use the download button in the chat to pull them to your machine.Write this week's "This Week in Music" newsletter. (requires TAVILY_API_KEY) This launches in the background and returns control immediately. You can work on other questions while the async subagent works on the report in the background. Ask again a little later; the agent checks on it and saves the finished newsletter when research is done.The mock inbox and chinook.db reset the same way as in 5.3: re-seed the inbox, and restore data/chinook.db from git if you approved an add_customer. The sandbox adds one more thing: skills and AGENTS.md are seeded into a thread's sandbox once, when that thread is first created, so editing a skill file only takes effect in a new conversation, not an existing one. If start.sh doesn't shut down cleanly and sandboxes are left running, stop those manually too:
cd typescript/m5/sales_assistant_sandbox
pnpm tsx ./mcp/send_to_inbox.ts --reset
pnpm tsx ./stop-sandboxes.ts
download() path.graph is a graph factory because the mail MCP tools and the sandbox only exist at runtime. It skips the sandbox lookup during introspection calls.AGENTS.md. Skill edits only show up in new conversations.langgraph.json. The main agent launches it with start_async_task, keeps working, and checks on it later with check_async_task.weekly-newsletter skill tells the agent when to launch the task, when to check it, and to skip polling.createAsyncSubAgentMiddleware gives the main agent the five async tools.Try sandbox operations beyond plotting.
createCodeInterpreterMiddleware({ ptc: ["execute", "write_file"] }) is already enabled in this lesson's agent.ts, so write_file and execute are callable from inside the interpreter's eval tool, not just as a top-level tool call. Ask exactly: "Run a workflow that writes a customer directory: one file per customer under /outputs/customers/, with their contact info and lifetime spend." The word "workflow" is what tells the agent to orchestrate through the interpreter instead of one subagent call at a time. Watch it dispatch chinook-analyst once via the interpreter's built-in task() global to fetch the customer list, then loop over the result inside that same eval call, calling write_file once per customer instead of a separate top-level tool call for each. Open the sandbox-files panel afterward to see all of them land at once.update_async_task to redirect the same taskId rather than starting over. Then ask it to cancel the job outright and confirm check_async_task reports it stopped.