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

Async Subagents

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.

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.

The two invocation paths

Async subagents let a supervisor agent launch background tasks that return immediately, so the supervisor can continue interacting with the user while subagents work concurrently. The supervisor can check progress, send follow-up instructions, or cancel tasks at any point.

An async subagent runs differently from a synchronous one in two ways:

Synchronous subagent
(module 4.1, 4.2)
Async subagent
  • Invoked through the built-in task tool
  • Calls create_agent in the same process
  • Waits for it to finish, and returns the result
  • Invoked through a different set of tools that go over the LangGraph SDK
  • Runs on a remote Agent Protocol server (a managed LangSmith Agent Server deployment or a self-hosted one)
  • The main agent doesn't wait for that run to finish, it gets a task ID back right away
  • Can check on the task whenever it wants
Synchronous subagent
(module 4.1, 4.2)
Async subagent
  • Invoked through the built-in task tool
  • Calls createAgent in the same process
  • Waits for it to finish, and returns the result
  • Invoked through a different set of tools that go over the LangGraph SDK
  • Runs on a remote Agent Protocol server (a managed LangSmith Agent Server deployment or a self-hosted one)
  • The main agent doesn't wait for that run to finish, it gets a task ID back right away
  • Can check on the task whenever it wants

That remote server is the same kind of deployment you set up earlier in this module, when you ran langgraph dev to serve an agent over HTTP. An async subagent target is just another deployed graph, reachable the same way.


Setup

You already have both pieces this needs from 5.2's homework (python/m5/homework/call_agent_api.py):

Below, graph_id is that same key, and url is that same kind of address, just pointing at a different deployment.

You already have both pieces this needs from 5.2's homework (typescript/m5/homework/call_agent_api.ts):

Below, graphId is that same key, and url is that same kind of address, just pointing at a different deployment.

Configuring an async subagent looks like configuring a sync one, but instead of a system prompt and tools, you point at a deployed graph:

import os

from deepagents import AsyncSubAgent, create_deep_agent
from langchain_openai import ChatOpenAI

subagents = [
    AsyncSubAgent(
        name="researcher",
        description="Long-running research agent for deep, multi-source analysis.",
        graph_id="research_agent",
        url="https://my-deployment.langsmith.dev",
    ),
]

model = ChatOpenAI(
    model="nvidia/nemotron-3-ultra-550b-a55b:free",
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)

agent = create_deep_agent(
    model=model,
    subagents=subagents,
)
import { initChatModel } from "langchain";
import { createDeepAgent, type AsyncSubAgent } from "deepagents";

const subagents: AsyncSubAgent[] = [
  {
    name: "researcher",
    description: "Long-running research agent for deep, multi-source analysis.",
    graphId: "research_agent",
    url: "https://my-deployment.langsmith.dev",
  },
];

// Reads OPENROUTER_API_KEY from the environment.
const model = await initChatModel(
  "openrouter:nvidia/nemotron-3-ultra-550b-a55b:free"
);

const agent = createDeepAgent({
  model,
  subagents,
});

The highlighted lines are what actually make this an async setup:

This example is shown with NVIDIA's Nemotron model, an open model.
  • name: what the main agent calls this subagent type when it calls start_async_task.
  • description: how the main agent decides when to delegate to it, same role as a sync subagent's description.
  • graph_id: the graph or assistant ID on the remote server.
  • url: where that server lives. Omit it to connect to a local graph over ASGI transport instead of HTTP; for Agent Server, authentication is handled automatically from your environment (LANGGRAPH_API_KEY, LANGSMITH_API_KEY, or LANGCHAIN_API_KEY).
  • name: what the main agent calls this subagent type when it calls start_async_task.
  • description: how the main agent decides when to delegate to it, same role as a sync subagent's description.
  • graphId: the graph or assistant ID on the remote server.
  • url: where that server lives. Omit it to fall back to the LangGraph SDK's default endpoint; for Agent Server, authentication is handled automatically from your environment (LANGGRAPH_API_KEY, LANGSMITH_API_KEY, or LANGCHAIN_API_KEY). You can also pass headers for custom auth.

You can register more than one async subagent type, each with its own graph_id and optionally its own url. And since AsyncSubAgent entries and plain sync subagent dicts both just go in subagents=, you don't need to keep them in separate lists: create_deep_agent sorts out which is which when it compiles the agent.

