llm-evaluation について
自動指標、人手による評価、LLM審査、RAG、エージェント、リリーステストを扱うLLMアプリ評価スキルです。品質の測定や変更の比較、性能低下の検出に取り組むチーム向けです。
主な機能
- 01テキスト・分類・検索の自動指標
- 02人手評価の基準と評価者間一致度
- 03ルーブリック式・ペア式のLLM審査
- 04RAGとエージェントタスクの評価
- 05A/Bテスト、ベンチマーク、回帰検査
- 06CI/CD評価のガイダンス
活用シーン
- 01リリース前のモデルやプロンプト比較
- 02RAGの検索と回答品質の確認
- 03エージェントのタスク達成率とツール選択の測定
- 04CI/CDでの品質低下の検出
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ ckorhonen/ claude-skills --skill llm-evaluationインストール後、Claude Code で/llm-evaluationを入力して読み込まれたか確認します。
詳細
LLM 評価
自動評価指標から人間による評価、A/B テストまで、LLM アプリケーションの包括的な評価戦略を習得します。
このスキルを使用する場面
- LLM アプリケーションのパフォーマンスを体系的に測定する
- 異なるモデルやプロンプトを比較する
- デプロイ前にパフォーマンスの低下を検出する
- プロンプトの変更による改善を検証する
- 本番システムへの信頼性を高める
- ベースラインを確立し、経時的な進捗を追跡する
- 予期しないモデルの動作をデバッグする
- RAG パイプラインの品質を評価する(検索+生成)
- エージェントタスクの成功率を測定する
- 構造化出力のスキーマ準拠をテストする
主な評価タイプ
1. 自動評価指標
計算されたスコアを使用して、高速かつ再現可能で、拡張性の高い評価を行います。
テキスト生成:
- BLEU:N グラムの重複(翻訳)
- ROUGE:再現率重視(要約)
- METEOR:意味的類似度
- BERTScore:埋め込みベースの類似度
- Perplexity:言語モデルの信頼度
分類:
- Accuracy:正解率
- Precision/Recall/F1:クラスごとのパフォーマンス
- Confusion Matrix:誤りのパターン
- AUC-ROC:ランキング品質
検索(RAG):
- MRR:平均逆順位
- NDCG:正規化割引累積利得
- Precision@K:上位 K 件に含まれる適合項目の割合
- Recall@K:上位 K 件の網羅率
2. 人間による評価
自動化が難しい品質面を手動で評価します。
評価軸:
- Accuracy:事実の正確性
- Coherence:論理的な流れ
- Relevance:質問に答えているか
- Fluency:自然言語としての品質
- Safety:有害な内容がないこと
- Helpfulness:ユーザーにとって役立つこと
3. LLM-as-Judge
より強力な LLM を使用して、より弱いモデルの出力を評価します。2025/2026 年には、自由形式のタスクで主流のアプローチとなっています。
アプローチ:
- Pointwise:個々の応答を採点する(0〜10 のリッカート尺度)
- Pairwise:2 つの応答を比較する(MT-Bench、Chatbot Arena で採用)
- Reference-based:正解となる回答と比較する
- Reference-free:正解データなしで評価する(創造的なタスクや自由形式のタスクに適しています)
- Rubric-based:明示的な基準に照らして評価する(一貫性を高めるのに最適)
- Constitutional:一連の原則やルールに照らして確認する
主な課題:
- 位置バイアス:評価モデルは、最初に表示された応答を好む傾向があります
- 冗長性バイアス:品質に関係なく、長い応答ほど高く評価される傾向があります
- 自己選好バイアス:モデルが自らの出力を好むことがあります
- 軽減策:順序を入れ替えて平均する、構造化された評価基準を使う、第三者の評価モデルを使う
4. RAG 専用の評価(RAGAS)
検索拡張生成パイプラインには、RAGAS の評価指標を使用します。
from ragas import evaluate
from ragas.metrics import (
faithfulness, # Is answer grounded in retrieved context?
answer_relevancy, # Does answer address the question?
context_precision, # Is retrieved context relevant?
context_recall, # Is all necessary info retrieved?
)
from datasets import Dataset
# Prepare evaluation dataset
data = {
"question": ["What is the capital of France?"],
"answer": ["Paris is the capital of France."],
"contexts": [["Paris is a city in France. It is the capital."]],
"ground_truth": ["Paris"]
}
dataset = Dataset.from_dict(data)
result = evaluate(dataset, metrics=[faithfulness, answer_relevancy, context_precision, context_recall])
print(result)
RAGAS 評価指標の解釈:
- Faithfulness(0〜1):スコアが低い場合は、ハルシネーションが発生しています。事実性が重要なアプリケーションでは特に重要です。
- Answer Relevancy(0〜1):低い場合は、回答が話題から逸れているか、はぐらかしています。
- Context Precision(0〜1):低い場合は、検索で無関係なチャンクを取得しています。
- Context Recall(0〜1):低い場合は、検索で関連文書を取得できていません。
5. エージェントタスクの評価
複数ステップのタスクを実行するエージェント向けです。
class AgentTaskEvaluator:
"""Evaluate agentic task completion."""
def evaluate_task(self, task, agent_trajectory, expected_result):
return {
"task_success": self._check_task_success(agent_trajectory, expected_result),
"tool_use_accuracy": self._check_tool_selection(agent_trajectory),
"step_efficiency": self._measure_step_efficiency(agent_trajectory),
"hallucination_rate": self._check_for_hallucinations(agent_trajectory),
}
def _check_task_success(self, trajectory, expected):
# Did agent achieve the goal? (binary or partial credit)
final_state = trajectory[-1]["state"]
return compare_states(final_state, expected)
def _measure_step_efficiency(self, trajectory):
# How many extra steps did agent take? (vs. optimal path)
actual_steps = len(trajectory)
optimal_steps = self.get_optimal_path_length(trajectory[0]["task"])
return optimal_steps / actual_steps # 1.0 = optimal
def _check_tool_selection(self, trajectory):
# Did agent use correct tools in correct order?
correct_tools = sum(1 for step in trajectory if step["tool_correct"])
return correct_tools / len(trajectory)
主なエージェント評価指標:
- タスク完了率:完全に完了したタスクの割合
- ステップ効率:最適なステップ数/実際に実行したステップ数
- ツール選択精度:正しいツールを選択した回数/ツール呼び出しの総数
- エラー回復:エージェントはミスから回復できたか
- ハルシネーションによるツール呼び出し:架空のパラメーターを使って呼び出されたツール
クイックスタート
from llm_eval import EvaluationSuite, Metric
# Define evaluation suite
suite = EvaluationSuite([
Metric.accuracy(),
Metric.bleu(),
Metric.bertscore(),
Metric.custom(name="groundedness", fn=check_groundedness)
])
# Prepare test cases
test_cases = [
{
"input": "What is the capital of France?",
"expected": "Paris",
"context": "France is a country in Europe. Paris is its capital."
},
# ... more test cases
]
# Run evaluation
results = suite.evaluate(
model=your_model,
test_cases=test_cases
)
print(f"Overall Accuracy: {results.metrics['accuracy']}")
print(f"BLEU Score: {results.metrics['bleu']}")
自動評価指標の実装
BLEU スコア
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
def calculate_bleu(reference, hypothesis):
"""Calculate BLEU score between reference and hypothesis."""
smoothie = SmoothingFunction().method4
return sentence_bleu(
[reference.split()],
hypothesis.split(),
smoothing_function=smoothie
)
# Usage
bleu = calculate_bleu(
reference="The cat sat on the mat",
hypothesis="A cat is sitting on the mat"
)
ROUGE スコア
from rouge_score import rouge_scorer
def calculate_rouge(reference, hypothesis):
"""Calculate ROUGE scores."""
scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
scores = scorer.score(reference, hypothesis)
return {
'rouge1': scores['rouge1'].fmeasure,
'rouge2': scores['rouge2'].fmeasure,
'rougeL': scores['rougeL'].fmeasure
}
BERTScore
from bert_score import score
def calculate_bertscore(references, hypotheses):
"""Calculate BERTScore using pre-trained BERT."""
P, R, F1 = score(
hypotheses,
references,
lang='en',
model_type='microsoft/deberta-xlarge-mnli'
)
return {
'precision': P.mean().item(),
'recall': R.mean().item(),
'f1': F1.mean().item()
}
カスタム評価指標
def calculate_groundedness(response, context):
"""Check if response is grounded in provided context."""
# Use NLI model to check entailment
from transformers import pipeline
nli = pipeline("text-classification", model="microsoft/deberta-large-mnli")
result = nli(f"{context} [SEP] {response}")[0]
# Return confidence that response is entailed by context
return result['score'] if result['label'] == 'ENTAILMENT' else 0.0
def calculate_toxicity(text):
"""Measure toxicity in generated text."""
from detoxify import Detoxify
results = Detoxify('original').predict(text)
return max(results.values()) # Return highest toxicity score
def calculate_factuality(claim, knowledge_base):
"""Verify factual claims against knowledge base."""
# Implementation depends on your knowledge base
# Could use retrieval + NLI, or fact-checking API
pass
LLM-as-Judge のパターン
単一出力の評価(評価基準ベース)
from openai import OpenAI
import json
client = OpenAI()
def llm_judge_quality(response, question):
"""Use GPT-4.1 to judge response quality with structured output."""
prompt = f"""You are an impartial evaluator. Rate the following response on a scale of 1-10 for each criterion.
**Criteria:**
1. Accuracy (1=many factual errors, 10=completely correct)
2. Helpfulness (1=doesn't address question, 10=fully resolves question)
3. Clarity (1=confusing/unclear, 10=perfectly clear and well-structured)
**Question:** {question}
**Response:** {response}
Evaluate objectively. Provide ratings in JSON format:
{{
"accuracy": <1-10>,
"helpfulness": <1-10>,
"clarity": <1-10>,
"reasoning": "<2-3 sentence justification>",
"overall": <1-10>
}}
"""
result = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": prompt}],
temperature=0,
response_format={"type": "json_object"} # Structured output
)
return json.loads(result.choices[0].message.content)
### Pairwise Comparison (with position bias mitigation)
```python
def compare_responses(question, response_a, response_b):
"""Compare two responses using LLM judge with position bias mitigation."""
def _judge(q, r1, r2, label1, label2):
prompt = f"""Compare these two responses to the question. Which is better?
Question: {q}
Response {label1}: {r1}
Response {label2}: {r2}
Which response is better and why? Consider accuracy, helpfulness, and clarity.
Answer with JSON:
{{
"winner": "{label1}" or "{label2}" or "tie",
"reasoning": "<explanation>",
"confidence": <1-10>
}}
"""
result = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": prompt}],
temperature=0,
response_format={"type": "json_object"}
)
return json.loads(result.choices[0].message.content)
# Run twice with swapped order to detect position bias
result_ab = _judge(question, response_a, response_b, "A", "B")
result_ba = _judge(question, response_b, response_a, "B", "A") # swapped
# Normalize result_ba back to A/B labels
winner_ba_normalized = "A" if result_ba["winner"] == "B" else ("B" if result_ba["winner"] == "A" else "tie")
# Check for consistency
consistent = result_ab["winner"] == winner_ba_normalized
if not consistent:
final_winner = "tie" # Disagree = call it a tie
else:
final_winner = result_ab["winner"]
return {
"winner": final_winner,
"consistent": consistent,
"reasoning_ab": result_ab["reasoning"],
"reasoning_ba": result_ba["reasoning"],
}
人間による評価のフレームワーク
アノテーションガイドライン
class AnnotationTask:
"""Structure for human annotation task."""
def __init__(self, response, question, context=None):
self.response = response
self.question = question
self.context = context
def get_annotation_form(self):
return {
"question": self.question,
"context": self.context,
"response": self.response,
"ratings": {
"accuracy": {
"scale": "1-5",
"description": "Is the response factually correct?"
},
"relevance": {
"scale": "1-5",
"description": "Does it answer the question?"
},
"coherence": {
"scale": "1-5",
"description": "Is it logically consistent?"
}
},
"issues": {
"factual_error": False,
"hallucination": False,
"off_topic": False,
"unsafe_content": False
},
"feedback": ""
}
評価者間一致度
from sklearn.metrics import cohen_kappa_score
def calculate_agreement(rater1_scores, rater2_scores):
"""Calculate inter-rater agreement."""
kappa = cohen_kappa_score(rater1_scores, rater2_scores)
interpretation = {
kappa < 0: "Poor",
kappa < 0.2: "Slight",
kappa < 0.4: "Fair",
kappa < 0.6: "Moderate",
kappa < 0.8: "Substantial",
kappa <= 1.0: "Almost Perfect"
}
return {
"kappa": kappa,
"interpretation": interpretation[True]
}
A/B テスト
統計的検定のフレームワーク
from scipy import stats
import numpy as np
class ABTest:
def __init__(self, variant_a_name="A", variant_b_name="B"):
self.variant_a = {"name": variant_a_name, "scores": []}
self.variant_b = {"name": variant_b_name, "scores": []}
def add_result(self, variant, score):
"""Add evaluation result for a variant."""
if variant == "A":
self.variant_a["scores"].append(score)
else:
self.variant_b["scores"].append(score)
def analyze(self, alpha=0.05):
"""Perform statistical analysis."""
a_scores = self.variant_a["scores"]
b_scores = self.variant_b["scores"]
# T-test
t_stat, p_value = stats.ttest_ind(a_scores, b_scores)
# Effect size (Cohen's d)
pooled_std = np.sqrt((np.std(a_scores)**2 + np.std(b_scores)**2) / 2)
cohens_d = (np.mean(b_scores) - np.mean(a_scores)) / pooled_std
return {
"variant_a_mean": np.mean(a_scores),
"variant_b_mean": np.mean(b_scores),
"difference": np.mean(b_scores) - np.mean(a_scores),
"relative_improvement": (np.mean(b_scores) - np.mean(a_scores)) / np.mean(a_scores),
"p_value": p_value,
"statistically_significant": p_value < alpha,
"cohens_d": cohens_d,
"effect_size": self.interpret_cohens_d(cohens_d),
"winner": "B" if np.mean(b_scores) > np.mean(a_scores) else "A"
}
@staticmethod
def interpret_cohens_d(d):
"""Interpret Cohen's d effect size."""
abs_d = abs(d)
if abs_d < 0.2:
return "negligible"
elif abs_d < 0.5:
return "small"
elif abs_d < 0.8:
return "medium"
else:
return "large"
回帰テスト
回帰の検出
class RegressionDetector:
def __init__(self, baseline_results, threshold=0.05):
self.baseline = baseline_results
self.threshold = threshold
def check_for_regression(self, new_results):
"""Detect if new results show regression."""
regressions = []
for metric in self.baseline.keys():
baseline_score = self.baseline[metric]
new_score = new_results.get(metric)
if new_score is None:
continue
# Calculate relative change
relative_change = (new_score - baseline_score) / baseline_score
# Flag if significant decrease
if relative_change < -self.threshold:
regressions.append({
"metric": metric,
"baseline": baseline_score,
"current": new_score,
"change": relative_change
})
return {
"has_regression": len(regressions) > 0,
"regressions": regressions
}
ベンチマーク
ベンチマークの実行
class BenchmarkRunner:
def __init__(self, benchmark_dataset):
self.dataset = benchmark_dataset
def run_benchmark(self, model, metrics):
"""Run model on benchmark and calculate metrics."""
results = {metric.name: [] for metric in metrics}
for example in self.dataset:
# Generate prediction
prediction = model.predict(example["input"])
# Calculate each metric
for metric in metrics:
score = metric.calculate(
prediction=prediction,
reference=example["reference"],
context=example.get("context")
)
results[metric.name].append(score)
# Aggregate results
return {
metric: {
"mean": np.mean(scores),
"std": np.std(scores),
"min": min(scores),
"max": max(scores)
}
for metric, scores in results.items()
}
CI/CD との統合:コードとしての評価
CI/CD パイプラインで評価を自動的に実行します。
# .github/workflows/eval.yml
name: LLM Evaluation
on:
pull_request:
paths: ['prompts/**', 'src/llm/**']
jobs:
evaluate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run evaluation suite
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
pip install -r requirements-eval.txt
python scripts/run_evaluations.py --baseline main --compare HEAD
- name: Check for regression
run: |
python scripts/check_regression.py \
--threshold 0.05 \
--fail-on-regression
# scripts/run_evaluations.py
import argparse
import json
from pathlib import Path
def run_eval_suite(model_fn, test_cases, metrics):
"""Run complete evaluation suite and return results."""
results = []
for case in test_cases:
prediction = model_fn(case["input"])
scores = {m.name: m.calculate(prediction, case["reference"]) for m in metrics}
results.append({"case": case["id"], "scores": scores})
aggregated = {
metric: sum(r["scores"][metric] for r in results) / len(results)
for metric in results[0]["scores"]
}
return aggregated
def main():
# Load test cases
test_cases = json.loads(Path("evals/test_cases.json").read_text())
# Run evaluation
results = run_eval_suite(your_model, test_cases, your_metrics)
# Save results with git commit hash
import subprocess
commit = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
output = {"commit": commit, "metrics": results}
Path(f"eval_results/{commit[:8]}.json").write_text(json.dumps(output, indent=2))
print(json.dumps(results, indent=2))
if __name__ == "__main__":
main()
構造化出力の評価
構造化出力(JSON スキーマ、関数呼び出し)が必要なアプリケーションの場合:
from pydantic import BaseModel, ValidationError
class ExpectedOutput(BaseModel):
name: str
age: int
email: str
def evaluate_structured_output(model_response: str, expected: dict) -> dict:
"""Evaluate whether model output conforms to schema and matches expected values."""
# 1. Schema compliance
try:
parsed = ExpectedOutput.model_validate_json(model_response)
schema_valid = True
except ValidationError as e:
return {"schema_valid": False, "error": str(e), "field_accuracy": 0}
# 2. Field accuracy
expected_obj = ExpectedOutput(**expected)
fields = ExpectedOutput.model_fields.keys()
correct = sum(1 for f in fields if getattr(parsed, f) == getattr(expected_obj, f))
return {
"schema_valid": True,
"field_accuracy": correct / len(fields),
"fields_correct": correct,
"fields_total": len(fields),
}
ベストプラクティス
- 複数のメトリクス:全体像を包括的に把握するため、多様なメトリクスを使用します。単一のメトリクスだけでは全体を把握できません。
- 代表的なデータ:現実世界の多様な例に加え、敵対的な例でもテストします。
- ベースライン:常にベースラインの性能(以前のプロンプトのバージョンや、より性能の低いモデル)と比較します。
- 統計的な厳密性:適切な統計検定を使用します。n < 100 の場合はブートストラップ信頼区間を使用します。
- 継続的な評価:CI/CD パイプラインに統合し、プロンプトを変更するたびに評価します。
- 人による検証:LLM-as-judge の出力を人間の評価者と照らし合わせて、定期的に検証します。
- エラー分析:失敗を分類して、単に件数を数えるのではなく、体系的な弱点を見つけます。
- バージョン管理:評価用データセットと結果を git で追跡し、評価をコードとして扱います。
- 提示順序バイアスの軽減:ペアワイズ比較では A/B の順序を入れ替え、結果を平均します。
- 開発用セットとテスト用セットの分離:テストセットを使ってプロンプトを調整せず、未使用データを保持します。
よくある落とし穴
- 単一メトリクスへの固執:他のメトリクスを犠牲にして、1つのメトリクスだけを最適化すること
- サンプルサイズの不足:少なすぎる例から結論を導くこと(統計的検出力を得るには 50 件以上が必要です)
- データ汚染:学習データや、プロンプトの調整に使ったデータでテストすること
- ばらつきの無視:統計的不確実性を考慮せず、信頼区間を報告しないこと
- メトリクスの不適合:自由形式のタスクに BLEU/ROUGE を使用すること(最新の LLM では相関が低い指標です)
- 評価モデルのバイアス:LLM 評価者に体系的なバイアスがあるかどうかを確認しないこと
- ベンチマークの漏洩:一般的なベンチマークは学習データに含まれている可能性があるため、非公開の評価を優先します。
- レイテンシーとコストの無視:コストが3倍になるようなメトリクスの改善は、割に合わない場合があります。
コメント
Markdown 対応