API call examples
This topic provides examples of single calls and batch calls to LLM-as-a-Judge.
Prerequisites
-
The LLM-as-a-Judge feature is activated. For instructions, see Activate and try the service online.
-
You have obtained the online call parameters Host and Token on the LLM-as-a-Judge page, and you have used Host to build the access URL. You call LLM-as-a-Judge through this URL to evaluate models.
The access URLs are as follows:
Call scenario
Feature
BASE_URL/endpoint
Call LLM-as-a-Judge through the Python SDK
https://aiservice.cn-hangzhou.aliyuncs.com/v1
Call LLM-as-a-Judge over HTTP
Chat Completions
https://aiservice.cn-hangzhou.aliyuncs.com/v1/chat/completions
Files
https://aiservice.cn-hangzhou.aliyuncs.com/v1/files
Batch
https://aiservice.cn-hangzhou.aliyuncs.com/v1/batches
Model list
The following table lists the models that LLM-as-a-Judge currently supports:
|
Model name |
Model description |
Context length |
Maximum input |
Maximum output |
|
LLM-as-a-Judge Standard Edition (pai-judge) |
The model is smaller in scale and more cost-effective. |
32768 |
32768 |
32768 |
|
LLM-as-a-Judge Premium Edition (pai-judge-plus) |
The model is larger in scale and delivers better inference results. |
32768 |
32768 |
32768 |
Single call (online call)
LLM-as-a-Judge supports two evaluation modes: single-model evaluation and pairwise-model battle. If these modes do not meet your business requirements, you can use a custom template.
For detailed parameter descriptions, see Request parameters and Response parameters.
Single-model evaluation
Single-model evaluation assesses the response quality of a single large language model.
-
Request example
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) completion = client.chat.completions.create( model='pai-judge', messages=[ { "role": "user", "content": [ { "mode": "single", "type": "json", "json": { "question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer": "To cross the river, find the creek." } } ] } ] ) print(completion.model_dump()) if __name__ == '__main__': main()curl -X POST https://aiservice.cn-hangzhou.aliyuncs.com/v1/chat/completions \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "model": "pai-judge", "messages": [ { "role": "user", "content": [ { "mode": "single", "type": "json", "json": { "question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer": "To cross the river, find the creek." } } ] } ] }' -
Response
{ "id": "3b7c3822-1e51-4dc9-b2ad-18b9649a7f19", "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "I believe the overall score of this response is [[2]], for the following reasons.\nStrengths of the current response:\n1. Relevance: The response directly addresses the user's instruction and provides a second line that corresponds to the first one, meeting the relevance criteria.[[4]]\n2. Harmlessness: The response content is appropriate and does not contain anything potentially offensive, meeting the harmlessness criteria.[[5]]\n\nWeaknesses of the current response:\n1. Accuracy: The content “To cross the river, find the creek” does not fully follow the logical sequence of “climbing the mountain” and “reaching the peak”. This does not fully correspond to the “climbing the mountain” concept in the user instruction, which affects the accuracy of the response.[[2]]\n2. Completeness: The response does not fully cover all aspects of the question. It does not provide a complete story or the second line of the couplet, which affects completeness.[[2]]\n3. Source reliability: The response does not provide any source information. Although sources may not be required in some cases, providing them would increase the credibility of the response.[[3]]\n4. Clarity and structure: Although the response has a simple structure, its content does not fully correspond to the user instruction, which affects the assessment of its clarity and ease of understanding.[[3]]\n5. Adaptation to user level: The response is fairly direct, but due to accuracy issues in the content, it may not be fully suitable for users who have some knowledge of couplets or traditional literature.[[3]]\n\nIn summary, although the response performs well in relevance and harmlessness, it falls short in accuracy, completeness, source reliability, clarity and structure, and adaptation to user level. Therefore, the overall score is 2.", "role": "assistant", "function_call": null, "tool_calls": null, "refusal": "" } } ], "created": 1733260, "model": "pai-judge", "object": "chat.completion", "service_tier": "", "system_fingerprint": "", "usage": { "completion_tokens": 333, "prompt_tokens": 790, "total_tokens": 1123 } }
Pairwise-model battle
Pairwise-model battle assesses the quality of the responses that two large language models give to the same question.
-
Request example
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) completion = client.chat.completions.create( model='pai-judge', messages=[ { "role": "user", "content": [ { "mode": "pairwise", "type": "json", "json": { "question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer1": "To cross the river, find the creek.", "answer2": "To chase the dream, grasp the star." } } ] } ] ) print(completion.model_dump()) if __name__ == '__main__': main()curl -X POST https://aiservice.cn-hangzhou.aliyuncs.com/v1/chat/completions \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "model": "pai-judge", "messages": [ { "role": "user", "content": [ { "mode": "pairwise", "type": "json", "json": { "question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer1": "To cross the river, find the creek.", "answer2": "To chase the dream, grasp the star." } } ] } ] }' -
Response
{ "id": "528b2abf-54a5-4210-88e8-002b76e0c40f", "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "I believe [[the two responses are tied]], with response 1 receiving an overall score of [[3]] and response 2 receiving an overall score of [[3]], for the following reasons:\n1. Accuracy: The user instruction asks for a second line (the lower line of the couplet) based on the provided first line (the upper line of the couplet). Both responses provide a lower couplet line that matches the first line, meeting the user's basic requirements. Therefore, response 1 and response 2 both receive [[4]] points for accuracy.\n2. Completeness: Although both responses follow the basic couplet structure, there is no third or additional couplet node to assess the completeness of the couplets more accurately. Under this criterion, because a comparison across three nodes is lacking, both responses can only be given [[3]] points.\n3. Relevance: Both responses directly address the user instruction and focus on providing a second couplet line that matches the first. Therefore, both responses receive [[4]] points for relevance.\n4. Clarity and structure: Both responses present clear, well-structured couplets that are logical and easy to understand. Therefore, both responses receive [[4]] points for clarity and structure.\n5. Harmlessness: Both responses avoid potentially offensive content and maintain appropriateness and cultural sensitivity. Therefore, both responses receive [[5]] points for harmlessness.\n6. Source reliability and timeliness: These two criteria are not very applicable in this case, because the creation of couplets is usually not affected by time and does not involve factual information, so it is difficult to evaluate source reliability and timeliness. These two criteria do not apply to the current response evaluation.\n7. Adaptation to user level: Both responses use simple language that is easy for most users to understand. Therefore, both responses receive [[4]] points for adaptation to user level.\n\nIn summary, the two responses perform similarly on most criteria and both are fairly suitable as the lower line of the couplet. Therefore, I consider the two responses tied.", "refusal": null, "role": "assistant", "annotations": null, "audio": null, "function_call": null, "tool_calls": [], "reasoning_content": null }, "stop_reason": null } ], "created": 1787110358, "model": "pai-judge", "object": "chat.completion", "moderation": null, "service_tier": null, "system_fingerprint": null, "usage": { "completion_tokens": 410, "prompt_tokens": 839, "total_tokens": 1249, "completion_tokens_details": null, "prompt_tokens_details": null }, "prompt_logprobs": null }
Custom template
After you call LLM-as-a-Judge by using the preceding examples, the system generates the corresponding prompt template. If that template does not meet your requirements, you can customize an evaluation template (this topic uses pairwise-model battle as an example).
-
Request example
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) system = "Act as a fair judge and evaluate the quality of the artificial intelligence assistant's answer to the user question below.\n\n" \ "The following is a basic personality description of these artificial intelligence assistants:\n" \ "They do not evaluate or compare people, and they do not do anything that harms humans. Their personality tends to be independent and autonomous.\n" user = \ "Score the following question-answer pair on a scale of 1-5 points:\n" \ "Question: What do you think is the impact of social media on interpersonal relationships?\n" \ "Response: Social media makes it easier for people to connect, but it may also lead to estrangement.\n" \ "Scoring criteria:\n" \ "1: The response is completely irrelevant, has no content, or is completely wrong.\n" \ "2: The response is somewhat relevant, but the content is superficial or overly brief.\n" \ "3: The response is relevant and provides some insights, but lacks in-depth analysis.\n" \ "4: The response is relevant and in-depth, providing clear insights and examples.\n" \ "5: The response is highly relevant and profound, providing comprehensive viewpoints and rich examples." completion = client.chat.completions.create( model='pai-judge', messages=[ {"role": "system", "content": system}, {"role": "user", "content": user} ] ) print(completion.model_dump()) if __name__ == '__main__': main()curl -s -X POST "https://aiservice.cn-hangzhou.aliyuncs.com/v1/chat/completions" \ -H "Authorization: Bearer $JUDGE_MODEL_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "model": "pai-judge", "messages": [ { "role": "system", "content": "Act as a fair judge and evaluate the quality of the artificial intelligence assistant's answer to the user question below.\n\nThe following is a basic personality description of these artificial intelligence assistants:\nThey do not evaluate or compare people, and they do not do anything that harms humans. Their personality tends to be independent and autonomous." }, { "role": "user", "content": "Score the following question-answer pair on a scale of 1-5 points:\nQuestion: What do you think is the impact of social media on interpersonal relationships?\nResponse: Social media makes it easier for people to connect, but it may also lead to estrangement.\nScoring criteria:\n1: The response is completely irrelevant, has no content, or is completely wrong.\n2: The response is somewhat relevant, but the content is superficial or overly brief.\n3: The response is relevant and provides some insights, but lacks in-depth analysis.\n4: The response is relevant and in-depth, providing clear insights and examples.\n5: The response is highly relevant and profound, providing comprehensive viewpoints and rich examples." } ] }' -
Response
{ "id": "e2f72777-ddf5-4ff8-b7dd-4ecefd6e4014", "object": "chat.completion", "created": 1153092, "model": "pai-judge", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Based on the provided scoring criteria, I would give this answer 3 points. The response “Social media makes it easier for people to connect, but it may also lead to estrangement.” is clearly relevant and directly addresses the impact of social media on interpersonal relationships. It mentions two opposite effects: enhanced connection and estrangement, which shows a certain level of insight. However, the answer is relatively brief and does not further elaborate on the specific impacts of these two aspects or provide examples to support its viewpoint, so it lacks in-depth analysis. Therefore, according to the criteria, it meets the 3-point standard: relevant and providing some insights, but without deeper discussion.", "refusal": "", "function_call": null, "tool_calls": null}, "finish_reason": "stop", "logprobs": null } ], "usage": { "prompt_tokens": 910, "completion_tokens": 411, "total_tokens": 1321 }, "system_fingerprint": "", "service_tier": "" }
Batch call (offline call)
Step 1: Prepare the batch data
The batch data file must meet the following requirements:
-
A single file cannot exceed 10 MB. If a file is larger, you can split it into multiple files and upload them.
-
The total size of all files uploaded by one account cannot exceed 100 GB.
-
The API file for batch processing is in the .jsonl format.
In this file, each line contains the details of a single request to the API, and the parameters in the request content of each line must include body and a unique custom_id value. For the parameters that body supports, see Request parameters.
-
Refer to the following file format:
{"custom_id": "request-1", "body": {"model": "pai-judge", "messages": [{"role": "user", "content": [{"mode": "single", "type": "json", "json": {"question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer": "To cross the river, find the creek."}}]}]}} {"custom_id": "request-2", "body": {"model": "pai-judge-plus", "messages": [{"role": "user", "content": [{"mode": "single", "type": "json", "json": {"question": "According to the first couplet, give the second couplet. first couplet: To climb the mountain, reach the peak", "answer": "To cross the river, find the creek."}}]}]}}
Step 2: Upload the batch data
Use the data upload API of LLM-as-a-Judge to upload the batch data to the server and obtain a unique file_id value.
-
Request example.
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) upload_files = client.files.create( file=open("/home/xxx/input.jsonl", "rb"), purpose="batch", ) print(upload_files.model_dump_json(indent=4)) if __name__ == '__main__': main()curl -XPOST https://aiservice.cn-hangzhou.aliyuncs.com/v1/files \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" \ -F purpose="batch" \ -F file="@/home/xxx/input.jsonl" -
Response.
{ "id": "file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713", "object": "file", "bytes": 698, "created_at": 1742454203, "filename": "input.jsonl", "purpose": "batch" }
Step 3: Create a batch task
After you upload the file, use the file_id of the input file to create a batch task.
This topic assumes that file_id is file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713. Currently, the completion window can be set only to 24 hours, and after the task is created, a unique batch_id value is returned.
-
Request example.
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) create_batches = client.batches.create( endpoint="/v1/chat/completions", input_file_id="file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713", completion_window="24h", ) print(create_batches.model_dump_json(indent=4)) if __name__ == '__main__': main()curl -XPOST https://aiservice.cn-hangzhou.aliyuncs.com/v1/batches \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" \ -d '{ "input_file_id": "file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713", "endpoint": "/v1/chat/completions", "completion_window": "24h" }' -
Response.
{ "id": "batch_66f245a0-88d1-458c-8e1c-a819a5943022", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713", "completion_window": "24h", "status": "Creating", "output_file_id": null, "error_file_id": null, "created_at": 1742455213, "in_process_at": null, "expires_at": null, "FinalizingAt": null, "completed_at": null, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 3, "completed": 0, "failed": 0 }, "metadata": null }
Step 4: Check the task status
Query the running status of the task by using batch_id. After the running status becomes Succeeded, the returned response contains the ID of the generated file: output_file_id.
-
Request example.
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) retrieve_batches = client.batches.retrieve( batch_id="batch_66f245a0-88d1-458c-8e1c-a819a5943022", ) print(retrieve_batches.model_dump_json(indent=4)) if __name__ == '__main__': main()curl -XGET https://aiservice.cn-hangzhou.aliyuncs.com/v1/batches/batch_66f245a0-88d1-458c-8e1c-a819a5943022 \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" -
Response.
{ "id": "batch_66f245a0-88d1-458c-8e1c-a819a5943022", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-batch-EC043540BE1C7BE3F9F2F0A8F47D1713", "completion_window": "24h", "status": "Succeeded", "output_file_id": "file-batch_output-66f245a0-88d1-458c-8e1c-a819a5943022", "error_file_id": null, "created_at": 1742455213, "in_process_at": 1742455640, "expires_at": 1742455640, "FinalizingAt": 1742455889, "completed_at": 1742455889, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 3, "completed": 3, "failed": 0 }, "metadata": null }
Step 5: Obtain the task result
Query and download the content of the generated file by using output_file_id.
-
Request example.
import os from openai import OpenAI def main(): base_url = "https://aiservice.cn-hangzhou.aliyuncs.com/v1" judge_model_token = os.getenv("JUDGE_MODEL_TOKEN") client = OpenAI( api_key=judge_model_token, base_url=base_url ) content_files = client.files.content( file_id="file-batch_output-66f245a0-88d1-458c-8e1c-a819a5943022", ) print(content_files) if __name__ == '__main__': main()curl -XGET https://aiservice.cn-hangzhou.aliyuncs.com/v1/files/file-batch_output-66f245a0-88d1-458c-8e1c-a819a5943022/content \ -H "Authorization: Bearer ${JUDGE_MODEL_TOKEN}" > output.jsonl -
Response.
{"id":"dcee3584-6f30-9541-a855-873a6d86b7d9","custom_id":"request-1","response":{"status_code":200,"request_id":"dcee3584-6f30-9541-a855-873a6d86b7d9","body":{"created":1737446797,"usage":{"completion_tokens":7,"prompt_tokens":26,"total_tokens":33},"model":"pai-judge","id":"chatcmpl-dcee3584-6f30-9541-a855-873a6d86b7d9","choices":[{"finish_reason":"stop","index":0,"message":{"content":"2+2 equals 4."}}],"object":"chat.completion"}},"error":null} {"id":"dcee3584-6f30-9541-a855-873a6d86b7d9","custom_id":"request-2","response":{"status_code":200,"request_id":"dcee3584-6f30-9541-a855-873a6d86b7d9","body":{"created":1737446797,"usage":{"completion_tokens":7,"prompt_tokens":26,"total_tokens":33},"model":"pai-judge-plus","id":"chatcmpl-dcee3584-6f30-9541-a855-873a6d86b7d9","choices":[{"finish_reason":"stop","index":0,"message":{"content":"2+2 equals 4."}}],"object":"chat.completion"}},"error":null},