For translation, open lesson in new tab and use Chrome translate

The Sales Assistant (Advanced)

Lesson Video Walkthrough

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.


Sandbox security

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:

Lesson Video Walkthrough

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:

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:

  1. Calls _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.
      • The lab's sandboxes stop after 10 idle minutes.
    • Any other status, such as provisioning: wait for it to become ready.
    • No sandbox with that name: create one.
      • This happens on a thread's first run, and again if the sandbox was deleted. The lab deletes stopped sandboxes after an hour.
  2. Wraps that sandbox object in a LangSmithSandbox backend instance.
  3. If the sandbox was just created (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.


Async Subagents

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:

Lab Video Walkthrough

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.

Run it

Before you start

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.

Running

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.

Chat UI

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.

What it can do

Try the two task sequences this lesson touches:

  1. Report on the territory: 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.
  2. Write the weekly newsletter: 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.

Resetting the lab

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

Recap


Next

Try sandbox operations beyond plotting.

  1. Trend over snapshot: have the agent pull monthly revenue for the past year and chart the trajectory, not just a single point-in-time total.
  2. Interpreter calling tools directly: 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.
  3. Interrupt and cancel a background job: ask for the newsletter, then before it finishes, change your mind: "only cover Jazz and Electronic this week." The agent should call 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
Lesson Video Walkthrough (Python)

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.


Sandbox security

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:

Lesson Video Walkthrough (Python)

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:

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:

  1. Calls 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.
      • The lab's sandboxes stop after 10 idle minutes.
    • Any other status, such as provisioning: wait for it to become ready.
    • No sandbox with that name: create one.
      • This happens on a thread's first run, and again if the sandbox was deleted. The lab deletes stopped sandboxes after an hour.
  2. Wraps that sandbox object in a LangSmithSandbox backend instance.
  3. If the sandbox was just created (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.


Async Subagents

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:

Lab Video Walkthrough (Python)

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.

Run it

Before you start

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.

Running

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.

Chat UI

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.

What it can do

Try the two task sequences this lesson touches:

  1. Report on the territory: 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.
  2. Write the weekly newsletter: 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.

Resetting the lab

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

Recap


Next

Try sandbox operations beyond plotting.

  1. Trend over snapshot: have the agent pull monthly revenue for the past year and chart the trajectory, not just a single point-in-time total.
  2. Interpreter calling tools directly: 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.
  3. Interrupt and cancel a background job: ask for the newsletter, then before it finishes, change your mind: "only cover Jazz and Electronic this week." The agent should call 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.