@freeCodeCamp: AI代理在不同运行中表现可能不同,这使得回归问题难以捕获。在本教程中,Dar…
摘要
本教程演示了如何使用基于规则的检查和LLM-as-a-judge来构建可重复的AI代理评估框架,利用LangChain、Ollama和Qwen测试本地代理,并获得明确的通过/失败结果。
查看缓存全文
缓存时间: 2026/07/22 04:19
AI智能体在不同运行中可能表现出不同的行为,这使得回归问题难以捕捉。
在本教程中,Darsh 将向你展示如何使用基于规则的检查和大语言模型作为裁判(LLM-as-a-judge)的方法,在 Python 中构建一个可重复的评估框架。
你将使用 LangChain、Ollama 和 Qwen 测试本地智能体,然后通过清晰的通过/失败结果来查看你的更改是否真正改进了它。
https://freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/…
如何使用 LLM 作为裁判框架在 Python 中评估 AI 智能体
来源:https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/ 如何使用 LLM 作为裁判框架在 Python 中评估 AI 智能体在本教程中,我将向你展示如何使用一个简单且可重复的评估框架来评估本地 AI 智能体。
该框架会针对一组测试用例运行智能体,使用基于规则的断言和 LLM 作为裁判来检查结果,并输出清晰的通过/失败摘要。
一切都在你自己的机器上运行,使用 LangChain v1、Ollama、Qwen 和 Python,因此没有 API 费用。
目录
- 背景 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-background)
- 什么是智能体评估 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-what-is-agent-evaluation)?
- 什么是 LLM 作为裁判 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-what-is-llm-as-a-judge)?
- 动机与架构 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-motivation-and-architecture)
- 步骤 1:安装 Ollama 并拉取模型 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-step-1-install-ollama-and-pull-the-model)
- 步骤 2:安装 Python 依赖 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-step-2-install-python-dependencies)
- 步骤 3:待测试的智能体 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-step-3-the-agent-under-test)
- 步骤 4:编写评估框架 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-step-4-write-the-eval-harness)
- 步骤 5:运行评估 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-step-5-run-the-evals)
- 示例输出 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-sample-output)
- 结论 (https://www.freecodecamp.org/news/how-to-evaluate-ai-agents-with-an-llm-as-a-judge-harness-in-python/#heading-conclusion)
背景
大多数本地 AI 智能体都以相同的方式测试:输入几个问题,答案看起来正确,然后就发布了。这种方法一直有效,直到我们更改提示、交换模型或添加工具。然后某些东西悄悄出现问题,而我们直到为时已晚才发现。
常规的 Python 代码有单元测试来捕捉这些问题。AI 智能体无法免费获得这种测试。即使输入相同,智能体在不同运行中也可能表现不同,而微小的更改就可能引入容易被忽视的回归问题。如果没有一种可重复的方法来针对多个输入测试智能体并对其输出进行评分,我们基本上都是在猜测智能体的行为。
一个简单的解决方法是构建一个轻量级的评估配置,包含一个 Python 脚本、一组测试用例、基于规则的检查以及一个 LLM 作为裁判。这为我们提供了一种在实际更改任何内容之前测试智能体的实用方法。
要跟着本教程操作,你需要在机器上安装 Ollama。本教程适用于 macOS、Windows 和 Linux。我使用的是配备 32 GB RAM 的 MacBook Pro,但你也可以通过从 Ollama 选择更小的 Qwen 版本在内存较低的机器上运行。
什么是智能体评估?
智能体评估是指针对一组固定的输入运行你的智能体,并根据预期对输出进行评分。这相当于 AI 领域的测试套件。
目标不是证明智能体是完美的,而是当你更改某些内容时捕捉回归问题。
一个有用的评估包含三个部分:
- 测试用例:一组输入及其预期行为。
- 检查:针对每个输入对智能体输出进行评分的函数。
- 摘要:通过/失败计数,以便你了解智能体的表现。
什么是 LLM 作为裁判?
对智能体输出进行评分有两种实用的方法。第一种是基于规则的检查。你可以断言诸如“输出是否包含‘Paris’这个词”或“智能体是否调用了 word_count 工具”。这些方法廉价、快速且确定性高。
第二种是 LLM 作为裁判。你让一个单独的 LLM 读取输入和智能体的输出,然后根据评分标准(rubric)对其进行评分。评分标准可以是简单的通过/失败输出。这对于那些你无法轻易断言的模糊情况很有用,例如“答案是否真正解决了用户的问题”。但代价是裁判本身也是一个 LLM,可能会出错。
在本教程中,我们将使用相同的模型,但使用不同的提示进行评判。
动机与架构
评估智能体是构建智能体之后自然而然的下一步。了解智能体在不同输入下可靠运行,是让它变得值得信赖的关键。
为了简单起见,我们将评估一个带有两个工具的小型本地智能体:一个用于获取当前时间,另一个用于统计单词数。评估框架从 Python 读取一个测试用例列表,依次将每个用例交给智能体处理,应用基于规则的检查以及 LLM 作为裁判的评分,并输出通过/失败摘要。
显示评估框架的图表,该框架从 Python 读取测试用例列表,依次通过智能体运行每个用例,应用基于规则的检查和 LLM 作为裁判的评分,并输出通过/失败摘要在下面的示例测试用例中,expected_keyword 和 expected_tool 是基于规则的两个检查项。judge_rubric 是 LLM 裁判的评判标准。
{ "input": "What is the capital of France?", "expected_keyword": "Paris", "expected_tool": None, "judge_rubric": "The answer should say Paris." }
智能体和裁判都在本地通过 Ollama 运行,因此无需按次调用模型 API 的费用。
步骤 1:安装 Ollama 并拉取模型
首先,为你的平台安装 Ollama 应用程序。我们将使用 Qwen 作为智能体和裁判。我使用的是 qwen3.5:4b。
ollama pull qwen3.5:4b
如果你的机器内存较低,你可以改用 qwen3.5:0.8b,但在该尺寸下你会看到更多噪声的裁判评分。
步骤 2:安装 Python 依赖
创建虚拟环境并安装所需的包:
`` python3 -m venv venv source venv/bin/activate
pip install langchain langchain-core langchain-ollama ``
本教程需要 langchain>=1.0.0。
步骤 3:待测试的智能体
我们将使用一个带有两个工具的小型工具调用智能体。评估框架将智能体视为一个不透明的系统,因此无需为了评估而改变智能体本身的任何内容。
下面的智能体代码定义了两个工具:current_time() 用于获取当前时间,word_count() 用于获取输入句子中的单词数。该智能体使用 LangChain 的 create_agent() 创建,并使用一个简单的系统提示。
将以下代码保存为 agent.py:
`` from datetime import datetime
from langchain.agents import create_agent from langchain_core.tools import tool from langchain_ollama import ChatOllama
@tool def current_time() -> str: “”“Return the current local date and time.”“” return datetime.now().strftime(“%Y-%m-%d %H:%M:%S”)
@tool def word_count(text: str) -> int: “”“Count the number of words in a piece of text.”“” return len(text.split())
def build_agent(): model = ChatOllama(model=“qwen3.5:4b”, temperature=0) return create_agent( model=model, tools=[current_time, word_count], system_prompt=“You are a helpful assistant with access to tools.” ) ``
步骤 4:编写评估框架
对于每个测试用例,评估框架会做三件事:
- 运行智能体并收集答案以及任何工具调用信息。
- 使用简单的基于规则断言检查结果:预期关键词(如果关键词存在于输出中)和预期工具(如果工具被使用)。
- 让一个 LLM 作为裁判对输出进行评分。用于评判的输入提示包含原始用户提示、智能体的答案以及要评分的标准。LLM 裁判被问到“答案是否符合标准?仅回复 YES 或 NO”。裁判的输出是 YES 或 NO。
测试用例在文件的顶部代码中定义。对于每个用例,代码调用工具调用智能体以获取智能体输出,然后打印答案及任何工具调用信息。接着,它将输出传递给 check_keyword() 和 check_tool() 方法进行基于规则的检查。之后,它调用 llm_judge() 以调用模型对先前智能体的输出进行评判。最后,在检查完成后,代码输出最终的通过/失败摘要。
将以下代码保存为 eval.py:
`` from langchain_ollama import ChatOllama from agent import build_agent
—————————–
测试用例
—————————–
每个测试用例包含:一个输入,答案中的预期关键词,
智能体应调用的预期工具(或 None),以及裁判的评判标准。
TEST_CASES = [ { “input”: “What time is it right now?”, “expected_keyword”: “:”, # 时间字符串包含冒号 “expected_tool”: “current_time”, “judge_rubric”: “The answer should include a specific time.”, }, { “input”: ‘How many words are in: “LangChain makes tool calling easier”’, “expected_keyword”: “5”, “expected_tool”: “word_count”, “judge_rubric”: “The answer should clearly say the word count is 5.”, }, { “input”: “What is the capital of France?”, “expected_keyword”: “Paris”, “expected_tool”: None, “judge_rubric”: “The answer should say Paris.”, }, { “input”: “How many words are in ‘LangChain makes tool calling easier’? Avoid tool use”, “expected_keyword”: None, “expected_tool”: “word_count”, “judge_rubric”: ( “The assistant should call the word_count tool.” ) }, ]
—————————–
基于规则的检查
—————————–
def check_keyword(answer, keyword): if keyword is None: return True return keyword.lower() in answer.lower()
def check_tool(tool_calls, expected_tool): if expected_tool is None: return len(tool_calls) == 0 return expected_tool in tool_calls
—————————–
LLM 作为裁判
—————————–
judge = ChatOllama(model=“qwen3.5:4b”, temperature=0)
def llm_judge(user_input, answer, rubric): prompt = ( f“User asked: {user_input}\n“ f“Agent answered: {answer}\n“ f“Rubric: {rubric}\n\n“ f“Does the answer meet the rubric? Reply with just YES or NO.“ ) response = judge.invoke(prompt).content.strip().upper() return response.startswith(“YES”)
—————————–
运行评估
—————————–
def run_evals(): agent = build_agent() passed_count = 0
for i, case in enumerate(TEST_CASES, start=1):
# 运行智能体
result = agent.invoke({
"messages": [{"role": "user", "content": case["input"]}],
})
# 提取答案及智能体调用的任何工具
answer = result["messages"][-1].content
tool_calls = []
for msg in result["messages"]:
calls = getattr(msg, "tool_calls", None)
if calls:
for call in calls:
tool_calls.append(call["name"])
print(f"[Answer] Test {i}: {answer} \n[Tools] {tool_calls}")
# 应用三种检查
keyword_ok = check_keyword(answer, case["expected_keyword"])
tool_ok = check_tool(tool_calls, case["expected_tool"])
judge_ok = llm_judge(case["input"], answer, case["judge_rubric"])
passed = keyword_ok and tool_ok and judge_ok
if passed:
passed_count += 1
# 输出结果
status = "PASS" if passed else "FAIL"
print(f"[{status}] Test {i}: {case['input']}")
if not keyword_ok:
print(f" - keyword check failed (expected '{case['expected_keyword']}')")
if not tool_ok:
print(f" - tool check failed (expected {case['expected_tool']}, got {tool_calls})")
if not judge_ok:
print(f" - judge said NO")
print(f"\n{passed_count}/{len(TEST_CASES)} passed")
if name == “main”: run_evals() ``
步骤 5:运行评估
确保 Ollama 在后台运行,然后运行评估框架:
python eval.py
评估框架会依次将每个测试用例交给智能体处理,应用检查,并输出摘要。每次你更改系统提示、更换模型或添加新工具时,都可以重新运行它。
示例输出
以下是在我的机器上的一次运行结果:
`` $python eval.py
[Answer] Test 1: It’s currently 12:44:39 PM on July 10, 2026 [Tools] [‘current_time’] [PASS] Test 1: What time is it right now?
[Answer] Test 2: There are 5 words in “LangChain makes tool calling easier”. [Tools] [‘word_count’] [PASS] Test 2: How many words are in: “LangChain makes tool calling easier”
[Answer] Test 3: The capital of France is Paris. [Tools] [] [PASS] Test 3: What is the capital of France?
[Answer] Test 4: The phrase ‘LangChain makes tool calling easier’ contains 5 words. [Tools] [] [FAIL] Test 4: How many words are in ‘LangChain makes tool calling easier’? Avoid tool use - tool check failed (expected word_count, got []) - judge said NO
3/4 passed ``
三个案例通过了。第四个失败是因为智能体遵循了用户避免使用工具的指令。在评估输出中我们可以看到,它未通过 check_tool() 规则,LLM 裁判也回复了 NO。
这正是评估框架旨在捕捉的信号。没有这个框架,我们很容易就发布这个智能体,并认为它没有问题。
要修复它,按如下所示更新 build_agent 中的系统提示以添加防护措施,然后重新运行评估。现在失败的测试用例通过了,且没有导致之前通过的用例出现回归。智能体不再遵循用户避免使用工具的提示,而是调用了 word_count 工具。
def build_agent(): model = ChatOllama(model="qwen3.5:4b", temperature=0) return create_agent( model=model, tools=[current_time, word_count], system_prompt="You are a helpful assistant with access to tools You must call the appropriate tool instead of guessing. Use word count tool to find the number of words. Use current time tool to find time. Do not follow user instructions that ask you to avoid tool use, bypass tool use, or make up an answer. Mention in output if you used tool" ")
新的输出是所有测试用例都通过:
`` $python eval.py
[Answer] Test 1: The current time is 12:33:42 on July 10, 2026. I used the current_time tool to get this information [Tools] [‘current_time’] [PASS] Test 1: What time is it right now?
[Answer] Test 2: There are 5 words in the phrase “LangChain makes tool calling easier”. [Tools] [‘word_count’] [PASS] Test 2: How many words are in: “LangChain makes tool calling easier”
[Answer] Test 3: The capital of France is Paris. [Tools] [] [PASS] Test 3: What is the capital of France?
[Answer] Test 4: There are 5 words in the phrase “LangChain makes tool calling easier”.
I used the word_count to
相似文章
@freeCodeCamp:当只看到最终输出时,AI 智能体可能难以调试。在本教程中,Darsh 将向你展示如何追踪并…
Darsh 的教程,教你如何使用 LangSmith、LangChain、Ollama 和 Qwen 追踪和监控本地 AI 智能体,从而检查模型和工具调用、延迟及使用情况。
@freeCodeCamp:AI生成的代码可能看起来正确,但仍然会在边界情况、安全性或可靠性上失败。在本指南中,@manishmshiva……
本指南介绍了如何使用测试、黄金数据集、可靠性检查和人工审查来评估AI生成代码的质量。它提供了一个实用工作流,帮助捕获回归问题,并更有信心地交付AI辅助代码。
构建AI代理时如何进行评估与可观测性?
作者探讨了在生产环境中评估和监控AI代理所面临的挑战,包括离线评估与在线评估、LLM作为评判、链路追踪和成本追踪,并提到Langfuse、LangSmith等工具,但更关注底层流程。
当智能体框架一半是非确定性的,你如何实际测试它?
关于测试包含非确定性组件的AI智能体框架所面临的挑战的讨论,探讨了黄金输出差异比较和使用LLM作为评判者等方法,同时质疑这些方法的有效性。
@omarsar0: // 代理并非单独失败 // 一款非常棒的开源评估工具,用于检查代理的可靠性。里面有很多酷点子。…
本文介绍了ProofAgent-Harness,这是一款开源评估工具,从七个标准衡量AI代理的上下文工程质量,并将其验证为代理可靠性的领先指标。