Swarms Logo
GuidesEngineering

LLM-as-a-Judge: Build an Evaluation Pipeline With a Panel of Agents

How to grade LLM outputs automatically: write a rubric, score with one judge, then reduce judge bias with a panel of three judges from different model providers, majority voting, and self-consistency sampling for the close calls. Working Python code on the Swarms API.

Kye Gomez12 min read
LLM-as-a-Judge: Build an Evaluation Pipeline With a Panel of Agents

Every team shipping an LLM feature hits the same wall. You change a prompt or switch models, and you need to know whether the answers got better or worse. Reading a few hundred outputs by hand does not scale, and string-matching metrics miss what matters in free-form text.

LLM-as-a-judge is the standard answer: a model reads each output, compares it with a rubric, and returns a score. It is fast and cheap, and when the rubric is good it agrees with human raters often enough to be useful. It also has known failure modes. The MT-Bench paper that popularized the method documented three of them: position bias (preferring whichever answer comes first), verbosity bias (preferring longer answers) and self-enhancement bias (a model rating its own outputs higher).

This guide builds an evaluation pipeline that keeps the speed and reduces those biases. It starts with one judge, then moves to a panel of three judges from different providers with majority voting, and sends only the close calls to a self-consistency judge that samples several independent verdicts. Everything runs on the Swarms API with plain HTTP calls in Python.

Step 0: write the rubric first

A judge is only as good as its instructions. "Rate this answer from 1 to 10" produces scores that drift between runs and between models. A rubric with a small scale and a concrete description of each level produces scores you can compare.

Here is a rubric for a customer support assistant. Adapt the criteria to your product, but keep the shape: a few named criteria, a 1 to 5 scale with each level described, and a strict output format.

Python
RUBRIC = """You are grading a customer support answer.

Criteria:
1. Correctness: every factual claim agrees with the reference policy.
2. Completeness: the answer resolves the customer's actual question.
3. Tone: polite, direct, no filler.

Scale:
5 = correct, complete, ready to send as is
4 = correct and complete, minor wording issues
3 = mostly correct, but missing a detail the customer needs
2 = contains a factual error or misses the main question
1 = wrong, harmful or off topic

Judge the answer against the reference policy only. Length is not a quality signal.
Return only JSON: {"score": <1-5>, "verdict": "pass" | "fail", "reason": "<one sentence>"}.
A score of 4 or 5 is a pass."""

Two lines in there target known biases directly: "Length is not a quality signal" counters verbosity bias, and "Judge against the reference policy only" keeps the judge from grading against its own opinion of what the answer should be.

Step 1: one judge

A single judge is one call to POST /v1/agent/completions with the rubric as the system prompt and the item to grade as the task. Temperature 0 keeps it as repeatable as the model allows.

Python
import json
import os
import re
import requests

BASE = "https://api.swarms.world"
HEADERS = {"x-api-key": os.environ["SWARMS_API_KEY"], "Content-Type": "application/json"}


def parse_json(text: str) -> dict:
    """Pull the first JSON object out of a model reply."""
    match = re.search(r"\{.*\}", text, re.S)
    return json.loads(match.group(0)) if match else {}


def item_text(item: dict) -> str:
    return (
        f"Reference policy:\n{item['policy']}\n\n"
        f"Customer question:\n{item['question']}\n\n"
        f"Answer to grade:\n{item['answer']}"
    )


def judge_once(item: dict, model: str = "gpt-5.4") -> dict:
    payload = {
        "agent_config": {
            "agent_name": "Judge",
            "system_prompt": RUBRIC,
            "model_name": model,
            "max_loops": 1,
            "max_tokens": 400,
            "temperature": 0,
        },
        "task": item_text(item),
    }
    resp = requests.post(f"{BASE}/v1/agent/completions", headers=HEADERS, json=payload, timeout=120)
    resp.raise_for_status()
    outputs = resp.json()["outputs"]
    reply = [o for o in outputs if str(o.get("role", "")).lower() not in ("user", "system")][-1]["content"]
    return parse_json(str(reply))


item = {
    "policy": "Refunds are available within 30 days of purchase. After 30 days we offer store credit.",
    "question": "I bought this 41 days ago. Can I get my money back?",
    "answer": "Yes! We're happy to refund you in full, just reply with your order number.",
}
print(judge_once(item))
# {"score": 1, "verdict": "fail", "reason": "Promises a refund after 30 days, which the policy does not allow."}

This is already a working evaluator. Run it over a few hundred items and you have a pass rate you can track across prompt versions. The weakness is that every score comes from one model with one set of biases, including a preference for outputs that sound like its own.

Step 2: a panel of judges from different providers