You can register more than one async subagent type, each with its own graphId and optionally its own url. And since AsyncSubAgent entries and plain sync subagent config objects both just go in subagents, you don't need to keep them in separate arrays: createDeepAgent sorts out which is which when it compiles the agent.


The five tools

That middleware exposes five tools to the main agent, alongside the single task tool synchronous subagents use, not instead of it:

Tool What it does
start_async_task Launches a background run on the named async subagent. Returns a task_id immediately.
check_async_task Looks up the current status of a task by task_id. If it's finished, the result comes back too.
update_async_task Sends new instructions to a still-running task, on the same thread.
cancel_async_task Stops a running task.
list_async_tasks Reports the live status of every tracked task at once, optionally filtered by status.

start_async_task doesn't block. It creates a thread on the remote server, kicks off a run on it, and hands the model a task_id right away, its own model call continues without waiting on the subagent at all.

One agent can use sync and async subagents together. By default, deepagents adds a general-purpose sync subagent, so the task tool is already there. Add async subagents and the main agent has all six tools: task plus the five above. In a single conversation, it can hand a quick job to an in-process subagent, then send a long job to a remote one.

Step through a typical exchange to see how the pieces connect. Notice that "check" is a separate, later round trip; nothing happens automatically in between.


Tracking a task

Every launched task is tracked as an AsyncTask and persisted in the main agent's state, under an async_tasks key: a task_id (the thread ID), which agent type launched it, its run_id, its status, and when it was created, last checked, and last updated.

Every launched task is tracked as an AsyncTask and persisted in the main agent's state, under an asyncTasks key: a taskId (the thread ID), which agent type launched it (agentName), its runId, its status, and when it was created, last checked, and last updated.

Because of that, it survives context compaction. If the conversation gets long enough that older messages are summarized away, the task record stays put, since it lives in state.


How the main agent is expected to behave

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.

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.

Checking on a task right after launching it defeats the purpose, so the model should report the task ID and move on. In Python, the async tools' own descriptions teach this. The model reads them as part of each tool's schema. AsyncSubAgentMiddleware accepts an optional system_prompt, but it defaults to None as of deepagents 0.7, and create_deep_agent doesn't set one when you pass it async subagents. So this lab relies on the tool descriptions, which ask for:

  • Launch, then stop. After start_async_task, report the task ID and return control. Don't immediately call check_async_task on it.
  • Check only on request, by default. The check_async_task description tells the model to check only when the user asks for a status update. Auto-notifying the supervisor when a subagent finishes is possible, but needs extra middleware on the subagent side that isn't part of this default setup.
  • Never trust a status already in the transcript. A task that shows "running" earlier in the conversation may be done by now. Always call a tool to get the current status rather than repeating a stale one.
  • update_async_task restarts the run. It interrupts the current run and starts a fresh one on the same thread, so the subagent sees the full history plus the new instructions. The task_id doesn't change.

Launching a task and immediately checking on it defeats the point, so the model needs to report the task ID and move on. In TypeScript that discipline is carried by the async tools' own descriptions, which the model reads as part of each tool's schema. createAsyncSubAgentMiddleware takes an optional systemPrompt, but it defaults to null: this lab's main_agent/agent.ts passes nothing and relies on those tool descriptions, which ask for:

  • Launch, then stop. After start_async_task, report the task ID and return control. Don't immediately call check_async_task on it.
  • Check only on request, by default. The check_async_task description tells the model to check only when the user asks for a status update. Auto-notifying the supervisor when a subagent finishes is possible, but needs extra middleware on the subagent side that isn't part of this default setup.
  • Never trust a status already in the transcript. A task that shows "running" earlier in the conversation may be done by now. Always call a tool to get the current status rather than repeating a stale one.
  • update_async_task restarts the run. It interrupts the current run and starts a fresh one on the same thread, so the subagent sees the full history plus the new instructions. The taskId doesn't change.

Sync vs. async, side by side

Synchronous subagent Async subagent
Invoked via built-in task tool start_async_task + friends
Runs where in-process, via create_agent remote server, via the LangGraph SDK
Main agent blocks until it returns continues immediately
Identified by nothing, it's just a tool call task_id (persisted in state)
Good fit for focused work the main agent needs before it can continue long-running or concurrent work the main agent shouldn't wait on

