
想象一下,一个人工智能不仅能回答你的问题,还能提前思考、分解任务、创建待办事项清单,甚至还能生成子智能体来完成工作。这就是深度智能体(Deep Agents)的愿景。人工智能智能体已经将逻辑逻辑模型(LLM)的功能提升到了一个新的高度,今天我们将深入了解深度智能体,看看它们如何能将这种能力进一步提升。深度智能体构建于 LangGraph 之上,LangGraph 是一个专门用于创建能够处理复杂任务的智能体的库。让我们深入了解深度智能体,理解它们的核心功能,然后使用该库构建我们自己的人工智能智能体。
深度智能体
LangGraph 为有状态工作流提供了一个基于图的运行时环境,但你仍然需要从头开始构建自己的规划、上下文管理或任务分解逻辑。而基于 LangGraph 的深度智能体则开箱即用地集成了规划工具、基于虚拟文件系统的内存和子智能体编排功能。
您可以通过独立的 deepagents 库使用 DeepAgents。它包含规划功能,可以生成子代理,并使用文件系统进行上下文管理。它还可以与 LangSmith 结合使用,进行部署和监控。此处构建的代理默认使用“claude-sonnet-4-5-20250929”模型,但您可以对其进行自定义。在开始创建代理之前,让我们先了解一下其核心组件。

Source: Deep Agents
核心组件
- 详细系统提示 – 深度智能体使用包含详细说明和示例的系统提示。
- 规划工具 – 深度智能体内置规划工具,即待办事项列表管理工具。这有助于它们即使在执行复杂任务时也能保持专注。
- 子智能体 – 子智能体为委派的任务生成,并在上下文隔离中执行。
- 文件系统 – 用于上下文管理和内存管理的虚拟文件系统。当上下文窗口已满时,AI 智能体使用文件作为工具将上下文卸载到内存中。
构建深度智能体
现在,让我们使用“deepagents”库构建一个研究智能体,它将使用 Tavily 进行网络搜索,并包含深度智能体的所有组件。
注意:我们将在 Google Colab 中进行本教程。
前提条件
您需要一个 OpenAI 密钥才能创建此代理。您也可以选择使用其他模型提供商,例如 Gemini/Claude。请从 OpenAI 平台获取您的密钥:https://platform.openai.com/api-keys
此外,请从此处获取用于网络搜索的 Tavily API 密钥:https://app.tavily.com/home

在 Google Colab 中新建一个笔记本,并添加密钥:

将密钥分别保存为 OPENAI_API_KEY 和 TAVILY_API_KEY(用于演示),并记得启用笔记本访问权限。
要求
!pip install deepagents tavily-python langchain-openai
我们将安装运行代码所需的这些库。
导入和 API 设置
import os
from deepagents import create_deep_agent
from tavily import TavilyClient
from langchain.chat_models import init_chat_model
from google.colab import userdata
# Set API keys
TAVILY_API_KEY=userdata.get("TAVILY_API_KEY")
os.environ["OPENAI_API_KEY"]=userdata.get("OPENAI_API_KEY")
我们将 Tavily API 存储在一个变量中,将 OpenAI API 存储在环境变量中。
定义工具、子代理和代理。
# Initialize Tavily client
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
# Define web search tool
def internet_search(query: str, max_results: int = 5) -> str:
"""Run a web search to find current information"""
results = tavily_client.search(query, max_results=max_results)
return results
# Define a specialized research sub-agent
research_subagent = {
"name": "data-analyzer",
"description": "Specialized agent for analyzing data and creating detailed reports",
"system_prompt": """You are an expert data analyst and report writer.
Analyze information thoroughly and create well-structured, detailed reports.""",
"tools": [internet_search],
"model": "openai:gpt-4o",
}
# Initialize GPT-4o-mini model
model = init_chat_model("openai:gpt-4o-mini")
# Create the deep agent
# The agent automatically has access to: write_todos, read_todos, ls, read_file,
# write_file, edit_file, glob, grep, and task (for subagents)
agent = create_deep_agent(
model=model,
tools=[internet_search], # Passing the tool
system_prompt="""You are a thorough research assistant. For this task:
1. Use write_todos to create a task list breaking down the research
2. Use internet_search to gather current information
3. Use write_file to save your findings to /research_findings.md
4. You can delegate detailed analysis to the data-analyzer subagent using the task tool
5. Create a final comprehensive report and save it to /final_report.md
6. Use read_todos to check your progress
Be systematic and thorough in your research.""",
subagents=[research_subagent],
)
我们定义了一个用于网络搜索的工具,并将其传递给了我们的智能体。在本演示中,我们使用 OpenAI 的“gpt-4o-mini”模型。您可以将其更改为任何其他模型。
另请注意,我们没有创建任何文件,也没有为卸载上下文和待办事项列表所需的文件系统定义任何内容。这些内容已在“create_deep_agent()”函数中预先构建,智能体可以访问它们。
运行推理
# Research query
research_topic = "What are the latest developments in AI agents and LangGraph in 2025?"
print(f"Starting research on: {research_topic}\n")
print("=" * 70)
# Execute the agent
result = agent.invoke({
"messages": [{"role": "user", "content": research_topic}]
})
print("\n" + "=" * 70)
print("Research completed.\n")

