阿尔弗雷德随时为您服务。作为韦恩先生的可靠管家,我有幸记录下我是如何协助韦恩先生处理各种文档工作的。在他忙于夜间活动的时候,我会确保他所有的文件、培训计划以及营养计划都得到妥善的分析和整理。
在离开之前,他留下了一张写有本周训练计划的纸条。于是,我承担起了制定计划的责任。 菜单 用于明天的餐饮。
对于未来的此类事件,让我们使用 LangGraph 创建一个文档分析系统,以满足韦恩先生的需求。该系统可以:
- 处理图像文档
- 使用视觉模型提取文本(视觉语言模型)
- 在需要时进行计算(以演示常规工具)
- 分析内容并提供简洁的摘要
- 执行与文档相关的特定指令
智能体的工作流程
我们构建的工作流程遵循以下结构化的模式:

[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。
设置环境
%pip install langgraph langchain_openai langchain_core
以及导入:
import base64
from typing import List, TypedDict, Annotated, Optional
from langchain_openai import ChatOpenAI
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
from langgraph.graph.message import add_messages
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from IPython.display import Image, display
定义智能体的状态
这个状态比我们之前看到的那些要复杂一些。
AnyMessage 是Langchain中的一个类,用于定义消息。 add_messages 是一种操作符,它添加最新的消息,而不是用最新的状态覆盖它。
这是 LangGraph中的一个新概念,你可以在智能体的状态中添加操作符来定义它们相互作用的方式。
class AgentState(TypedDict):
# The document provided
input_file: Optional[str] # Contains file path (PDF/PNG)
messages: Annotated[list[AnyMessage], add_messages]
准备工具
vision_llm = ChatOpenAI(model="gpt-4o")
def extract_text(img_path: str) -> str:
"""
Extract text from an image file using a multimodal model.
Master Wayne often leaves notes with his training regimen or meal plans.
This allows me to properly analyze the contents.
"""
all_text = ""
try:
# Read image and encode as base64
with open(img_path, "rb") as image_file:
image_bytes = image_file.read()
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
# Prepare the prompt including the base64 image data
message = [
HumanMessage(
content=[
{
"type": "text",
"text": (
"Extract all the text from this image. "
"Return only the extracted text, no explanations."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_base64}"
},
},
]
)
]
# Call the vision-capable model
response = vision_llm.invoke(message)
# Append extracted text
all_text += response.content + "\n\n"
return all_text.strip()
except Exception as e:
# A butler should handle errors gracefully
error_msg = f"Error extracting text: {str(e)}"
print(error_msg)
return ""
def divide(a: int, b: int) -> float:
"""Divide a and b - for Master Wayne's occasional calculations."""
return a / b
# Equip the butler with tools
tools = [
divide,
extract_text
]
llm = ChatOpenAI(model="gpt-4o")
llm_with_tools = llm.bind_tools(tools, parallel_tool_calls=False)
节点
def assistant(state: AgentState):
# System message
textual_description_of_tool="""
extract_text(img_path: str) -> str:
Extract text from an image file using a multimodal model.
Args:
img_path: A local image file path (strings).
Returns:
A single string containing the concatenated text extracted from each image.
divide(a: int, b: int) -> float:
Divide a and b
"""
image=state["input_file"]
sys_msg = SystemMessage(content=f"You are a helpful butler named Alfred that serves Mr. Wayne and Batman. You can analyse documents and run computations with provided tools:\n{textual_description_of_tool} \n You have access to some optional images. Currently the loaded image is: {image}")
return {
"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])],
"input_file": state["input_file"]
}
ReAct模式:我如何协助韦恩先生
让我来解释一下这个智能体的方法。这个智能体遵循所谓的ReAct模式(Reason-Act-Observe)。
- 理由 关于他的文件和请求
- 行动 通过使用合适的工具
- 观察 结果
- 重复 根据需要,直到我完全满足了他的需求
这是一个使用 LangGraph的智能体简单实现。
# The graph
builder = StateGraph(AgentState)
# Define nodes: these do the work
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
# Define edges: these determine how the control flow moves
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
"assistant",
# If the latest message requires a tool, route to tools
# Otherwise, provide a direct response
tools_condition,
)
builder.add_edge("tools", "assistant")
react_graph = builder.compile()
# Show the butler's thought process
display(Image(react_graph.get_graph(xray=True).draw_mermaid_png()))
我们定义了一个 tools 包含我们工具列表的节点。 assistant 节点只是带有绑定工具的模型。
我们创建了一个包含…的图。 assistant 和 tools 节点。
我们添加了 tools_condition 边缘,用于路由 End 或为了 tools 基于是否 assistant 调用工具。
现在,我们增加一个新的步骤:
我们连接智能体 tools 回到节点 assistant,形成一个循环。
- 之后
assistant智能体执行,tools_condition检查模型的输出是否为工具调用。 - 如果是工具调用,流程将导向
tools节点。 - 这个
tools智能体回连assistant. - 这个循环会一直持续下去,只要智能体决定调用工具。
- 如果模型响应不是工具调用,则流程将导向 END,从而终止进程。

智能体在行动
示例1:简单计算
以下是一个示例,展示了智能体在 LangGraph 中使用工具进行简单使用的案例。
messages = [HumanMessage(content="Divide 6790 by 5")]
messages = react_graph.invoke({"messages": messages, "input_file": None})
# Show the messages
for m in messages['messages']:
m.pretty_print()
对话将继续进行:
Human: Divide 6790 by 5
AI Tool Call: divide(a=6790, b=5)
Tool Response: 1358.0
Alfred: The result of dividing 6790 by 5 is 1358.0.
示例2:分析韦恩大师的训练文档
当韦恩大师离开他的训练记录和饮食笔记时:
messages = [HumanMessage(content="According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu?")]
messages = react_graph.invoke({"messages": messages, "input_file": "Batman_training_and_meals.png"})
交互将继续进行:
Human: According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu?
AI Tool Call: extract_text(img_path="Batman_training_and_meals.png")
Tool Response: [Extracted text with training schedule and menu details]
Alfred: For the dinner menu, you should buy the following items:
1. Grass-fed local sirloin steak
2. Organic spinach
3. Piquillo peppers
4. Potatoes (for oven-baked golden herb potato)
5. Fish oil (2 grams)
Ensure the steak is grass-fed and the spinach and peppers are organic for the best quality meal.
关键要点
如果您希望创建自己的文档分析智能体,以下是需要考虑的关键点:
- 定义明确的工具 针对特定与文档相关的任务
- 创建一个健壮的状态跟踪器 维持工具调用之间的上下文
- 考虑错误处理 针对工具故障
- 保持上下文意识 之前的交互次数(由操作员确认)
add_messages)
遵循这些原则,您也能提供堪比韦恩庄园的典范文档分析服务。
我相信这个解释已经足够令人满意了。现在,如果你们不介意的话,韦恩大师的斗篷需要在今晚的活动之前进行处理。