LLM as a Judge Python: A Working Setup
Using a model to grade other model outputs takes about forty lines of Python. Here is a working judge for image prompts, with scoring, pairwise comparison, batching and the biases to watch.
Updated:

What a judge does and when it helps
An LLM judge is a second model call whose only job is to grade the output of a first one. If you want to try llm as a judge python style evaluation, the setup is the same as for any chat completion: you send the item to grade plus a rubric, and you get back a score you can aggregate. It is useful when the thing you measure has no exact answer, such as whether a generated image prompt is specific, coherent or on brief.
A judge does not replace human review. It gives you a cheap, repeatable first pass so you can compare two prompt templates over 300 cases instead of reading 300 outputs. You still spot-check, and you still calibrate against a few hand-labeled examples. Both are covered below.
The example here suits this site. You have a short brief ("a lighthouse in a storm, painterly") and a candidate prompt written for an image generator. The judge rates how well the prompt follows the brief and how concrete it is. Note that the judge reads text only. It never sees an image, so it grades the prompt, not the picture it would produce.
Connect the OpenAI SDK
Install the library with pip install openai, then create a client that targets this API. The only changes from a stock OpenAI setup are the base URL and the key. Get a key from the API key page; the one-click trial credit is enough to run everything in this article.
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredimagegenerator.com/v1",
api_key="YOUR_API_KEY",
)
check = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Reply with the single word: ready"}],
max_tokens=5,
)
print(check.choices[0].message.content)
If that prints a short reply, authentication and the model ID are right. The model ID is uncensored. A wrong key gives an authentication error, and a wrong base URL usually shows up as a connection or 404 error, so those two are the first things to check.
A single-answer scorer with a rubric
Good judges share three habits: a narrow rubric, a fixed output format, and low randomness. Narrow means two or three criteria, each defined in a sentence. A rubric that asks for "overall quality" gives vague scores. Fixed format means JSON mode, so your code does not parse prose. Low randomness means temperature=0, plus a seed so repeated runs match as closely as the backend allows.
import json
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredimagegenerator.com/v1",
api_key="YOUR_API_KEY",
)
RUBRIC = '''You grade image-generation prompts written from a brief.
Score each criterion from 1 (poor) to 5 (excellent):
- adherence: the prompt keeps every element named in the brief
- specificity: it names concrete subjects, lighting, framing and materials
- clarity: it reads as one coherent scene, with no contradictions
Return JSON only: {"adherence": int, "specificity": int, "clarity": int, "reason": "one sentence"}'''
def score(brief, candidate):
r = client.chat.completions.create(
model="uncensored",
temperature=0,
seed=11,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": RUBRIC},
{"role": "user", "content": "BRIEF:\n" + brief + "\n\nPROMPT:\n" + candidate},
],
)
return json.loads(r.choices[0].message.content)
print(score("a lighthouse in a storm, painterly",
"Lighthouse on a black cliff, storm waves breaking, thick oil brush strokes, cold teal light"))
Ask for the reason in the same object. It costs a few output tokens, and when a score looks wrong, the one-sentence reason tells you whether the rubric or the item is at fault. If you want the model to think before scoring, put the reason key first in the JSON so it is written before the numbers.
Even with JSON mode on, wrap json.loads in a try block in production code and count parse failures. A failure rate above a percent or two means your rubric or output spec needs tightening.
Pairwise comparison without position bias
Scores on a 1 to 5 scale drift. Asking "which of these two is better" is usually steadier, and it is the natural format for comparing two prompt templates. Judges tend to favor the answer shown first, so run every pair twice with the order swapped and only count a win when both orders agree.
import json
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredimagegenerator.com/v1",
api_key="YOUR_API_KEY",
)
PAIR_RULES = '''Compare two image prompts written for the same brief.
Pick the one that follows the brief more closely and is more concrete.
Return JSON only: {"winner": "A" or "B", "reason": "one sentence"}'''
def once(brief, a, b):
r = client.chat.completions.create(
model="uncensored",
temperature=0,
seed=11,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": PAIR_RULES},
{"role": "user", "content": "BRIEF:\n" + brief + "\n\nA:\n" + a + "\n\nB:\n" + b},
],
)
return json.loads(r.choices[0].message.content)["winner"]
def compare(brief, x, y):
first = once(brief, x, y)
second = once(brief, y, x)
if first == "A" and second == "B":
return "x"
if first == "B" and second == "A":
return "y"
return "tie"
When the two orders disagree, the judge is reacting to position rather than content, so the honest label is a tie. A high tie rate is information too: it often means the two templates are close, or that the rubric is too loose to separate them.
Run a batch within the rate limits
A full key allows 8 concurrent requests and 300 requests per minute, and a trial key allows 2 and 60. Use a thread pool no larger than your concurrency limit, and retry on HTTP 429. The error code concurrency means too many calls at once, rate_limited means too many per minute, and a Retry-After: 5 header marks temporary overload.
import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.uncensoredimagegenerator.com/v1",
api_key="YOUR_API_KEY",
)
def with_retry(fn, tries=5):
for attempt in range(tries):
try:
return fn()
except RateLimitError:
time.sleep(5 * (attempt + 1))
return None
def judge_one(item):
def call():
r = client.chat.completions.create(
model="uncensored",
temperature=0,
messages=[{"role": "user", "content": item["text"]}],
)
return r.choices[0].message.content
return with_retry(call)
items = [{"text": "Rate this prompt from 1 to 5: misty forest, fox, soft dawn light. Reply with the number only."}] * 16
workers = 2 # trial key; use up to 8 on a full key
with ThreadPoolExecutor(max_workers=workers) as pool:
results = list(pool.map(judge_one, items))
print(results)
Swap judge_one for your scorer or comparer. Save results to disk as you go, one JSON line per item, so a crash at item 400 does not cost you the first 399.
Biases to expect, and a calibration check
Research on model-graded evaluation has described several repeatable biases, and you can test for each of them yourself.
- Position bias. The first option wins more often than chance. The swap in the pairwise code handles it.
- Length bias. Longer answers look more thorough. Add a rubric line such as "do not reward length", and check whether your scores correlate with character count.
- Self-preference. A model can rate text in its own style higher. If you grade outputs from the same model that judges them, keep that in mind when you read small differences.
- Score clustering. Many judges hand out 4 for everything. Use pairwise mode, or anchor the scale with one example for each of 1, 3 and 5.
To calibrate, label 30 items by hand before running the judge. Compare your labels with the judge's. Count how often you agree on the better of two prompts. If agreement is low, change the rubric and rerun the same 30 rather than adding more data. Once agreement is acceptable, freeze the rubric and the seed, and record both next to your results so a later run is comparable.
A few habits keep a judge useful over time. Version your rubric in the same repository as the code, and write the rubric version into every results file. Log the raw judge reply next to the parsed score, so you can reread odd cases later. Sample about one in twenty judgments for a manual check each run; if you disagree with more than one or two of them, stop and fix the rubric before trusting the aggregate. When you change the prompt template under test, keep the briefs, the seed and the judge settings fixed, so the only thing that moves is the template.
It also helps to include a few deliberately bad candidates in every batch, such as a prompt that ignores half the brief or one that contradicts itself. A working judge should score them low every time. If it does not, the rubric is not doing its job, and you learn that before it distorts a real comparison.
Finally, decide in advance what a meaningful difference looks like. If template B beats template A in 58 of 100 decided pairs, that is a small edge that could easily be noise at this sample size. If it wins 80 of 100, you can act on it. Write the threshold down before the run, so the result does not tempt you to move it afterwards.
One more rule: never grade the same item you used to write the rubric. Keep a small held-out set that was not used for tuning.
What a judging run costs
Judge calls are short, so they are cheap. Say a pairwise call carries a rubric of 200 tokens, a brief of 60 and two prompts of 120 each, so about 500 input tokens, plus a 60-token JSON answer. With the swap you make two calls per pair. For 250 pairs that is 500 calls.
Input: 500 calls x 500 tokens = 250,000 tokens, and 0.25 x $0.15 = $0.0375. Output: 500 calls x 60 tokens = 30,000 tokens, and 0.03 x $0.50 = $0.015. The total is $0.0525, about five cents. A heavier single-answer scorer at 900 input and 120 output tokens over 500 items costs 450,000 x $0.15 / 1M = $0.0675 for input and 60,000 x $0.50 / 1M = $0.03 for output, so $0.0975.
That means you can afford to rerun a judge whenever you change a prompt template. Details on top-ups and the credit bonus are on the pricing page, and the docs list every request parameter used above.
More guides
Questions and answers
Can I use the model that writes the answers as the judge?
You can, and many people do. Expect some self-preference, so treat small score gaps with caution and calibrate against a few hand-labeled items.
Why set temperature to 0 for a judge?
Grading should be repeatable. Low temperature plus a fixed seed keeps repeated runs close to each other, which makes score changes easier to trust.
How many items do I need for a meaningful comparison?
A few hundred pairs separate clear differences, and 30 to 50 is enough for a quick sanity check. Close results need more items or a sharper rubric.
Does the judge look at the generated images?
No. This API is text only, so the judge grades prompts and descriptions. To judge pictures you would need a vision-capable model from elsewhere.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.