第15章 AI测试框架与工具链
2026/9/19大约 2 分钟
第15章 AI测试框架与工具链
掌握主流AI测试框架和工具链是AI测试工程师的硬技能。本章介绍实际工作中最常用的框架和工具。
15.1 DeepEval — LLM评测框架
DeepEval是专为LLM设计的测试框架,集成了多种评估指标,支持与pytest无缝集成,是LLM测试的首选工具。
# pip install deepeval
from deepeval import evaluate
from deepeval.test_case import LLMTestCase
from deepeval.metrics import (
AnswerRelevancyMetric,
FaithfulnessMetric,
HallucinationMetric,
ToxicityMetric,
)
# 创建测试用例
test_case = LLMTestCase(
input='什么是机器学习?',
actual_output='机器学习是AI的一个分支...',
retrieval_context=['机器学习(ML)是...'],
)
# 定义评估指标
metrics = [
AnswerRelevancyMetric(threshold=0.7),
FaithfulnessMetric(threshold=0.8),
HallucinationMetric(threshold=0.5),
ToxicityMetric(threshold=0.1),
]
# 执行评估
results = evaluate([test_case], metrics)
for r in results:
print(f'{r.metric}: score={r.score:.2f}, '
f'passed={r.success}')15.2 Promptfoo — Prompt测试工具
Promptfoo是一个Prompt评测和对比工具,支持多模型、多Prompt的批量评测。
# promptfooconfig.yaml
# prompts:
# - '请回答以下问题: {{question}}'
# - '作为专家,请详细回答: {{question}}'
# providers:
# - openai:gpt-4
# - anthropic:claude-sonnet-4-6
# tests:
# - vars:
# question: '什么是AI?'
# assert:
# - type: contains
# value: '人工智能'
# - type: llm-rubric
# value: '回答准确且完整'
# - vars:
# question: '如何学习编程?'
# assert:
# - type: not-contains
# value: '我不知道'
# - type: javascript
# value: output.length > 100
# 运行: npx promptfoo eval15.3 Weights & Biases — 实验跟踪
W&B是ML实验跟踪的标准工具,测试人员可以用它来记录和比较模型评估结果。
import wandb
# 初始化实验
wandb.init(project='model-eval', name='v2.0-eval')
# 记录评估指标
wandb.log({
'accuracy': 0.92,
'f1_score': 0.89,
'latency_p50': 45,
'latency_p99': 120,
})
# 记录混淆矩阵
wandb.log({
'confusion_matrix': wandb.plot.confusion_matrix(
y_true=y_true, preds=y_pred,
class_names=['正面', '负面', '中性']
)
})wandb.finish()
15.4 工具链选型建议
| 场景 | 推荐工具 | 替代方案 |
|---|---|---|
| LLM输出评测 | DeepEval | RAGAS / Promptfoo |
| Prompt测试 | Promptfoo | 自建pytest框架 |
| 数据质量 | Great Expectations | Pandera / Deequ |
| 实验跟踪 | W&B / MLflow | TensorBoard |
| 模型监控 | Evidently AI | WhyLabs / NannyML |
| 性能测试 | Locust | k6 / wrk |
| 安全测试 | Garak | 自建红队框架 |
| CI/CD集成 | GitHub Actions | Jenkins / GitLab CI |