Reach for an async subagent when:

Stick with a synchronous subagent when:

This is a different topic from Dynamic Subagents (module 4):

The Lab tab puts that last point into practice: two real local deployments, one of them carrying a dependency the other doesn't need.

The Lab tab puts that last point into practice: two real local deployments, one of them running a job slow enough that you'd never want it inline.


Recap


Next

Complete the Lab and Quiz above to see this running end to end, with two real local deployments talking to each other. That wraps up the course. To go further, try wiring an async subagent into the Sales Assistant from the previous lesson, or revisit Dynamic Subagents for dispatching subagents programmatically from a loop instead of one call at a time.


References

Documentation:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Blog:

Lab: Two Deployments, One Supervisor

Lab + Studio 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.

Every lab so far has run a single langgraph dev server. This one runs two, because specialized_agent needs pandas and main_agent doesn't:

In this lab:

That isolation comes from specialized_agent/langgraph.json declaring "dependencies": ["."] instead of the ["../.."] every other lab in this course uses to reach the shared environment:

// python/m5/async_lab/specialized_agent/langgraph.json
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./agent.py:graph"
  },
  "env": "../../../.env"
}

Its pyproject.toml lists pandas alongside a minimal set of its own dependencies, separate from the course's shared list:

# python/m5/async_lab/specialized_agent/pyproject.toml
dependencies = [
    "deepagents==0.7.0",
    "langgraph>=1.0.0,<2.0",
    "langchain-anthropic",
    "langchain-openai",
    "langgraph-cli[inmem]>=0.4.0",
    "pandas>=2.2.0",
]

And its agent uses that pandas dependency in a single tool, analyze_sales, which sleeps for 20 seconds (time.sleep(20)) to stand in for a heavyweight job. It takes a group_by argument, "region" or "product", so the main agent can launch more than one independent analysis at once:

# python/m5/async_lab/specialized_agent/agent.py
@tool
def analyze_sales(group_by: str = "region") -> str:
    """Run a full sales breakdown, grouped by "region" or by "product", ranked highest revenue first."""
    time.sleep(20)  # stands in for a genuinely slow job
    grouped = SALES.groupby(group_by)[["units_sold", "revenue"]].sum().sort_values("revenue", ascending=False)
    ...

# langgraph.json points at this variable: "./agent.py:graph"
graph = create_deep_agent(model=model, tools=[analyze_sales])

Using a provider other than Anthropic? This deployment can't import the shared models.py, so it sets its own model in agent.py: model = init_chat_model("anthropic:claude-haiku-4-5"). Change that string to your provider's model. Its pyproject.toml only includes langchain-anthropic and langchain-openai, so for any other provider, run uv add with that provider's package from inside specialized_agent/. API keys still come from the shared .env, through "env": "../../../.env" in its langgraph.json.

main_agent never sees that tool directly. It only knows about an AsyncSubAgent named "analyst", pointed at the second server's address:

Code overview of main_agent/agent.py: an AsyncSubAgent named analyst with a description, graph_id and url pointing at a second langgraph dev server on port 2025, passed to create_deep_agent so the main agent gets async task tools.

# python/m5/async_lab/main_agent/agent.py
subagents = [
    AsyncSubAgent(
        name="analyst",
        description="Runs sales analysis grouped by region or by product, returning total revenue and units sold per group only. Slow, so it lives on its own deployment.",
        graph_id="agent",
        url="http://127.0.0.1:2025",
    ),
]

graph = create_deep_agent(model=model, subagents=subagents)

The description also limits what the main agent asks for. The analyst's only tool returns total revenue and units sold per group. Without the part of the description that says so, the main agent may ask for something analyze_sales never computes, like average transaction value. The analyst can't compute that, but it may answer anyway with a plausible-looking number instead of saying it doesn't have the data. Spelling out what the analyst can return in its description helps prevent this kind of hallucination.

Run it

In the walkthrough video above, time.sleep(20) in analyze_sales was temporarily changed to time.sleep(300) (5 minutes) purely to leave enough time on camera to narrate each step before a task finished on its own. The lab code itself still uses 20; you don't need to change anything to follow along.

Two terminals, two servers. Start the specialized deployment first, on port 2025:

