EN ▾
Get your key

ApiRankingRanking API for LLMs: Score and Sort Text Outputs

Ranking API for LLMs: Score and Sort Text Outputs

If you searched ranking api google, you may want a service that takes candidate items and puts them in order. Google Cloud has its own ranking API for that, and this page shows another route: using a text LLM API to score and sort candidates by criteria you define.

Last updated

Sorting arm lifting the brightest glowing card from a conveyor onto a podium, illustrating LLM ranking of candidates

Summary

  • An LLM can rank by custom criteria that a generic relevance model does not know.
  • Ask for scores in JSON mode, validate them in code and sort locally.
  • Ranking 20 candidates of 150 tokens each costs about $0.000645 per call here.
  • Use temperature 0 and a fixed seed to make results more repeatable.

This is not about how Google ranks websites. It is about ranking items inside your own application: search results, product descriptions, support answers, story drafts, replies to choose from. Two kinds of tool do that job.

A purpose-built reranker, such as the ranking API in Google Cloud's search products, takes a query and documents and returns relevance scores. It is trained for that single task. Check Google's current documentation and pricing if that is what you need.

An LLM used as a ranker is slower and less specialised, but you control the criteria in plain language. "Prefer replies that stay in character." "Rank by how well each draft matches a formal tone." "Put answers that cite a step-by-step fix first." A generic relevance model cannot do that, and a text LLM can.

Three ways to make an LLM rank

Pointwise: score each item

The model rates every candidate from 0 to 10, and you sort by score. It is simple, handles any list length through batching and gives you a number you can threshold.

Listwise: return the full order

You send all candidates and ask for an ordered list of IDs. It is cheapest in output tokens and can compare items directly, but long lists suffer from position bias and the model may drop or repeat IDs.

Pairwise: compare two at a time

The model picks the better of two items. It is the most reliable for close calls and the most expensive, since a full sort needs many comparisons. Use it for the top few after a pointwise pass.

A practical pipeline: pointwise scoring for the whole list, then pairwise tie-breaks for the top three.

A working pointwise ranker

This script sends numbered candidates, asks for JSON, validates it and sorts locally. It uses JSON mode via response_format, temperature 0 and a fixed seed.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.apiranking.cc/v1", api_key="YOUR_KEY")

def rank(criteria, candidates):
    listing = "\n".join(f"{i}: {text}" for i, text in enumerate(candidates))
    prompt = (
        f"Criteria: {criteria}\n\nCandidates:\n{listing}\n\n"
        "Score every candidate from 0 to 10 against the criteria. "
        'Return JSON only, in the form {"scores": [{"id": 0, "score": 7}]} '
        "with exactly one entry per candidate."
    )
    resp = client.chat.completions.create(
        model="uncensored",
        messages=[
            {"role": "system", "content": "You are a strict, consistent ranking judge."},
            {"role": "user", "content": prompt},
        ],
        response_format={"type": "json_object"},
        temperature=0,
        seed=42,
    )
    data = json.loads(resp.choices[0].message.content)
    scores = {int(s["id"]): float(s["score"]) for s in data["scores"]}
    missing = [i for i in range(len(candidates)) if i not in scores]
    if missing:
        raise ValueError(f"missing ids: {missing}")
    order = sorted(scores, key=scores.get, reverse=True)
    return [(candidates[i], scores[i]) for i in order]

results = rank(
    "Stays in character as a gruff innkeeper and answers in under 40 words",
    ["Welcome, traveller. Rooms are two silver.", "Hello. How may I assist you today?", "Rooms cost two silver. No fighting."],
)
for text, score in results:
    print(score, text)

JSON mode asks for valid JSON; it does not guarantee your schema. That is why the code checks for missing IDs. In production, catch ValueError and json.JSONDecodeError and retry once.

Prompt design that improves scores

A ranker is only as good as the criteria you give it. Four habits help:

  • One criterion per call. "Tone", "accuracy" and "length" in a single score blur together. Score them separately and combine in code.
  • A defined scale. Say what a 2, a 5 and a 9 look like. Without anchors, scores drift towards the middle.
  • Short IDs. Use 0, 1, 2 rather than long titles, so the model returns IDs that you can match exactly.
  • A forbidden-output rule. Tell the model to return JSON only. Then parse strictly and fail loudly.

