Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/research_mcp/.example.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
OPENAI_API_KEY=
7 changes: 7 additions & 0 deletions examples/research_mcp/langgraph.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"dependencies": ["."],
"graphs": {
"research": "./research_agent.py:agent"
},
"env": ".env"
}
6 changes: 6 additions & 0 deletions examples/research_mcp/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
deepagents
langgraph-cli[inmem]
tavily-python
langchain-mcp-adapters
langchain-openai
python-dotenv
187 changes: 187 additions & 0 deletions examples/research_mcp/research_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import os
import asyncio
from typing import Literal
from dotenv import load_dotenv
from tavily import TavilyClient

from langchain.chat_models import init_chat_model
from langchain_mcp_adapters.client import MultiServerMCPClient
from deepagents import create_deep_agent, SubAgent

load_dotenv()

sub_research_prompt = """You are a dedicated researcher. Your job is to conduct research based on the users questions.

Conduct thorough research and then reply to the user with a detailed answer to their question"""

research_sub_agent = {
"name": "research-agent",
"description": "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.",
"prompt": sub_research_prompt,
}

sub_critique_prompt = """You are a dedicated editor. You are being tasked to critique a report.

You can find the report at `final_report.md`.

You can find the question/topic for this report at `question.txt`.

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.

You can use the search tool to search for information, if that will help you critique the report

Do not write to the `final_report.md` yourself.

Things to check:
- Check that each section is appropriately named
- 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!
- Check that the report is comprehensive. If any paragraphs or sections are short, or missing important details, point it out.
- Check that the article covers key areas of the industry, ensures overall understanding, and does not omit important parts.
- Check that the article deeply analyzes causes, impacts, and trends, providing valuable insights
- Check that the article closely follows the research topic and directly answers questions
- Check that the article has a clear structure, fluent language, and is easy to understand.
"""

critique_sub_agent = {
"name": "critique-agent",
"description": "Used to critique the final report. Give this agent some infomration about how you want it to critique the report.",
"prompt": sub_critique_prompt,
}


# Prompt prefix to steer the agent to be an expert researcher
research_instructions = """You are an expert researcher. Your job is to conduct thorough research, and then write a polished report.

The first thing you should do is to write the original user question to `question.txt` so you have a record of it.

Use the research-agent to conduct deep research. It will respond to your questions/topics with a detailed answer.

When you think you enough information to write a final report, write it to `final_report.md`

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`
You can do this however many times you want until are you satisfied with the result.

Only edit the file once at a time (if you call this tool in parallel, there may be conflicts).

Here are instructions for writing the final report:

<report_instructions>

CRITICAL: Make sure the answer is written in the same language as the human messages!
For example, if the user's messages are in English, then MAKE SURE you write your response in English. If the user's messages are in Chinese, then MAKE SURE you write your entire response in Chinese.
This is critical. The user will only understand the answer if it is written in the same language as their input message.

Please create a detailed answer to the overall research brief that:
1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)
2. Includes specific facts and insights from the research
3. References relevant sources using [Title](URL) format
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.
5. Includes a "Sources" section at the end with all referenced links

You can structure your report in a number of different ways. Here are some examples:

To answer a question that asks you to compare two things, you might structure your report like this:
1/ intro
2/ overview of topic A
3/ overview of topic B
4/ comparison between A and B
5/ conclusion

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.
1/ list of things or table of things
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.
1/ item 1
2/ item 2
3/ item 3

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:
1/ overview of topic
2/ concept 1
3/ concept 2
4/ concept 3
5/ conclusion

If you think you can answer the question with a single section, you can do that too!
1/ answer

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!
Make sure that your sections are cohesive, and make sense for the reader.

For each section of the report, do the following:
- Use simple, clear language
- Use ## for section title (Markdown format) for each section of the report
- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.
- Do not say what you are doing in the report. Just write the report without any commentary from yourself.
- 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.
- Use bullet points to list out information when appropriate, but by default, write in paragraph form.

REMEMBER:
The brief and research may be in English, but you need to translate this information to the right language when writing the final answer.
Make sure the final answer report is in the SAME language as the human messages in the message history.

Format the report in clear markdown with proper structure and include source references where appropriate.

<Citation Rules>
- Assign each unique URL a single citation number in your text
- End with ### Sources that lists each source with corresponding numbers
- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose
- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.
- Example format:
[1] Source Title: URL
[2] Source Title: URL
- 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.
</Citation Rules>
</report_instructions>

You have access to a few tools.

## `cloudflare-docs`

Use this to search for information about Cloudflare products.

You can use this tool to search for information about Cloudflare products.
"""

# Add Cloudflare Docs MCP Tool
# https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/docs-vectorize#prompt-examples
mcp_client = MultiServerMCPClient({
"cloudflare-docs": {
"url": "https://docs.mcp.cloudflare.com/sse",
"transport": "sse"
},
},
)

# Example Query
query = (
"Do Cloudflare Workers costs depend on response sizes? "
"I want to serve some images (map tiles) from an R2 bucket and I'm concerned about costs."
"Please provide a detailed answer."
)

async def main():
mcp_tools = await mcp_client.get_tools()
agent = create_deep_agent(
mcp_tools,
research_instructions,
subagents=[critique_sub_agent, research_sub_agent],
model=init_chat_model(
model="openai:gpt-4.1-nano",
temperature=0.0,
max_tokens=32768,
),
).with_config({"recursion_limit": 10})
async for chunk in agent.astream({"messages": [{"role": "user", "content": query}]}):
if chunk.get('agent'):
if chunk['agent']['messages'][-1].content:
print("\n*** AGENT OUTPUT ***")
print(chunk['agent']['messages'][-1].content)
if chunk['agent']['messages'][-1].tool_calls:
print("\n*** TOOL INPUT ***")
print(chunk['agent']['messages'][-1].tool_calls)
if chunk.get('tools'):
print("\n*** TOOL OUTPUT ***")
print(chunk['tools']['messages'][-1].content)

if __name__ == "__main__":
asyncio.run(main())