Skip to content

Commit ec3cde5

Browse files
authored
Merge pull request #11 from langchain-ai/palash/subagent-fix
fix: update subagents
2 parents 72ce2a8 + 06c425e commit ec3cde5

File tree

7 files changed

+317
-149
lines changed

7 files changed

+317
-149
lines changed

examples/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2+
# LangGraph API
3+
.langgraph_api

examples/research-agent.ts

Lines changed: 0 additions & 92 deletions
This file was deleted.

examples/research/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2+
# LangGraph API
3+
.langgraph_api

examples/research/langgraph.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"dependencies": ["../"],
3+
"graphs": {
4+
"research": "./research-agent.ts:agent"
5+
},
6+
"env": ".env"
7+
}
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
/* eslint-disable no-console */
2+
import { createDeepAgent, type SubAgent } from "../../src/index.js";
3+
import { tool } from "@langchain/core/tools";
4+
import { z } from "zod";
5+
import "dotenv/config";
6+
import { TavilySearch } from "@langchain/tavily";
7+
8+
type Topic = "general" | "news" | "finance";
9+
10+
// Search tool to use to do research
11+
const internetSearch = tool(
12+
async ({
13+
query,
14+
maxResults = 5,
15+
topic = "general" as Topic,
16+
includeRawContent = false,
17+
}: {
18+
query: string;
19+
maxResults?: number;
20+
topic?: Topic;
21+
includeRawContent?: boolean;
22+
}) => {
23+
/**
24+
* Run a web search
25+
*/
26+
27+
// Note: You'll need to install and import tavily-js or similar package
28+
// For now, this is a placeholder that shows the structure
29+
const tavilySearch = new TavilySearch({
30+
maxResults,
31+
tavilyApiKey: process.env.TAVILY_API_KEY,
32+
includeRawContent,
33+
topic,
34+
});
35+
const tavilyResponse = await tavilySearch.invoke({ query });
36+
37+
return tavilyResponse;
38+
},
39+
{
40+
name: "internet_search",
41+
description: "Run a web search",
42+
schema: z.object({
43+
query: z.string().describe("The search query"),
44+
maxResults: z
45+
.number()
46+
.optional()
47+
.default(5)
48+
.describe("Maximum number of results to return"),
49+
topic: z
50+
.enum(["general", "news", "finance"])
51+
.optional()
52+
.default("general")
53+
.describe("Search topic category"),
54+
includeRawContent: z
55+
.boolean()
56+
.optional()
57+
.default(false)
58+
.describe("Whether to include raw content"),
59+
}),
60+
},
61+
);
62+
63+
const subResearchPrompt = `You are a dedicated researcher. Your job is to conduct research based on the users questions.
64+
65+
Conduct thorough research and then reply to the user with a detailed answer to their question
66+
67+
only your FINAL answer will be passed on to the user. They will have NO knowledge of anything except your final message, so your final report should be your final message!`;
68+
69+
const researchSubAgent: SubAgent = {
70+
name: "research-agent",
71+
description:
72+
"Used to research more in depth questions. Only give this researcher one topic at a time. Do not pass multiple sub questions to this researcher. Instead, you should break down a large topic into the necessary components, and then call multiple research agents in parallel, one for each sub question.",
73+
prompt: subResearchPrompt,
74+
tools: ["internet_search"],
75+
};
76+
77+
const subCritiquePrompt = `You are a dedicated editor. You are being tasked to critique a report.
78+
79+
You can find the report at \`final_report.md\`.
80+
81+
You can find the question/topic for this report at \`question.txt\`.
82+
83+
The user may ask for specific areas to critique the report in. Respond to the user with a detailed critique of the report. Things that could be improved.
84+
85+
You can use the search tool to search for information, if that will help you critique the report
86+
87+
Do not write to the \`final_report.md\` yourself.
88+
89+
Things to check:
90+
- Check that each section is appropriately named
91+
- Check that the report is written as you would find in an essay or a textbook - it should be text heavy, do not let it just be a list of bullet points!
92+
- Check that the report is comprehensive. If any paragraphs or sections are short, or missing important details, point it out.
93+
- Check that the article covers key areas of the industry, ensures overall understanding, and does not omit important parts.
94+
- Check that the article deeply analyzes causes, impacts, and trends, providing valuable insights
95+
- Check that the article closely follows the research topic and directly answers questions
96+
- Check that the article has a clear structure, fluent language, and is easy to understand.
97+
`;
98+
99+
const critiqueSubAgent: SubAgent = {
100+
name: "critique-agent",
101+
description:
102+
"Used to critique the final report. Give this agent some infomration about how you want it to critique the report.",
103+
prompt: subCritiquePrompt,
104+
};
105+
106+
// Prompt prefix to steer the agent to be an expert researcher
107+
const researchInstructions = `You are an expert researcher. Your job is to conduct thorough research, and then write a polished report.
108+
109+
The first thing you should do is to write the original user question to \`question.txt\` so you have a record of it.
110+
111+
Use the research-agent to conduct deep research. It will respond to your questions/topics with a detailed answer.
112+
113+
When you think you enough information to write a final report, write it to \`final_report.md\`
114+
115+
You can call the critique-agent to get a critique of the final report. After that (if needed) you can do more research and edit the \`final_report.md\`
116+
You can do this however many times you want until are you satisfied with the result.
117+
118+
Only edit the file once at a time (if you call this tool in parallel, there may be conflicts).
119+
120+
Here are instructions for writing the final report:
121+
122+
<report_instructions>
123+
124+
CRITICAL: Make sure the answer is written in the same language as the human messages! If you make a todo plan - you should note in the plan what language the report should be in so you dont forget!
125+
Note: the language the report should be in is the language the QUESTION is in, not the language/country that the question is ABOUT.
126+
127+
Please create a detailed answer to the overall research brief that:
128+
1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)
129+
2. Includes specific facts and insights from the research
130+
3. References relevant sources using [Title](URL) format
131+
4. Provides a balanced, thorough analysis. Be as comprehensive as possible, and include all information that is relevant to the overall research question. People are using you for deep research and will expect detailed, comprehensive answers.
132+
5. Includes a "Sources" section at the end with all referenced links
133+
134+
You can structure your report in a number of different ways. Here are some examples:
135+
136+
To answer a question that asks you to compare two things, you might structure your report like this:
137+
1/ intro
138+
2/ overview of topic A
139+
3/ overview of topic B
140+
4/ comparison between A and B
141+
5/ conclusion
142+
143+
To answer a question that asks you to return a list of things, you might only need a single section which is the entire list.
144+
1/ list of things or table of things
145+
Or, you could choose to make each item in the list a separate section in the report. When asked for lists, you don't need an introduction or conclusion.
146+
1/ item 1
147+
2/ item 2
148+
3/ item 3
149+
150+
To answer a question that asks you to summarize a topic, give a report, or give an overview, you might structure your report like this:
151+
1/ overview of topic
152+
2/ concept 1
153+
3/ concept 2
154+
4/ concept 3
155+
5/ conclusion
156+
157+
If you think you can answer the question with a single section, you can do that too!
158+
1/ answer
159+
160+
REMEMBER: Section is a VERY fluid and loose concept. You can structure your report however you think is best, including in ways that are not listed above!
161+
Make sure that your sections are cohesive, and make sense for the reader.
162+
163+
For each section of the report, do the following:
164+
- Use simple, clear language
165+
- Use ## for section title (Markdown format) for each section of the report
166+
- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.
167+
- Do not say what you are doing in the report. Just write the report without any commentary from yourself.
168+
- Each section should be as long as necessary to deeply answer the question with the information you have gathered. It is expected that sections will be fairly long and verbose. You are writing a deep research report, and users will expect a thorough answer.
169+
- Use bullet points to list out information when appropriate, but by default, write in paragraph form.
170+
171+
REMEMBER:
172+
The brief and research may be in English, but you need to translate this information to the right language when writing the final answer.
173+
Make sure the final answer report is in the SAME language as the human messages in the message history.
174+
175+
Format the report in clear markdown with proper structure and include source references where appropriate.
176+
177+
<Citation Rules>
178+
- Assign each unique URL a single citation number in your text
179+
- End with ### Sources that lists each source with corresponding numbers
180+
- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose
181+
- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.
182+
- Example format:
183+
[1] Source Title: URL
184+
[2] Source Title: URL
185+
- Citations are extremely important. Make sure to include these, and pay a lot of attention to getting these right. Users will often use these citations to look into more information.
186+
</Citation Rules>
187+
</report_instructions>
188+
189+
You have access to a few tools.
190+
191+
## \`internet_search\`
192+
193+
Use this to run an internet search for a given query. You can specify the number of results, the topic, and whether raw content should be included.
194+
`;
195+
196+
// Create the agent
197+
const agent = createDeepAgent({
198+
tools: [internetSearch],
199+
instructions: researchInstructions,
200+
subagents: [critiqueSubAgent, researchSubAgent],
201+
}).withConfig({ recursionLimit: 1000 });
202+
203+
// Invoke the agent
204+
async function main() {
205+
const result = await agent.invoke({
206+
messages: [{ role: "user", content: "what is langgraph?" }],
207+
});
208+
console.log(result);
209+
}
210+
211+
export { agent, internetSearch };
212+
213+
// Run if this file is executed directly
214+
if (import.meta.url === `file://${process.argv[1]}`) {
215+
main();
216+
}

