LangGraph更低级别、更细粒度管理Agent的状态和行为。适合大型复杂的Agent。langchain提供类似AgentExecutor这样的更高层次框架,适合快速开发和部署。
上图是LangGraph完整的图计算的模式,有开始,有结束,中间有很多节点,节点之间会有一定的关系。我们会有三个概念来实现LangGraph。
Graph:对象与关系表达,它的组成有
有关图的内容可以参考图论整理
HelloWorld
pip install langgraph
from langgraph.graph import StateGraph, END
from langchain_community.chat_models import ChatZhipuAI
from langchain_core.messages import BaseMessage, HumanMessage
from typing import TypedDict, Annotated, Sequence
import operator
import os
class AgentState(TypedDict):
'''
状态记录
'''
messages: Annotated[Sequence[BaseMessage], operator.add]
def _call_model(state):
'''
执行LLM操作
'''
response = chat.invoke(state['messages'])
return {'messages': [response]}
if __name__ == '__main__':
os.environ['ZHIPUAI_API_KEY'] = '******'
chat = ChatZhipuAI(model='glm-4', temperature=0.5)
workflow = StateGraph(AgentState)
workflow.add_node('model', _call_model)
workflow.set_entry_point('model')
workflow.add_edge('model', END)
app = workflow.compile()
res = app.invoke({'messages': [HumanMessage(content='你好')]})
print(res)
运行结果
{'messages': [HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='你好👋!我是人工智能助手智谱清言,可以叫我小智🤖,很高兴见到你,欢迎问我任何问题。', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 32, 'prompt_tokens': 6, 'total_tokens': 38}, 'model_name': 'glm-4', 'finish_reason': 'stop'}, id='run-b982480c-39d9-4445-8888-62a10339ef86-0')]}
状态持久化
许多AI的应用程序需要Memory来在多个交互中共享上下文。在LangGraph中,通过Checkpointers为任何StateGraph提供内存。
对于任何一个LangGraph工作流,如果你想设置持久化状态,只需要做两个设置