The fix human evaluation uses is more than one rater. For LLM judges, the important part is that the raters come from different model families, so one provider's blind spots and self-preference do not decide the result.

The Swarms API runs several agents on the same input in one request with swarm_type: "ConcurrentWorkflow" on POST /v1/swarm/completions. Each agent sets its own model_name, so the panel can mix providers:

Python
from statistics import median

PANEL = [
    ("Judge GPT", "gpt-5.4"),
    ("Judge Claude", "claude-sonnet-5"),
    ("Judge Gemini", "gemini-3.5-flash"),
]


def judge_panel(item: dict) -> dict:
    payload = {
        "name": "Eval Panel",
        "description": "Three independent judges grade one answer",
        "swarm_type": "ConcurrentWorkflow",
        "task": item_text(item),
        "agents": [
            {
                "agent_name": name,
                "system_prompt": RUBRIC,
                "model_name": model,
                "max_loops": 1,
                "max_tokens": 400,
                "temperature": 0,
            }
            for name, model in PANEL
        ],
    }
    resp = requests.post(f"{BASE}/v1/swarm/completions", headers=HEADERS, json=payload, timeout=300)
    resp.raise_for_status()
    data = resp.json()

    names = {name for name, _ in PANEL}
    votes = {m["role"]: parse_json(str(m["content"])) for m in data["output"] if m.get("role") in names}
    scores = [v["score"] for v in votes.values() if "score" in v]
    passes = sum(1 for v in votes.values() if v.get("verdict") == "pass")

    return {
        "score": median(scores) if scores else None,
        "verdict": "pass" if passes >= 2 else "fail",
        "agreement": max(passes, len(votes) - passes) / max(len(votes), 1),
        "spread": (max(scores) - min(scores)) if scores else None,
        "votes": votes,
        "cost": data["usage"]["total_cost"],
    }

The aggregation is deliberately done in your code instead of by another model: the median score ignores one outlier judge, the verdict is a simple majority of three, and you keep every individual vote for debugging. Two numbers tell you how much to trust each result:

  • agreement is 1.0 when all three judges agree on pass or fail and about 0.67 on a 2 to 1 split.
  • spread is the gap between the highest and lowest score. A spread of 3 or more means the judges read the answer very differently, which usually means the rubric is ambiguous for that case.

If you would rather have the API run the deliberation, the same endpoint offers MajorityVoting, where a consensus agent reads all the answers, and CouncilAsAJudge, which evaluates a response along several dimensions with a separate judge per dimension. Multi-Agent Collaboration Patterns compares them. For a scoring pipeline you want to audit, doing the arithmetic yourself keeps it transparent.

Step 3: self-consistency for the close calls

Most items are easy: all three judges agree. The interesting ones are split decisions. For those, a second opinion from a judge that samples several independent verdicts and aggregates them is more reliable than any single call, because one unlucky sample no longer decides the outcome.

That is what the self-consistency type on POST /v1/reasoning-agent/completions does. It runs the same judge num_samples times in parallel and an aggregator returns the answer the samples converge on:

Python
def judge_self_consistent(item: dict, samples: int = 5) -> dict:
    payload = {
        "agent_name": "Tiebreak Judge",
        "description": "Resolves split panel decisions",
        "system_prompt": RUBRIC,
        "model_name": "claude-sonnet-5",
        "swarm_type": "self-consistency",
        "num_samples": samples,
        "max_loops": 1,
        "task": item_text(item),
    }
    resp = requests.post(f"{BASE}/v1/reasoning-agent/completions", headers=HEADERS, json=payload, timeout=300)
    resp.raise_for_status()
    outputs = resp.json()["outputs"]
    # The final entry holds the aggregated answer; a plain string is returned as is.
    final = outputs[-1]["content"] if isinstance(outputs, list) else outputs
    return parse_json(str(final))

The reasoning-agent endpoint is part of the Pro and Premium plans. The same endpoint also offers AgentJudge for a single structured evaluation and ReflexionAgent, which critiques and revises its own answer over several loops.

Step 4: the full pipeline

Put the pieces together: the panel grades everything, and only split decisions go to the tiebreaker. When the panel agrees on most items, the expensive call only runs on the few it splits on.

Python
import csv


def evaluate(items: list[dict], out_path: str = "eval_report.csv") -> None:
    rows, total_cost = [], 0.0
    for i, item in enumerate(items):
        result = judge_panel(item)
        total_cost += result["cost"]
        final = result["verdict"]
        escalated = result["agreement"] < 1.0 or (result["spread"] or 0) >= 2
        if escalated:
            final = judge_self_consistent(item).get("verdict", final)
        rows.append({
            "id": item.get("id", i),
            "median_score": result["score"],
            "panel_verdict": result["verdict"],
            "final_verdict": final,
            "agreement": round(result["agreement"], 2),
            "escalated": escalated,
            "reasons": " | ".join(f"{k}: {v.get('reason', '')}" for k, v in result["votes"].items()),
        })

    with open(out_path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)

    pass_rate = sum(r["final_verdict"] == "pass" for r in rows) / len(rows)
    print(f"{len(rows)} items, pass rate {pass_rate:.1%}, panel cost ${total_cost:.4f}")
    print(f"{sum(r['escalated'] for r in rows)} escalated to the tiebreak judge")

