深度智慧體教程:使用LangGraph和Web搜尋工具建立高階AI智慧體

深度智慧體教程:使用LangGraph和Web搜尋工具建立高階AI智慧體

文章目录

  • 深度智慧體
  • 核心元件
  • 構建深度智慧體
  • 前提條件
  • 要求
  • 匯入和 API 設定
  • 定義工具、子代理和代理。
  • 執行推理
  • 檢視輸出
  • 代理的潛在改進
  • 小結

使用LangGraph和Web搜尋工具建立高階AI智慧體

想象一下,一個人工智慧不僅能回答你的問題,還能提前思考、分解任務、建立待辦事項清單,甚至還能生成子智慧體來完成工作。這就是深度智慧體(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

Tavily API 金鑰

在 Google Colab 中新建一個筆記本,並新增金鑰:

在 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.")

檢視輸出

正如我們所見,該代理表現良好,它維護了一個虛擬檔案系統,並在多次迭代後給出了響應,因此我們認為它應該算得上是一個“深度代理”。但是我們的系統仍有改進空間,讓我們在下一個系統中探討這些改進。

代理的潛在改進

我們構建了一個簡單的深度代理,但您可以挑戰自己,構建一個更強大的系統。以下是一些您可以改進此代理的方法:

  1. 使用長期記憶 – 深度代理可以將使用者偏好和反饋儲存在檔案(/memories/)中。這將有助於代理提供更好的答案,並從對話中構建知識庫。
  2. 控制檔案系統 – 預設情況下,檔案儲存在虛擬環境中,您可以使用 deepagents.backends 中的“FilesystemBackend”將其儲存到不同的後端或本地磁碟。
  3. 最佳化系統提示 – 您可以測試多個提示,看看哪個最適合您。

小結

我們已成功構建了深度智慧體,現在可以看到,利用 LangGraph 處理任務,人工智慧智慧體如何將 LLM 的功能提升到一個新的高度。憑藉內建的規劃、子智慧體和虛擬檔案系統,它們能夠流暢地管理待辦事項、上下文和研究工作流程。深度智慧體固然強大,但也要​​記住,如果某個任務更簡單,可以用簡單的智慧體或 LLM 完成,則不建議使用深度智慧體。

 

評論留言