构建并评测用于获取金属价格的 ReAct Agent
AI agents 在金融、电商和客户支持等领域正变得越来越有价值。这些 agents 可以自主与 API 交互、检索实时数据,并执行与用户目标一致的任务。评测这些 agents 对于确保它们有效、准确并能响应不同输入至关重要。
在本教程中,我们将:
- 构建一个 ReAct agent 来获取金属价格。
- 搭建评测流水线以跟踪关键表现指标。
- 用不同查询运行并评估 agent 的有效性。
点击 链接 在 Google Colab 中打开 notebook。
前置条件
- Python 3.8+
- 对 LangGraph、LangChain 和 LLMs 有基本了解
安装 Ragas 和其他依赖
用 pip 安装 Ragas 和 LangGraph:
%pip install langgraph==0.2.44
%pip install ragas
%pip install nltk
构建 ReAct Agent
初始化外部组件
首先,设置外部组件有两种选择:
- 使用实时 API Key:
- 在 metals.dev 注册账号以获取 API key。
- 模拟 API 响应:
- 或者,你可以使用预定义的 JSON 对象来模拟 API 响应。这样你可以更快开始,无需实时 API key。
选择最适合你需求的方法继续设置。
用于模拟 API 响应的预定义 JSON 对象
如果你想快速开始而不创建账号,可以跳过设置过程,使用下面给出的预定义 JSON 对象来模拟 API 响应。
metal_price = {
"gold": 88.1553,
"silver": 1.0523,
"platinum": 32.169,
"palladium": 35.8252,
"lbma_gold_am": 88.3294,
"lbma_gold_pm": 88.2313,
"lbma_silver": 1.0545,
"lbma_platinum_am": 31.99,
"lbma_platinum_pm": 32.2793,
"lbma_palladium_am": 36.0088,
"lbma_palladium_pm": 36.2017,
"mcx_gold": 93.2689,
"mcx_gold_am": 94.281,
"mcx_gold_pm": 94.1764,
"mcx_silver": 1.125,
"mcx_silver_am": 1.1501,
"mcx_silver_pm": 1.1483,
"ibja_gold": 93.2713,
"copper": 0.0098,
"aluminum": 0.0026,
"lead": 0.0021,
"nickel": 0.0159,
"zinc": 0.0031,
"lme_copper": 0.0096,
"lme_aluminum": 0.0026,
"lme_lead": 0.002,
"lme_nickel": 0.0158,
"lme_zinc": 0.0031,
}
定义 get_metal_price 工具
get_metal_price 工具将被 agent 用来获取指定金属的价格。我们将使用 LangChain 的 @tool decorator 创建该工具。
如果你想使用来自 metals.dev API 的实时数据,可以修改该函数以向 API 发出实时请求。
from langchain_core.tools import tool
# Define the tools for the agent to use
@tool
def get_metal_price(metal_name: str) -> float:
"""Fetches the current per gram price of the specified metal.
Args:
metal_name : The name of the metal (e.g., 'gold', 'silver', 'platinum').
Returns:
float: The current price of the metal in dollars per gram.
Raises:
KeyError: If the specified metal is not found in the data source.
"""
try:
metal_name = metal_name.lower().strip()
if metal_name not in metal_price:
raise KeyError(
f"Metal '{metal_name}' not found. Available metals: {', '.join(metal_price['metals'].keys())}"
)
return metal_price[metal_name]
except Exception as e:
raise Exception(f"Error fetching metal price: {str(e)}")
把工具绑定到 LLM
定义了 get_metal_price 工具后,下一步是把它绑定到 ChatOpenAI 模型。这使 agent 能在执行过程中根据用户请求调用该工具,从而与外部数据交互并执行超出其原生能力的操作。
from langchain_openai import ChatOpenAI
tools = [get_metal_price]
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools(tools)
在 LangGraph 中,state 在图执行时跟踪和更新信息方面起着关键作用。随着图的不同部分运行,state 会演变以反映变化,并包含在节点之间传递的信息。
例如,在这样的对话系统中,state 用于跟踪交换的消息。每次生成新消息时,它都会被添加到 state 中,更新后的 state 在节点间传递,确保对话按逻辑推进。
定义 State
要在 LangGraph 中实现这一点,我们定义一个维护消息列表的 state 类。每当产生新消息时,它会被追加到该列表,确保对话历史持续更新。
from langgraph.graph import END
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages
from typing import Annotated
from typing_extensions import TypedDict
class GraphState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
定义 should_continue 函数
should_continue 函数决定对话是继续进行进一步的工具交互还是结束。具体来说,它检查最后一条消息是否包含任何 tool calls(例如请求金属价格)。
- 如果最后一条消息包含 tool calls,表明 agent 已调用外部工具,对话继续并转到 "tools" 节点。
- 如果没有 tool calls,对话结束,由 END state 表示。
# Define the function that determines whether to continue or not
def should_continue(state: GraphState):
messages = state["messages"]
last_message = messages[-1]
if last_message.tool_calls:
return "tools"
return END
调用模型
call_model 函数与语言模型(LLM)交互,基于当前对话 state 生成响应。它把更新后的 state 作为输入,进行处理并返回模型生成的响应。
# Define the function that calls the model
def call_model(state: GraphState):
messages = state["messages"]
response = llm_with_tools.invoke(messages)
return {"messages": [response]}
创建 Assistant 节点
assistant 节点是负责处理当前对话 state、并用语言模型(LLM)生成相关响应的关键组件。它评估 state,确定合适的行动方案,并调用 LLM 生成与正在进行的对话一致的响应。
# Node
def assistant(state: GraphState):
response = llm_with_tools.invoke(state["messages"])
return {"messages": [response]}
创建 Tool 节点
tool_node 负责管理与外部工具的交互,例如获取金属价格或执行超出 LLM 原生能力的其他操作。工具本身在代码前面定义,tool_node 根据当前 state 和对话需求调用这些工具。
from langgraph.prebuilt import ToolNode
# Node
tools = [get_metal_price]
tool_node = ToolNode(tools)
构建图
图结构是 agentic 工作流的骨干,由相互连接的节点和边组成。要构建这张图,我们使用 StateGraph builder,它允许我们定义并连接各种节点。每个节点代表过程中的一步(例如 assistant 节点、tool 节点),边则规定这些步骤之间的执行流。
from langgraph.graph import START, StateGraph
from IPython.display import Image, display
# Define a new graph for the agent
builder = StateGraph(GraphState)
# Define the two nodes we will cycle between
builder.add_node("assistant", assistant)
builder.add_node("tools", tool_node)
# Set the entrypoint as `agent`
builder.add_edge(START, "assistant")
# Making a conditional edge
# should_continue will determine which node is called next.
builder.add_conditional_edges("assistant", should_continue, ["tools", END])
# Making a normal edge from `tools` to `agent`.
# The `agent` node will be called after the `tool`.
builder.add_edge("tools", "assistant")
# Compile and display the graph for a visual overview
react_graph = builder.compile()
display(Image(react_graph.get_graph(xray=True).draw_mermaid_png()))
为了测试设置,我们将用一个查询运行 agent。agent 将使用 metals.dev API 获取铜的价格。
from langchain_core.messages import HumanMessage
messages = [HumanMessage(content="What is the price of copper?")]
result = react_graph.invoke({"messages": messages})
result["messages"]
[HumanMessage(content='What is the price of copper?', id='4122f5d4-e298-49e8-a0e0-c98adda78c6c'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_DkVQBK4UMgiXrpguUS2qC4mA', 'function': {'arguments': '{"metal_name":"copper"}', 'name': 'get_metal_price'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 116, 'total_tokens': 134, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0ba0d124f1', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-0f77b156-e43e-4c1e-bd3a-307333eefb68-0', tool_calls=[{'name': 'get_metal_price', 'args': {'metal_name': 'copper'}, 'id': 'call_DkVQBK4UMgiXrpguUS2qC4mA', 'type': 'tool_call'}], usage_metadata={'input_tokens': 116, 'output_tokens': 18, 'total_tokens': 134}),
ToolMessage(content='0.0098', name='get_metal_price', id='422c089a-6b76-4e48-952f-8925c3700ae3', tool_call_id='call_DkVQBK4UMgiXrpguUS2qC4mA'),
AIMessage(content='The price of copper is $0.0098 per gram.', response_metadata={'token_usage': {'completion_tokens': 14, 'prompt_tokens': 148, 'total_tokens': 162, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0ba0d124f1', 'finish_reason': 'stop', 'logprobs': None}, id='run-67cbf98b-4fa6-431e-9ce4-58697a76c36e-0', usage_metadata={'input_tokens': 148, 'output_tokens': 14, 'total_tokens': 162})]
将 Messages 转换为 Ragas 评测格式
在当前实现中,GraphState 把人类用户、AI(LLM 的响应)以及任何外部工具(AI 使用的 API 或服务)之间交换的消息存储在一个列表中。每条消息都是 LangChain 格式的对象
# Implementation of Graph State
class GraphState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
agent 执行期间每次交换消息时,它都会被添加到 GraphState 的 messages 列表中。然而,Ragas 评测交互需要特定的消息格式。
Ragas 使用自己的格式评测 agent 交互。因此,如果你使用 LangGraph,需要把 LangChain 消息对象转换成 Ragas 消息对象。这让你可以用 Ragas 的内置评测工具评测 AI agents。
目标: 把 LangChain 消息列表(例如 HumanMessage、AIMessage 和 ToolMessage)转换成 Ragas 期望的格式,以便评测框架能正确理解并处理它们。
要把 LangChain 消息列表转换成适合 Ragas 评测的格式,Ragas 提供函数 convert_to_ragas_messages,可用于把 LangChain 消息转换成 Ragas 期望的格式。
用法如下:
from ragas.integrations.langgraph import convert_to_ragas_messages
# Assuming 'result["messages"]' contains the list of LangChain messages
ragas_trace = convert_to_ragas_messages(result["messages"])
ragas_trace # List of Ragas messages
[HumanMessage(content='What is the price of copper?', metadata=None, type='human'),
AIMessage(content='', metadata=None, type='ai', tool_calls=[ToolCall(name='get_metal_price', args={'metal_name': 'copper'})]),
ToolMessage(content='0.0098', metadata=None, type='tool'),
AIMessage(content='The price of copper is $0.0098 per gram.', metadata=None, type='ai', tool_calls=None)]
评测 Agent 的表现
在本教程中,让我们用以下指标评测 Agent:
- Tool call Accuracy:ToolCallAccuracy 是可用于评测 LLM 识别并调用完成给定任务所需工具的表现的指标。
- Agent Goal accuracy:Agent goal accuracy 是可用于评测 LLM 识别并达成用户目标的表现的指标。这是一个二值指标,1 表示 AI 已达成目标,0 表示 AI 未达成目标。
首先,让我们用几个查询实际运行 Agent,并确保我们有这些查询的 ground truth 标签。
Tool Call Accuracy
from ragas.metrics import ToolCallAccuracy
from ragas.dataset_schema import MultiTurnSample
from ragas.integrations.langgraph import convert_to_ragas_messages
import ragas.messages as r
ragas_trace = convert_to_ragas_messages(
messages=result["messages"]
) # List of Ragas messages converted using the Ragas function
sample = MultiTurnSample(
user_input=ragas_trace,
reference_tool_calls=[
r.ToolCall(name="get_metal_price", args={"metal_name": "copper"})
],
)
tool_accuracy_scorer = ToolCallAccuracy()
await tool_accuracy_scorer.multi_turn_ascore(sample)
1.0
Tool Call Accuracy: 1,因为 LLM 正确识别并使用了必要工具(get_metal_price),参数也正确(即金属名为 "copper")。
Agent Goal Accuracy
messages = [HumanMessage(content="What is the price of 10 grams of silver?")]
result = react_graph.invoke({"messages": messages})
result["messages"] # List of LangChain messages
[HumanMessage(content='What is the price of 10 grams of silver?', id='51a469de-5b7c-4d01-ab71-f8db64c8da49'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_rdplOo95CRwo3mZcPu4dmNxG', 'function': {'arguments': '{"metal_name":"silver"}', 'name': 'get_metal_price'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 120, 'total_tokens': 137, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0ba0d124f1', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-3bb60e27-1275-41f1-a46e-03f77984c9d8-0', tool_calls=[{'name': 'get_metal_price', 'args': {'metal_name': 'silver'}, 'id': 'call_rdplOo95CRwo3mZcPu4dmNxG', 'type': 'tool_call'}], usage_metadata={'input_tokens': 120, 'output_tokens': 17, 'total_tokens': 137}),
ToolMessage(content='1.0523', name='get_metal_price', id='0b5f9260-df26-4164-b042-6df2e869adfb', tool_call_id='call_rdplOo95CRwo3mZcPu4dmNxG'),
AIMessage(content='The current price of silver is approximately $1.0523 per gram. Therefore, the price of 10 grams of silver would be about $10.52.', response_metadata={'token_usage': {'completion_tokens': 34, 'prompt_tokens': 151, 'total_tokens': 185, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0ba0d124f1', 'finish_reason': 'stop', 'logprobs': None}, id='run-93e38f71-cc9d-41d6-812a-bfad9f9231b2-0', usage_metadata={'input_tokens': 151, 'output_tokens': 34, 'total_tokens': 185})]
from ragas.integrations.langgraph import convert_to_ragas_messages
ragas_trace = convert_to_ragas_messages(
result["messages"]
) # List of Ragas messages converted using the Ragas function
ragas_trace
[HumanMessage(content='What is the price of 10 grams of silver?', metadata=None, type='human'),
AIMessage(content='', metadata=None, type='ai', tool_calls=[ToolCall(name='get_metal_price', args={'metal_name': 'silver'})]),
ToolMessage(content='1.0523', metadata=None, type='tool'),
AIMessage(content='The current price of silver is approximately $1.0523 per gram. Therefore, the price of 10 grams of silver would be about $10.52.', metadata=None, type='ai', tool_calls=None)]
from ragas.dataset_schema import MultiTurnSample
from ragas.metrics import AgentGoalAccuracyWithReference
from ragas.llms import LangchainLLMWrapper
sample = MultiTurnSample(
user_input=ragas_trace,
reference="Price of 10 grams of silver",
)
scorer = AgentGoalAccuracyWithReference()
evaluator_llm = LangchainLLMWrapper(ChatOpenAI(model="gpt-4o-mini"))
scorer.llm = evaluator_llm
await scorer.multi_turn_ascore(sample)
1.0
Agent Goal Accuracy: 1,因为 LLM 正确达成了用户获取 10 克银价格的目标。
接下来
🎉 恭喜!我们已经学会如何使用 Ragas 评测框架评测 agent。