cd python/m5/async_lab/specialized_agent
uv run langgraph dev --port 2025

Then, in a second terminal, start the main agent on the default port, 2024:

cd python/m5/async_lab/main_agent
uv run langgraph dev

The second command opens Studio for main_agent. Chat with it there, working through the tools from the table above:

  1. Ask it to analyze sales by region, and separately by product, at the same time. It should call start_async_task twice and report two task_ids right away, both jobs now running concurrently on the same specialized_agent server, without blocking the main agent on either one.
  2. Keep chatting, ask it something unrelated, ask what time it is, anything, while both analyses run in the background.
  3. Change your mind about the regional one: tell it to narrow that task to just the West region. It should call update_async_task on that task_id. This interrupts the run that's still in time.sleep(20) and starts a new one on the same thread. The subagent sees your new instruction, and the task_id stays the same.
  4. Decide you don't need the product breakdown after all: ask it to cancel that task. It should call cancel_async_task on the product task_id.
  5. Ask for an update on what's left. It should report back the West-region-only breakdown, reflecting the instruction you sent in step 3.

For step 5, it may call list_async_tasks, which reports the status of every tracked task at once instead of one task_id at a time.

If you stop the specialized_agent server partway through, main_agent still reports a task_id immediately and stays responsive, it just can't successfully check the task until that server is back.


Lab: Two Deployments, One Supervisor

The TypeScript version of this lab was made available on September 10, 2026. Pull the latest changes from the repo root to access it:

git pull
Lab + Studio 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.

Every lab so far has run a single langgraphjs dev server. This one runs two, so the slow analysis job lives somewhere other than the main agent's own process:

In this lab:

Its agent does that work in a single tool, analyze_sales, which waits 20 seconds (setTimeout(..., 20_000)) to stand in for a heavyweight job. It takes a groupBy argument, "region" or "product", so the main agent can launch more than one independent analysis at once:

// typescript/m5/async_lab/specialized_agent/agent.ts
const analyzeSales = tool(
  async ({ groupBy }: { groupBy: "region" | "product" }) => {
    // Stands in for a genuinely slow job (a big data pipeline, a model call, etc.).
    await new Promise((resolve) => setTimeout(resolve, 20_000));
    const totals = new Map<string, { unitsSold: number; revenue: number }>();
    // ... sum unitsSold and revenue per group, then rank by revenue
  },
  {
    name: "analyze_sales",
    description:
      'Run a full sales breakdown, grouped by "region" or by "product", ranked highest revenue first.',
    schema: z.object({ groupBy: z.enum(["region", "product"]).default("region") }),
  }
);

// langgraph.json points at this export: "./agent.ts:graph"
export const graph = createDeepAgent({ model, tools: [analyzeSales] });

main_agent never sees that tool directly. It only knows about an AsyncSubAgent named "analyst", pointed at the second server's address:

Code overview of main_agent/agent: an async subagent named analyst with a description, graph id and url pointing at a second dev server on port 2025.

// typescript/m5/async_lab/main_agent/agent.ts
const subagents: AsyncSubAgent[] = [
  {
    name: "analyst",
    description:
      "Runs sales analysis grouped by region or by product, returning total " +
      "revenue and units sold per group only. Slow, so it lives on its own deployment.",
    graphId: "agent",
    url: "http://localhost:2025",
  },
];

export const graph = createDeepAgent({ model, subagents });

The description also limits what the main agent asks for. The analyst's only tool returns total revenue and units sold per group. Without the part of the description that says so, the main agent may ask for something analyze_sales never computes, like average transaction value. The analyst can't compute that, but it may answer anyway with a plausible-looking number instead of saying it doesn't have the data. Spelling out what the analyst can return in its description helps prevent this kind of hallucination.

Run it

In the walkthrough video above, time.sleep(20) in analyze_sales was temporarily changed to time.sleep(300) (5 minutes) purely to leave enough time on camera to narrate each step before a task finished on its own. The TypeScript lab's equivalent 20-second setTimeout is unchanged; you don't need to change anything to follow along.

Two terminals, two servers. Start the specialized deployment first, on port 2025:

cd typescript/m5/async_lab/specialized_agent
pnpm exec langgraphjs dev --port 2025

Then, in a second terminal, start the main agent on the default port, 2024:

cd typescript/m5/async_lab/main_agent
pnpm exec langgraphjs dev

The second command opens Studio for main_agent. Chat with it there, working through the tools from the table above:

  1. Ask it to analyze sales by region, and separately by product, at the same time. It should call start_async_task twice and report two taskIds right away, both jobs now running concurrently on the same specialized_agent server, without blocking the main agent on either one.
  2. Keep chatting, ask it something unrelated, ask what time it is, anything, while both analyses run in the background.
  3. Change your mind about the regional one: tell it to narrow that task to just the West region. It should call update_async_task on that taskId. This interrupts the run that's still in setTimeout(..., 20_000) and starts a new one on the same thread. The subagent sees your new instruction, and the taskId stays the same.
  4. Decide you don't need the product breakdown after all: ask it to cancel that task. It should call cancel_async_task on the product taskId.
  5. Ask for an update on what's left. It should report back the West-region-only breakdown, reflecting the instruction you sent in step 3.

For step 5, it may call list_async_tasks, which reports the status of every tracked task at once instead of one taskId at a time.

Step 1 should come back in a few seconds, not the 20 the analysis itself takes, and step 5's result looks like this:

West region: $78,500 revenue, 2,050 units

Regional ranking by revenue:
1. East    - $99,400 revenue, 2,380 units
2. West    - $78,500 revenue, 2,050 units
3. Central - $54,900 revenue, 1,350 units

If you stop the specialized_agent server partway through, main_agent still reports a taskId immediately and stays responsive, it just can't successfully check the task until that server is back.


Check your understanding

Question: What happens when the main agent calls start_async_task?
A) Its server starts a thread and run; the task ID comes back at once
B) The subagent runs in-process like task, and its final result is returned
C) The full message history is sent over, and the call waits for a reply
D) The job is scheduled for the main agent's next turn and nothing returns
Question: The model just received a task_id from start_async_task, and the user has not asked anything else. What do the tool's usage notes tell it to do?
A) Call check_async_task once to confirm the run started
B) Call check_async_task each turn until the status is final
C) Report the task ID to the user and end its turn
D) Call update_async_task to repeat the instructions
Question: Ten turns ago, check_async_task reported running. Now the user asks whether the report is done. What should the main agent do?
A) Answer running, since statuses in the transcript stay current
B) Repeat the last status recorded in async_tasks without a new call
C) Start a new task, since a task ID expires after one check
D) Call check_async_task again, since the earlier status may be stale
Question: Where does the main agent keep track of a launched async task, and why does that matter?
A) Only in the message history, so it is lost once old messages are summarized
B) In state under async_tasks, so it survives older messages being summarized
C) In a file the agent writes to /tasks/, which it re-reads before each check
D) Only on the remote server, which the agent must search by task description

Check your understanding

Question: What happens when the main agent calls start_async_task?
A) Its server starts a thread and run; the task ID comes back at once
B) The subagent runs in-process like task, and its final result is returned
C) The full message history is sent over, and the call waits for a reply
D) The job is scheduled for the main agent's next turn and nothing returns
Question: The model just received a taskId from start_async_task, and the user has not asked anything else. What do the tool's usage notes tell it to do?
A) Call check_async_task once to confirm the run started
B) Call check_async_task each turn until the status is final
C) Report the task ID to the user and end its turn
D) Call update_async_task to repeat the instructions
Question: Ten turns ago, check_async_task reported running. Now the user asks whether the report is done. What should the main agent do?
A) Answer running, since statuses in the transcript stay current
B) Repeat the last status recorded in asyncTasks without a new call
C) Start a new task, since a task ID expires after one check
D) Call check_async_task again, since the earlier status may be stale
Question: Where does the main agent keep track of a launched async task, and why does that matter?
A) Only in the message history, so it is lost once old messages are summarized
B) In state under asyncTasks, so it survives older messages being summarized
C) In a file the agent writes to /tasks/, which it re-reads before each check
D) Only on the remote server, which the agent must search by task description
Question: In TypeScript, how do you turn a subagent entry into an async one?
A) Build it with createAsyncSubAgent() and pass it to an asyncSubagents option
B) Set async: true on an otherwise normal entry in the subagents array
C) Add graphId (and usually url), keeping it in the same subagents array
D) Wrap the agent in createAsyncSubAgentMiddleware; detection is not automatic