注意:代理程序的执行可能需要一些时间。
查看输出
# Agent execution trace
print("AGENT EXECUTION TRACE:")
print("-" * 70)
for i, msg in enumerate(result["messages"]):
if hasattr(msg, 'type'):
print(f"\n[{i}] Type: {msg.type}")
if msg.type == "human":
print(f"Human: {msg.content}")
elif msg.type == "ai":
if hasattr(msg, 'tool_calls') and msg.tool_calls:
print(f"AI tool calls: {[tc['name'] for tc in msg.tool_calls]}")
if msg.content:
print(f"AI: {msg.content[:200]}...")
elif msg.type == "tool":
print(f"Tool '{msg.name}' result: {str(msg.content)[:200]}...")

# Final AI response
print("\n" + "=" * 70)
final_message = result["messages"][-1]
print("FINAL RESPONSE:")
print("-" * 70)
print(final_message.content)

# Files created
print("\n" + "=" * 70)
print("FILES CREATED:")
print("-" * 70)
if "files" in result and result["files"]:
for filepath in sorted(result["files"].keys()):
content = result["files"][filepath]
print(f"\n{'=' * 70}")
print(f"{filepath}")
print(f"{'=' * 70}")
print(content)
else:
print("No files found.")
print("\n" + "=" * 70)
print("Analysis complete.")

正如我们所见,该代理表现良好,它维护了一个虚拟文件系统,并在多次迭代后给出了响应,因此我们认为它应该算得上是一个“深度代理”。但是我们的系统仍有改进空间,让我们在下一个系统中探讨这些改进。
代理的潜在改进
我们构建了一个简单的深度代理,但您可以挑战自己,构建一个更强大的系统。以下是一些您可以改进此代理的方法:
- 使用长期记忆 – 深度代理可以将用户偏好和反馈保存在文件(/memories/)中。这将有助于代理提供更好的答案,并从对话中构建知识库。
- 控制文件系统 – 默认情况下,文件存储在虚拟环境中,您可以使用 deepagents.backends 中的“FilesystemBackend”将其存储到不同的后端或本地磁盘。
- 优化系统提示 – 您可以测试多个提示,看看哪个最适合您。
小结
我们已成功构建了深度智能体,现在可以看到,利用 LangGraph 处理任务,人工智能智能体如何将 LLM 的功能提升到一个新的高度。凭借内置的规划、子智能体和虚拟文件系统,它们能够流畅地管理待办事项、上下文和研究工作流程。深度智能体固然强大,但也要记住,如果某个任务更简单,可以用简单的智能体或 LLM 完成,则不建议使用深度智能体。


评论留言