src/graph.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,22 @@ import type { StructuredTool } from "@langchain/core/tools";
1717
import { z } from "zod";
1818
import { DeepAgentState } from "./state.js";
1919

20+
/**
21+
* Base prompt that provides instructions about available tools
22+
* Ported from Python implementation to ensure consistent behavior
23+
*/
24+
const BASE_PROMPT = `You have access to a number of standard tools
25+
26+
## \`write_todos\`
27+
28+
You have access to the \`write_todos\` tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
29+
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
30+
31+
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
32+
## \`task\`
33+
34+
- When doing web search, prefer to use the \`task\` tool in order to reduce context usage.`;
35+
2036
/**
2137
* Built-in tools that are always available in Deep Agents
2238
*/
@@ -69,11 +85,16 @@ export function createDeepAgent<
6985
allTools.push(taskTool);
7086
}
7187

88+
// Combine instructions with base prompt like Python implementation
89+
const finalInstructions = instructions
90+
? instructions + BASE_PROMPT
91+
: BASE_PROMPT;
92+
7293
// Return createReactAgent with proper configuration
7394
return createReactAgent({
7495
llm: model,
7596
tools: allTools,
7697
stateSchema,
77-
messageModifier: instructions,
98+
messageModifier: finalInstructions,
7899
});
79100
}

0 commit comments

Comments
 (0)