使用langgraph构建agent
·
rag系列文章目录
前言
LangGraph 是 LangChain 的一个分支或扩展,专注于构建和运行基于图的、有状态的、多参与者的工作流。它通过将复杂的任务分解为多个节点(步骤),并通过边(依赖关系)连接这些节点,来实现更灵活和强大的任务编排。
一、核心概念
LangGraph 的核心思想是将任务建模为 有向图,其中:
节点(Node):表示一个具体的任务或操作(如调用 LLM、执行函数、访问数据库等)。
边(Edge):表示节点之间的依赖关系或执行顺序。
状态(State):在整个图执行过程中,状态可以在节点之间传递和共享。
二、使用优点
(1)灵活的任务编排
LangGraph 允许你将复杂的任务分解为多个步骤,并通过图的形式定义它们的执行顺序和依赖关系。这种方式比传统的线性任务编排更灵活,适合处理复杂的业务逻辑。
(2)有状态的工作流
LangGraph 支持 有状态的工作流,即每个节点可以访问和修改全局状态。这使得在任务执行过程中可以动态调整行为。
(3)多参与者支持
LangGraph 支持多个参与者(如多个 LLM、外部 API、数据库等)协同工作。每个节点可以由不同的参与者执行,从而实现更复杂的任务。
(4)可视化与调试
通过将任务建模为图,LangGraph 可以更容易地可视化和调试工作流。你可以清晰地看到每个节点的输入、输出和执行顺序。
三、实践
- 定义tools
这里定义了两个工具tools,分别是查询天气的工具,还有一个网页搜索的工具,这两个tools一起构建一个langgraph的一个节点Node。
from langgraph.prebuilt import ToolNode
from langgraph.graph import StateGraph, MessagesState, START, END
import requests
from typing import Literal
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def get_weather(query: str) -> list:
"""Search weatherapi to get the current weather"""
# 需要补全access_key
endpoint = f"http://api.weatherstack.com/current?access_key=&query={query}"
response = requests.get(endpoint)
data = response.json()
if data.get("current"):
return data
else:
return "Weather Data Not Found"
@tool
def search_web(query: str) -> list:
"""Search the web for a query"""
tavily_search = TavilySearchResults(api_key="ss", max_results=2, search_depth='advanced', max_tokens=1000)
results = tavily_search.invoke(query)
return results
- 大模型
大模型是agent的大脑,这里将大模型构建为一个langgraph的一个节点Node。
# define a tool_node with the available tools
tools = [search_web, get_weather]
tool_node = ToolNode(tools)
llm = ChatOpenAI(base_url="https://aaa.tt/v1",
api_key="sk-sss",
model="gpt-4o-2024-05-13")
llm_with_tools = llm.bind_tools(tools)
# define functions to call the LLM or the tools
def call_model(state: MessagesState):
messages = state["messages"]
response = llm_with_tools.invoke(messages)
return {"messages": [response]}
def call_tools(state: MessagesState) -> Literal["tools", END]:
messages = state["messages"]
last_message = messages[-1]
if last_message.tool_calls:
return "tools"
return END
- 构建graph
首先构建一个langgraph的workflow,加入上面创建的两个Node。然后创建一个从START到LLM的边Edge,创建一个从Tools到LLM的边,这是因为工具调用的结果需要返回给大模型LLM。最后创建一个Conditional的边Edge,因为LLM可能需要调用工具,也可能直接END。

# initialize the workflow from StateGraph
workflow = StateGraph(MessagesState)
# add a node named LLM, with call_model function. This node uses an LLM to make decisions based on the input given
workflow.add_node("LLM", call_model)
# Our workflow starts with the LLM node
workflow.add_edge(START, "LLM")
# Add a tools node
workflow.add_node("tools", tool_node)
# Add a conditional edge from LLM to call_tools function. It can go tools node or end depending on the output of the LLM.
workflow.add_conditional_edges("LLM", call_tools)
# tools node sends the information back to the LLM
workflow.add_edge("tools", "LLM")
构建完成之后,就可以对workflow进行编译,然后执行workflow,逐步打印结果。结果如下:
if __name__ == '__main__':
agent = workflow.compile()
# display(Image(agent.get_graph().draw_mermaid_png()))
for chunk in agent.stream(
{"messages": [("user", "What is the temperature in New York today?")]},
stream_mode="values",):
chunk["messages"][-1].pretty_print()
执行输出如下:
================================ Human Message =================================
What is the temperature in New York today?
================================== Ai Message ==================================
Tool Calls:
get_weather (call_BP)
Call ID: call_BP
Args:
query: New York
================================= Tool Message =================================
Name: get_weather
{"request": {"type": "City", "query": "New York, United States of America", "language": "en", "unit": "m"}, "location": {"name": "New York", "country": "United States of America", "region": "New York", "lat": "40.714", "lon": "-74.006", "timezone_id": "America/New_York", "localtime": "2025-03-20 07:45", "localtime_epoch": 1742456700, "utc_offset": "-4.0"}, "current": {"observation_time": "11:45 AM", "temperature": 6, "weather_code": 143, "weather_icons": ["https://cdn.wmist.png"], "weather_descriptions": ["Mist"], "astro": {"sunrise": "06:59 AM", "sunset": "07:09 PM", "moonrise": "12:48 AM", "moonset": "09:44 AM", "moon_phase": "Waning Gibbous", "moon_illumination": 73}, "air_quality": {"co": "358.9", "no2": "49.21", "o3": "47", "so2": "7.77", "pm2_5": "12.025", "pm10": "13.69", "us-epa-index": "1", "gb-defra-index": "1"}, "wind_speed": 15, "wind_degree": 142, "wind_dir": "SE", "pressure": 1014, "precip": 0, "humidity": 89, "cloudcover": 100, "feelslike": 3, "uv_index": 0, "visibility": 6, "is_day": "yes"}}
================================== Ai Message ==================================
The current temperature in New York is 6°C. The weather is described as misty.
总结
目前大模型agent特别火,agent框架也特别多,比如langchain、openai agent、autoGen等等,从这些不同的框架中,可以学习它们的构建思路,来完善自己的agent。
更多推荐



所有评论(0)