For creative text, such as story drafts or in-character replies, put the character or style sheet in the system message and the candidates in the user message. That keeps the judging instructions stable across calls.

Keep rankings stable

  • Temperature 0 and a seed. These are passed through and cut run-to-run variation, though they cannot promise identical output.
  • Shuffle and average. For important decisions, rank the list in two or three random orders and average the scores to wash out position bias.
  • Write a rubric. "Score 9 to 10 if..., 5 to 8 if..., below 5 if..." gives the model anchors and makes scores comparable across calls.
  • Keep batches modest. Fifty candidates per call is a sensible size. For more, rank in chunks and merge the winners with a final pass.
  • Log disagreements. Save items where two runs differ by more than two points and review them by hand.

The context window is 100,000 tokens for prompt plus completion, so size is rarely the limit. Quality is.

A listwise variant with a tie-break

When you need only the order, ask for IDs from best to worst. It produces fewer output tokens than scoring each item. This version reuses the client from the earlier script:

def rank_listwise(criteria, candidates):
    listing = "\n".join(f"{i}: {text}" for i, text in enumerate(candidates))
    prompt = (
        f"Criteria: {criteria}\n\nCandidates:\n{listing}\n\n"
        'Return JSON only: {"order": [ids from best to worst]}. '
        "Include every id exactly once."
    )
    resp = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        temperature=0,
        seed=42,
    )
    order = json.loads(resp.choices[0].message.content)["order"]
    if sorted(order) == list(range(len(candidates))):
        return [candidates[i] for i in order]
    raise ValueError("model returned an invalid order")

Run it twice with the candidates in a different order. If the top item changes between runs, you have a close call, and a pairwise question ("Which of these two is better, A or B?") for just those two items settles it cheaply. The listwise call returns only a short list of IDs, so its output stays small.

What ranking costs

The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Take a ranking call with 20 candidates of about 150 tokens each plus 300 tokens of instructions:

  • Input: 20 x 150 + 300 = 3,300 tokens, 3,300 / 1M x $0.15 = $0.000495
  • Output: about 300 tokens of JSON, 300 / 1M x $0.50 = $0.00015
  • Total: $0.000645 per ranking

Ten thousand such rankings cost $6.45. A larger call with 100 candidates of 150 tokens and about 1,500 output tokens costs $0.002295 + $0.00075 = $0.003045.

The score object is short on purpose. Asking for explanations multiplies the output tokens, which are the more expensive side. Request reasons only for the items you will review. Failed or refused requests are not charged, and credit never expires. Top-ups start at $20 in USDT (TRC20) or USDC (Base). See the pricing page for bonuses.

When not to use an LLM ranker

If you have millions of documents and a latency budget in milliseconds, use a search engine with a real reranker. An LLM call is the wrong tool for the first pass. It fits the last mile: reordering the top 20 to 100 candidates by a rule you can only state in words. It is also a good way to build a labelled test set.

Also keep human oversight where a ranking affects people, and tell users when content is ranked by a model.

For broader guidance on running models in production, read the production checklist for uncensored LLMs. To try the code above, claim the $0.50 trial on the API key page, and use the docs for parameter details.

Before you trust the ranker, build a small golden set: 30 to 50 lists where a person has already put the items in the right order. Run your prompt on it and compare. If the top choice matches the human choice most of the time, ship it; if not, change the rubric before you change anything else. Repeat the check whenever you edit the prompt, so improvements are measured instead of assumed.

Common questions

Is there an official Google ranking API?

Google Cloud offers a ranking API within its search products for reranking documents by relevance. Check Google's documentation for current features and pricing.

Can an LLM API really rank items?

Yes, by scoring candidates against criteria you write and sorting the scores in your code. It suits custom rules and small candidate lists rather than massive first-stage search.

How do I get valid JSON back?

Set response_format to {"type": "json_object"} and describe the shape in the prompt. Validate the fields in code, since JSON mode does not guarantee your exact schema.

How much does it cost?

Ranking 20 candidates of about 150 tokens each takes about 3,300 input and 300 output tokens, which is $0.000645 at $0.15 and $0.50 per 1M tokens.

Generate your API key

Register, retrieve your key, and update your base URL. That is the entire configuration.

Get your key