The CSV keeps every judge's one-sentence reason, so when the pass rate moves you can read why instead of guessing.

For large datasets, the loop is the slow part. On the Pro plan, POST /v1/swarm/batch/completions takes a list of swarm configurations and runs them concurrently in one request, so you can send the panel for many items at once.

Pairwise comparisons: A versus B

When you are choosing between two prompts or two models, a pairwise judgment ("which answer is better?") is often more sensitive than two separate scores. It is also where position bias is strongest. The standard fix is to ask twice with the order swapped and only count a win if it holds both ways:

Python
PAIRWISE = """You compare two answers to the same customer question against the reference policy.
Return only JSON: {"winner": "A" | "B" | "tie", "reason": "<one sentence>"}."""


def compare(policy: str, question: str, ans_1: str, ans_2: str, model: str = "gpt-5.4") -> str:
    def ask(a: str, b: str) -> str:
        payload = {
            "agent_config": {"agent_name": "Pairwise Judge", "system_prompt": PAIRWISE,
                             "model_name": model, "max_loops": 1, "max_tokens": 300, "temperature": 0},
            "task": f"Policy:\n{policy}\n\nQuestion:\n{question}\n\nAnswer A:\n{a}\n\nAnswer B:\n{b}",
        }
        r = requests.post(f"{BASE}/v1/agent/completions", headers=HEADERS, json=payload, timeout=120)
        r.raise_for_status()
        out = [o for o in r.json()["outputs"] if str(o.get("role", "")).lower() not in ("user", "system")]
        return parse_json(str(out[-1]["content"])).get("winner", "tie")

    first, second = ask(ans_1, ans_2), ask(ans_2, ans_1)
    if first == "A" and second == "B":
        return "answer 1"
    if first == "B" and second == "A":
        return "answer 2"
    return "tie"  # the preference flipped with the order, so it was position bias

Calibrate against your own labels

Before you trust the pipeline on a release decision, check it against people. Label 50 items yourself as pass or fail, run them through evaluate, and measure how often the final verdict matches your label. If agreement is low, read the disagreements: the cause is almost always a rubric line that two reasonable readers interpret differently. Tighten the wording, rerun, and keep those 50 items as a regression set that every rubric change must pass.

What it costs

Every response includes a usage block with the exact total_cost of that call, and the pipeline adds them up. A panel run is three short agent calls plus $0.01 per agent on the swarm endpoint, so most of the cost is tokens: the length of your policy, question and answer times three. Using a small model for one of the three judges, or a cheaper model for the bulk of the panel and a strong model only on the tiebreaker, cuts the bill without changing the design. GET /v1/models/pricing returns each model's price per million tokens.

Get started

Create an API key at cloud.swarms.world, paste the rubric and judge_panel into a script, and run it on ten examples from your logs. Single judges and panels work on every plan; the reasoning-agent tiebreaker and batch endpoints come with Pro or Premium. The Swarms API docs list every swarm type, and How to Compare GPT, Claude and Gemini on Your Own Prompts uses this judge to pick a model.

More from the blog

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure
Engineering

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure

The complete technical changelog for Swarms v18, code-named Collective. SelfOrganizingSwarm runs a leaderless team that coordinates by message, MessageBoard gives agents a forum they work through tools, A2AServer and A2AClient put any agent on the A2A protocol, Agent.arun runs natively on the event loop, output_schema returns a validated Pydantic object, every multi-agent structure reports its token usage, seven structures force the tool call they depend on, images actually reach the model, telemetry is off by default, and importing swarms and building the first Agent takes half the time. Every new feature, improvement, bug fix and removal from November 2 to December 1, 2026, day by day.

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call
Guides

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Run AI agents on a schedule or in response to webhooks from Vercel Cron, AWS Lambda or Cloudflare Workers, with no Python runtime, worker process or queue to maintain. Each agent run is one HTTPS request to the Swarms API. TypeScript code for all three platforms.

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API
Guides

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API

OpenAI sunset the Assistants API on August 26, 2026. This guide maps assistants, threads, runs, function tools and file search to the Swarms API, with before-and-after Python code, a thread store you own, MCP in place of function calling, and a one-line route for code that already uses the OpenAI SDK.