Subagents, Files, and Skills: A Deep Research Assistant Built on Deep Agents
Recreate a Deep Research Assistant with Deep Agents: From Main Agent, Sub Agents to Skill
This article is intended for readers who already understand the basic concepts of LangChain and LangGraph but haven't used Deep Agents.
We will work together to reproduce a "mini deep research assistant":
- Formulate a research plan based on the user's question;
- Call the Bocha search API to obtain web resources;
- Delegate different subtopics to multiple researchers;
- Use QuickJS for data processing;
- Organize the material into a Chinese report;
- Pass intermediate results via files instead of long conversations.
The amount of code in this demo is small, but it contains many core concepts in agent engineering: tools, sub-agents, context isolation, filesystem backend, Skills, streaming events, and prompt boundaries.
1. Why not use a regular Agent
A normal agent usually has a single conversation context:
User question -> search -> read web page -> write report
When the task is short, it's fine, but deep research exposes several obvious pain points:
- Many search results; putting them all into the same context quickly blows it up;
- Multiple subtopics may interfere with each other;
- Research, computation, and review require different roles;
- Intermediate results need a stable storage location;
- Long tasks easily forget early information because the context is too long.
Deep Agents' approach is to break these problems apart:
Main Agent
├─ Responsible for planning and final delivery
├─ Delegates sub-agents via task
├─ Passes intermediate results through the filesystem
└─ Loads domain workbooks via Skills
In this demo, the responsibilities of each role are as follows:
| Role | Responsibility |
|---|---|
| Main Agent | Planning, delegation, drafting, revising, finalizing |
researcher |
Research one focused subtopic and write a findings file |
analyst |
Do calculations and data analysis via a QuickJS REPL |
editor |
Review the draft, give feedback only, don't modify the report |
general-purpose |
A general-purpose sub-agent automatically added by Deep Agents |
Note that general-purpose does not need to be manually written into subagents; createDeepAgent provides it by default.
2. Final runtime flow
The whole system can be abstracted as the following chain:
CLI receives the question
↓
Main Agent writes question.txt and research_plan.md
↓
Starts 1–3 researcher agents via task
↓
researcher calls web_search
↓
researcher writes the results into findings_*.md
↓
When computation is needed, the analyst is started
↓
Main Agent reads the files and writes draft_*.md
↓
editor reviews the draft
↓
Main Agent revises and writes report_*_YYYY-MM-DD.md
There is a very important design decision here:
Sub-agents primarily communicate through files, rather than relying on the full conversation history.
Researchers use an isolated context by default. They don't see any of the main agent's previous conversation; they only receive the task description passed through the task tool. Therefore, the findings file must be complete and self-contained.
3. Prepare the project structure
The following directory layout is recommended:
deep-research-assistant/
├── .env
├── package.json
├── src/
│ ├── agent.mjs
│ ├── cli.mjs
│ ├── tools/
│ │ └── search.mjs
│ └── skills/
│ ├── web-research/
│ │ └── SKILL.md
│ └── report-writer/
│ └── SKILL.md
└── workspace/
├── sources/
└── reports/
Core dependencies:
{
"dependencies": {
"@langchain/core": "^1.4.2",
"@langchain/langgraph": "^1.7.5",
"@langchain/openai": "^1.8.4",
"@langchain/quickjs": "^0.6.7",
"deepagents": "^1.17.0",
"dotenv": "^18.0.10",
"langchain": "^1.6.7",
"zod": "^4.6.7"
}
}
At minimum, the .env needs:
MODEL_NAME=your model name
OPENAI_API_KEY=your model key
OPENAI_BASE_URL=the API endpoint compatible with the OpenAI protocol
BOCHA_API_KEY=your Bocha search key
Don't commit real keys to Git.
4. Set up the filesystem backend first
Deep Agents provides read_file, write_file, edit_file, ls, glob, and grep file tools by default.
These tools need a Backend to decide which directory they ultimately access:
import path from "node:path";
import { fileURLToPath } from "node:url";
import { FilesystemBackend } from "deepagents";
const projectDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
".."
);
const backend = new FilesystemBackend({
rootDir: projectDir,
virtualMode: true
});
When virtualMode is true:
/workspace/sources/question.txt
will map to:
<project root>/workspace/sources/question.txt
This has two benefits:
- Prompts and Skills always use stable virtual paths;
- The real project directory isn't hardcoded into every prompt segment.
On Windows, the final path looks like:
C:\workSpace\...\deep-research-assistant\workspace\sources\question.txt
5. Wrap the Bocha search tool
The agent won't learn to search the web by itself. We need to wrap the Bocha API into a tool using LangChain's tool().
import { tool } from "langchain";
import { z } from "zod";
const BOCHA_API_URL = "https://api.bochaai.com/v1/web-search";
async function bochaWebSearch(query, count) {
const apiKey = process.env.BOCHA_API_KEY?.trim();
if (!apiKey) {
throw new Error("BOCHA_API_KEY is not set");
}
const response = await fetch(BOCHA_API_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
query,
count,
summary: true
})
});
if (!response.ok) {
throw new Error(`Search failed: ${response.status}`);
}
const json = await response.json();
const pages = json.data?.webPages?.value ?? [];
return pages.map((page, index) => `
Citation: ${index + 1}
Title: ${page.name ?? ""}
URL: ${page.url ?? ""}
Summary: ${page.summary ?? ""}
Site: ${page.siteName ?? ""}
`).join("\n");
}
export const webSearch = tool(
async (input) => {
return bochaWebSearch(input.query, input.count);
},
{
name: "web_search",
description: "Use Bocha to search the internet; prefer Chinese keywords.",
schema: z.object({
query: z
.string()
.trim()
.min(2)
.max(200)
.describe("Search keywords"),
count: z
.number()
.int()
.min(1)
.max(20)
.default(10)
.describe("Number of results")
})
}
);
Two concepts here:
- The
descriptionand Zod Schema are the calling instructions for the model. - The code inside the tool function is the actual execution logic.
The model usually generates arguments based on the Schema, but that's not absolute obedience. The real business boundary still has to be implemented in the tool code or in Middleware.
For example:
- The 1–20 range for
countcan be validated by the Schema. - Network timeouts, retries, and API rate limiting need to be handled by the tool code.
- "Each researcher can search at most three times" written only in a prompt is not reliable.
6. Define the researcher sub-agent
The researcher's configuration mainly covers four items:
const researchSubAgent = {
name: "researcher",
description: "Research a single subtopic and write a findings file.",
systemPrompt: `
You are a researcher responsible for a focused subtopic.
Workflow:
1. Use web_search to search for materials;
2. Organize key facts and source URLs;
3. Use write_file to write to the file specified in the task:
/workspace/sources/findings_*.md;
4. End immediately after writing once.
`,
tools: [webSearch]
};
Here tools: [webSearch] adds a custom search tool for the researcher.
Note that file tools aren't manually added here. The SubAgent Middleware in Deep Agents automatically provides read_file, write_file, and other basic tools.
Why task allows two agents to collaborate
task is a built-in tool in Deep Agents; it doesn't need to be written into the top-level tools array.
It roughly has only two parameters:
{
"description": "The complete task handed to a sub-agent",
"subagent_type": "researcher"
}
For example, the main agent might generate:
{
"description": "Research AI industry news for November 2026. Write the results to /workspace/sources/findings_ai_news.md.",
"subagent_type": "researcher"
}
Deep Agents turns the description exactly into the sub-agent's user message, then starts the researcher.
So if you need the researcher to write to a specific file, the filename has to go into the description. task doesn't have a structured output_file parameter.
7. Define the analyst and the editor
1. Analyst
The analyst needs to actually execute JavaScript, not have the model do mental math.
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const analystSubAgent = {
name: "analyst",
description: "Use a QuickJS REPL for calculation, ranking, and data processing.",
systemPrompt: `
You are a data analyst.
1. Read data from /workspace/sources/;
2. Use the eval REPL to run calculations;
3. Write the calculation logic and conclusions into /workspace/sources/analysis_*.md;
4. Never guess numbers without executing code.
`,
middleware: [createCodeInterpreterMiddleware()]
};
Worth noting: the eval capability isn't obtained through a prompt; it's really injected by createCodeInterpreterMiddleware().
2. Editor
The editor only reviews; it doesn't modify files:
const editorSubAgent = {
name: "editor",
description: "Review report drafts and provide revision suggestions.",
systemPrompt: `
You are a senior editor. You only review; you don't modify the report.
Check for:
- Whether the original question is answered;
- Whether the structure is clear;
- Whether sources are cited;
- Whether there are unsupported assertions;
- Whether there are information gaps.
Return your opinions to the main agent. Do not write to the report file.
`
};
The main agent, after receiving the review opinions, calls edit_file itself to modify the draft.
This avoids multiple agents modifying the same file at the same time.
8. Write the main agent's orchestration prompt
The main agent is responsible for the whole process, but it shouldn't do all the research itself.
const orchestratorPrompt = `
You are the main agent of the "Deep Research Assistant," responsible for coordinating the research, analysis, and editing.
Standard flow:
1. Write the user question into /workspace/sources/question.txt;
2. Create /workspace/sources/research_plan.md;
3. Delegate researchers via task to research subtopics;
4. Delegate the analyst when calculations are involved;
5. Write the report draft yourself;
6. Delegate the editor via task to review;
7. Revise once according to the feedback;
8. Write the final version to /workspace/reports/.
Rules:
- Each researcher handles only one subtopic;
- Use at most 3 researchers per report;
- Drafting and finalizing can't be delegated;
- All file content should be in Chinese.
`;
This prompt's role is to "tell the model when to use which tool," not to create tools.
What the main agent can do still depends on:
- The file tools that come with Deep Agents;
- The automatically mounted
tasktool; - Your custom search tool;
- Any extra Middleware you add.
9. What a Skill is
A Skill is best understood as an "on-demand work manual."
For example:
src/skills/web-research/SKILL.md
Its content might be:
---
name: web-research
description: Structured multi-source web research, suitable for research, comparison, and deep analysis tasks
---
# Web Research Skill
1. Write the user question into /workspace/sources/question.txt.
2. Create /workspace/sources/research_plan.md.
3. Break the question into 2–4 subtopics that don't overlap.
4. Delegate researchers via task.
5. Researchers write independent results into findings_*.md.
6. The main agent reads all findings files before synthesizing.
There are three easily misunderstood points about Skills.
1. A Skill is not a sub-agent
A Skill isn't a subagent_type. It's a work guide the main agent can consult.
Correct:
subagent_type: researcher
Wrong:
subagent_type: web-research
2. A Skill usually isn't injected in full
The Skills Middleware first reads each Skill's name and description and tells the model which Skills are available. When the model thinks one is relevant, it reads the full SKILL.md.
This is progressive context loading, which avoids all guides filling the prompt from the start.
3. A Skill is guidance, not a hard constraint
Rules like "write a plan before researching" or "search at most three times" written in a Skill are usually understood by the model, but there's no guarantee of absolute enforcement.
If you need a hard constraint, use:
- A custom tool wrapper;
- Middleware;
- Filesystem permissions;
- A separate validation node;
- Structured output.
10. Create the Deep Agent
Finally, assemble the model, sub-agents, Backend, and Skills:
import { ChatOpenAI } from "@langchain/openai";
import { createDeepAgent } from "deepagents";
const model = new ChatOpenAI({
model: process.env.MODEL_NAME,
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: process.env.OPENAI_BASE_URL
},
temperature: 0
});
export function createResearchAgent() {
return createDeepAgent({
model,
systemPrompt: orchestratorPrompt,
subagents: [
researchSubAgent,
analystSubAgent,
editorSubAgent
],
backend,
skills: ["/src/skills/"]
});
}
Here's an easy trap to fall into.
The project root is:
deep-research-assistant/
The FilesystemBackend root is also that. So:
skills: ["/src/skills/"]
will correctly map to:
deep-research-assistant/src/skills/
If the actual files are in src/skills but you write:
skills: ["/skills/"]
it will look for:
deep-research-assistant/skills/
That directory doesn't exist. Deep Agents usually silently skips Skills it can't read, so the agent still runs, but the Skill is never loaded.
11. About write_todos
Many Deep Agents tutorials mention write_todos, but in newer versions, whether it exists automatically depends on the Harness Profile for the model.
For example, in [email protected], some Codex model configurations automatically mount Todo Middleware, while ordinary OpenAI-compatible models don't necessarily get write_todos automatically.
If the prompt asks the model to use write_todos but at runtime you see invalid tool calls or the model doesn't plan at all, check first whether the tool actually exists.
If needed, you can add it explicitly:
import { todoListMiddleware } from "langchain";
return createDeepAgent({
model,
systemPrompt: orchestratorPrompt,
subagents: [
researchSubAgent,
analystSubAgent,
editorSubAgent
],
middleware: [todoListMiddleware()],
backend,
skills: ["/src/skills/"]
});
The principle is simple:
Before prompting a tool, confirm that tool is actually registered.
12. Write a minimal CLI
When reproducing this for the first time, don't rush to listen to all sub-graph events. First use invoke to get the smallest loop working:
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin, stdout } from "node:process";
import { HumanMessage } from "@langchain/core/messages";
import { createResearchAgent } from "./agent.mjs";
async function main() {
const rl = readline.createInterface({
input: stdin,
output: stdout
});
const query = (await rl.question("请输入调研主题:")).trim();
rl.close();
const agent = createResearchAgent();
const result = await agent.invoke(
{
messages: [new HumanMessage(query)]
},
{
recursionLimit: 300
}
);
const lastMessage = result.messages.at(-1);
console.log(lastMessage?.content);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
Run:
node src/cli.mjs
Or pass the question directly:
import { argv } from "node:process";
const query = argv.slice(2).join(" ").trim();
Then:
node src/cli.mjs "2026年11月有哪些值得关注的AI新闻?"
Once the minimal loop works, switch from invoke to streaming output:
for await (const [namespace, chunk] of await agent.stream(
{
messages: [new HumanMessage(query)]
},
{
streamMode: "updates",
subgraphs: true,
recursionLimit: 300
}
)) {
console.log("Sub-graph:", namespace?.join("/") || "root");
console.dir(chunk, { depth: 3 });
}
This lets you see the runtime events from the main graph, researcher, analyst, and editor.
13. Common problems in the current demo
When reproducing, actively avoid these issues.
1. Inconsistent Skill path
Files are in src/skills, but the config says /skills/.
Solution:
skills: ["/src/skills/"]
or move the directory into a skills/ folder under the project root.
2. Conflicting search-count rules
The researcher prompt says "at most 3 times," while the Skill says "at most 10 times."
When the model sees two sets of rules, its behavior can become unstable. Keep only one explicit limit, preferably implemented in code.
3. Different tasks share the same directory
If the previous task left a findings_old.md, and the main agent reads:
/workspace/sources/findings_*.md
old material will get mixed into the new report.
A more robust structure is:
workspace/runs/2026-11-23-ai-news/
├── question.txt
├── research_plan.md
├── findings_*.md
└── reports/
Each task uses its own directory.
4. CLI only prints tool calls
If the CLI only outputs:
tool_calls=1 ["web_search"]
and doesn't print the message body, the user can't see the final result.
At minimum, output:
- The AI's final text;
- The report file path;
- Whether sub-agents succeeded;
- Search or tool errors.
5. Search errors are treated as ordinary content
If a failed search API call only returns an error string, the model may treat it as search results and continue.
A better approach is to throw an error or return a structured status:
return {
ok: false,
error: "BOCHA_API_KEY_MISSING"
};
Whether to retry or continue should be explicitly decided by the agent or by the upper-level code.
14. From prompt-driven to engineering constraints
This demo is a good entry point for Deep Agents, but as you continue learning, don't stop at "writing rules into prompts."
You can add these capabilities in order.
1. Search budget
Don't just tell the researcher "search at most three times." Record the actual number of calls in a tool or in Middleware.
2. Output file validation
After the task completes, check:
- whether the findings file exists;
- whether the content is empty;
- whether it includes source URLs;
- whether the filename matches the convention.
3. Request timeout and retry
Add timeout, retry, and error classification to the Bocha request, so a network failure doesn't stall the whole agent.
4. File permissions
Restrict the researcher to writing only to sources, make the editor read-only, and allow only the main agent to write the final report.
5. Checkpointer
Use thread_id to save task state so long tasks can be resumed after interruption.
6. Human approval
Pause and wait for a human confirmation when the search budget is exhausted, when a final report is about to be written, or when a high-cost tool is called.
7. Observability
Record each sub-agent's tool calls, time taken, tokens, errors, and the final artifact path.
15. What this demo really teaches
If you only look at the surface of the code, it does seem to be mostly writing prompts:
define researcher -> write researcher prompt
define analyst -> write analyst prompt
define editor -> write editor prompt
then stuff them into createDeepAgent
But from an agent-engineering perspective, the more important thing is to understand this division of labor:
System Prompt: defines role and work strategy
Tools: provide actions the model can perform
Subagents: isolate responsibilities and context
Task: passes tasks between agents
Backend: provides a stable file and state boundary
Skills: load domain workbooks on demand
Middleware: implements real control and cross-cutting logic
Checkpointer: handles persistence and recovery
Prompts decide how the agent "wants to do things," and code decides what the agent "can do" and "cannot do."
When you can transform a rule written in a prompt into a tool contract, Middleware, or a validation node, you've moved from "writing agent prompts" to "building agent systems."
Conclusion
This deep research assistant isn't complex, but it covers the main skeleton of a complete agent system:
- The LLM is responsible for planning and decision-making;
- Tools are responsible for interacting with the outside world;
- Sub-agents are responsible for isolating different responsibilities;
- Files carry the context of long tasks;
- Skills are responsible for organizing domain knowledge;
- Middleware and the Backend are responsible for execution boundaries.
The recommended reproduction order is:
- First get the main agent and file read/write working;
- Add the Bocha search tool;
- Add one researcher sub-agent;
- Correctly load one Skill;
- Add search-result files;
- Add the editor review step;
- Finally add Middleware, validation, Checkpointer, and observability.
After each layer, observe how the agent's behavior changes. That way, what you reproduce isn't just a demo, but a set of agent-engineering methods you can continue to extend.