Agent的本质:
- 大模型可以借助外部工具来实现一些特定的功能
- 流程:
- 准备外部工具(函数)列表 tools
- 准备大模型 model
- 创建一个 agent
- 调用 agent
- model 大模型
- 做决策大脑
- tools 一系列工具
- 做能力拓展(专长)
- create_react_agent
- 创建一个 agent
Agent 的手动创建:
- 借助 LangGraph 搭建工作流
- Graph
- 节点 Node:
- 执行一个动作,包括调用函数、调用模型等
- 边 Edge:
- 节点之间的连线,代表状态转移
- 固定边
- 条件边
- 节点 Node:
- 状态 State:
- 最常用的是 Message State
- 状态中存储着消息
基本 ReAct Agent 的实现
1. 从平台(如阿里云百炼)获取 api-key
2. 创建 .env 文件,配置 api-key
DASHSCOPE_API_KEY = your api-key
3. 创建 models.py 文件,配置模型
from dotenv import load_dotenv
load_dotenv()
from langchain_community.chat_models import ChatTongyi
def get_chat():
return ChatTongyi(model="qwen-turbo", temperature=0.1)
4. 创建 ReAct_Agent.ipynb 文件
(1)加载模型
from models import get_chat
model = get_chat()
(2)定义外部工具
from datetime import datetime
def get_current_datetime():
"""
查询当前的日期和时间
"""
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return current_time
(3)构建一个 agent
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(model=model, tools=[get_current_datetime])
(4) 调用 agent
results = agent.invoke(input={"messages":[("user","现在几点了?")]})
for msg in results["messages"]:
msg.pretty_print()
(5)运行结果
手动实现 react_agent
参考文档:https://langchain-ai.github.io/langgraph/#example
1. 引入依赖
# 类型 限制
from typing import Annotated, Literal, TypedDict
# 人类消息
from langchain_core.messages import HumanMessage
# 加载大模型
from models import get_chat
# 当做装饰器使用,把一个普通的函数变成一个agent可以调用的工具
from langchain_core.tools import tool
# 消息持久化
from langgraph.checkpoint.memory import MemorySaver
# 引入预定义的一些类或工具
from langgraph.graph import END, START, StateGraph, MessagesState
# 引入一个预编译的工具节点
from langgraph.prebuilt import ToolNode
# 引入一个 datetime
from datetime import datetime
2. 定义外部工具
# 给 agent 定义工具
# @tool 写不写都可以
@tool
def get_current_datetime() -> str:
"""
查询当前的日期和时间
"""
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
return formatted_date
@tool
def get_apple_price(model: str) -> int:
"""
查询苹果手机的价格!
入参:model 是苹果手机的型号,目前,只有如下3个型号 '4s'、'5s'、'6s',其它型号暂不支持
"""
if model == "4s":
return 4000
elif model == "5s":
return 5000
elif model == "6s":
return 6000
else:
raise ValueError("model 是苹果手机的型号,目前,只有如下3个型号 '4s'、'5s'、'6s',其它型号暂不支持")
创建工具节点
# 创建查询日期和时间的工具节点
call_datetime = ToolNode(tools=[get_current_datetime],name="datetime")
# 创建查询苹果手机的工具节点
call_apple_price = ToolNode(tools=[get_apple_price], name="apple_price")
连接大模型,绑定工具
# 连接大模型
model = get_chat()
# 绑定工具
model_with_tools = model.bind_tools(tools=[get_apple_price, get_current_datetime])
定义条件边
# 定义一个条件边,做转向判断,返回 Literal常量
def should_continue(state: MessagesState) -> Literal["datetime","apple_price", END]:
# 获取当前的消息
messages = state['messages']
# 取出最后一条消息
last_message = messages[-1]
# 如果大模型发出工具调用请求,我们就转向工具节点
# print(last_message)
if not last_message.tool_calls:
return END
elif last_message.tool_calls[0]["name"]=="get_current_datetime":
return "datetime"
else:
return "apple_price"
return END
定义调用模型的函数
def call_model(state: MessagesState):
# 取出消息列表(所有的历史对话)
messages = state['messages']
# 调用大模型
response = model_with_tools.invoke(messages)
# 只需要通过列表形式返回当前这一步的消息即可
# 系统会自动把当前这一步的消息追加到系统状态中
return {"messages":[response]}
添加节点和边
# 定义一个新的图
workflow = StateGraph(MessagesState)
# 添加一个大模型节点,每个node都要执行一个动作
workflow.add_node(node="model", action=call_model)
# 添加一个查询日期和时间的节点
workflow.add_node(node="datetime", action=call_datetime)
# 添加一个查询苹果手机价格的节点
workflow.add_node(node="apple_price", action=call_apple_price)
# 添加一条边
workflow.add_edge(start_key=START, end_key="model")
# 添加一个条件边,大模型判断完后有可能直接结束了
workflow.add_conditional_edges(source="model",path=should_continue)
# 工具调完,都转向大模型,工具和大模型之间是内部过程
workflow.add_edge(start_key="datetime", end_key="model")
workflow.add_edge(start_key="apple_price", end_key="model")
# 消息的持久化
checkpointer = MemorySaver()
# 编译整个图
agent = workflow.compile(checkpointer=checkpointer)
可视化图

调用 Agent

315

被折叠的 条评论
为什么被折叠?



