|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""A workflow with LLM-as-a-judge.""" |
| 3 | +import json |
| 4 | +from typing import List, Optional, Tuple |
| 5 | + |
| 6 | +import openai |
| 7 | + |
| 8 | +from trinity.common.experience import Experience |
| 9 | +from trinity.common.models.model import ModelWrapper |
| 10 | +from trinity.common.workflows.workflow import WORKFLOWS, SimpleWorkflow, Task |
| 11 | + |
| 12 | + |
| 13 | +@WORKFLOWS.register_module("rubric_judge_workflow") |
| 14 | +class RubricJudgeWorkflow(SimpleWorkflow): |
| 15 | + """A workflow using LLM-as-a-judge and rubrics to get the reward. |
| 16 | +
|
| 17 | + Adapted from https://arxiv.org/pdf/2507.17746 |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + *, |
| 23 | + task: Task, |
| 24 | + model: ModelWrapper, |
| 25 | + auxiliary_models: Optional[List[openai.OpenAI]] = None, |
| 26 | + ): |
| 27 | + super().__init__( |
| 28 | + task=task, |
| 29 | + model=model, |
| 30 | + auxiliary_models=auxiliary_models, |
| 31 | + ) |
| 32 | + |
| 33 | + def reset(self, task: Task): |
| 34 | + """Modified from SimpleWorkflow.reset""" |
| 35 | + self.format_args = task.format_args |
| 36 | + self.system_prompt = task.format_args.system_prompt |
| 37 | + self.reply_prefix = task.format_args.reply_prefix |
| 38 | + |
| 39 | + if self.system_prompt is None: |
| 40 | + self.system_prompt = """A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. |
| 41 | + """ |
| 42 | + |
| 43 | + self.raw_task = task.raw_task |
| 44 | + self.task_desc = task.task_desc |
| 45 | + self.truth = task.truth |
| 46 | + self.rubric = self.raw_task.get("rubric", []) |
| 47 | + |
| 48 | + def run(self) -> List[Experience]: |
| 49 | + """Modified from SimpleWorkflow.run""" |
| 50 | + |
| 51 | + messages = self.format_messages() |
| 52 | + |
| 53 | + self.logger.debug("start chat") |
| 54 | + responses = self.model.chat(messages, **self.rollout_args) |
| 55 | + |
| 56 | + # === Calculate rubric-based rewards === |
| 57 | + assert ( |
| 58 | + self.auxiliary_models is not None |
| 59 | + ), "Current implementation of rubric-based rewards requires that auxiliary_models is not None." |
| 60 | + |
| 61 | + judge_success_list = [] |
| 62 | + for i, response in enumerate(responses): |
| 63 | + judge_success, reward = self.get_judge_reward( |
| 64 | + response=response.response_text, judger=self.auxiliary_models[0] |
| 65 | + ) |
| 66 | + response.reward = reward |
| 67 | + response.eid.run = i + self.run_id_base |
| 68 | + |
| 69 | + judge_success_list.append(judge_success) |
| 70 | + |
| 71 | + if i == 0: |
| 72 | + self.logger.debug( |
| 73 | + f"self.task_desc: {self.task_desc}, messages: {messages}, response: {response.response_text}, reward: {response.reward}" |
| 74 | + ) |
| 75 | + |
| 76 | + # record judge success |
| 77 | + judge_success_rate = ( |
| 78 | + sum(judge_success_list) / len(judge_success_list) if judge_success_list else 0.0 |
| 79 | + ) |
| 80 | + for response in responses: |
| 81 | + if response.metrics is None: |
| 82 | + response.metrics = {} |
| 83 | + response.metrics.update({"judge_success": float(judge_success_rate)}) |
| 84 | + |
| 85 | + return responses |
| 86 | + |
| 87 | + def get_judge_reward(self, response: str, judger: openai.OpenAI) -> Tuple[bool, float]: |
| 88 | + """Get rewards with LLM-as-a-judge |
| 89 | + The prompts are adapted from RAR-IMPLICIT method in https://arxiv.org/pdf/2507.17746 |
| 90 | + """ |
| 91 | + # Step 1: format prompts |
| 92 | + # system prompt |
| 93 | + ruler_system_prompt = """You are an expert evaluator. Given a user prompt, a generated response, and a list of quality rubrics, please rate the overall quality of the response on a scale of 1 to 10 based on how well it satisfies the rubrics. |
| 94 | +Consider all rubrics holistically when determining your score. A response that violates multiple rubrics should receive a lower score, while a response that satisfies all rubrics should receive a higher score. |
| 95 | +Start your response with a valid JSON object that starts with "```json" and ends with "```". The JSON object should contain |
| 96 | +a single key "rating" and the value should be an integer between 1 and 10. |
| 97 | +Example response: |
| 98 | +```json |
| 99 | +{ |
| 100 | +"rating": 7 |
| 101 | +}```""" |
| 102 | + # user prompt |
| 103 | + if len(self.rubric) > 0: |
| 104 | + rubric_prompt_parts = [ |
| 105 | + f"Rubric {i} (weight: {single_rubric['weight']}): {single_rubric['description']}" |
| 106 | + for i, single_rubric in enumerate(self.rubric) |
| 107 | + ] |
| 108 | + rubric_list_string = "\n".join(rubric_prompt_parts) |
| 109 | + else: |
| 110 | + self.logger.warning("No rubric is provided!") |
| 111 | + rubric_list_string = "Rubrics are not provided." |
| 112 | + |
| 113 | + ruler_user_prompt = f"""Given the following prompt, response, and rubrics, please rate the overall quality of the response on a scale of 1 to 10 based |
| 114 | +on how well it satisfies the rubrics. |
| 115 | +<prompt> |
| 116 | +{self.task_desc} |
| 117 | +</prompt> |
| 118 | +<response> |
| 119 | +{response} |
| 120 | +</response> |
| 121 | +<rubrics> |
| 122 | +{rubric_list_string} |
| 123 | +</rubrics> |
| 124 | +Your JSON Evaluation: |
| 125 | +""".strip() |
| 126 | + |
| 127 | + # Step 2: invoke judger LLM |
| 128 | + messages = [ |
| 129 | + {"role": "system", "content": ruler_system_prompt}, |
| 130 | + {"role": "user", "content": ruler_user_prompt}, |
| 131 | + ] |
| 132 | + completion = judger.chat.completions.create( |
| 133 | + model=judger.model_path, messages=messages, stream=False, temperature=0.0 |
| 134 | + ) |
| 135 | + judger_response = completion.choices[0].message.content |
| 136 | + self.logger.debug(f"LLM judge response: {judger_response}") |
| 137 | + |
| 138 | + # Step 3: extract score from judger's response (expecting a JSON block with "rating") |
| 139 | + try: |
| 140 | + # Extract content between ```json and ``` |
| 141 | + start_tag = "```json" |
| 142 | + start_index = judger_response.find(start_tag) |
| 143 | + if start_index == -1: |
| 144 | + start_tag = "```" |
| 145 | + start_index = judger_response.find(start_tag) |
| 146 | + |
| 147 | + if start_index == -1: |
| 148 | + self.logger.warning("No JSON code block found in judger response.") |
| 149 | + return False, 0.0 |
| 150 | + |
| 151 | + end_index = judger_response.find("```", start_index + len(start_tag)) |
| 152 | + if end_index == -1: |
| 153 | + self.logger.warning("Malformed JSON code block in judger response.") |
| 154 | + return False, 0.0 |
| 155 | + |
| 156 | + json_str = judger_response[start_index + len(start_tag) : end_index].strip() |
| 157 | + parsed = json.loads(json_str) |
| 158 | + rating = parsed.get("rating") |
| 159 | + |
| 160 | + if not isinstance(rating, (int, float)) or not (1 <= rating <= 10): |
| 161 | + self.logger.warning(f"Invalid or out-of-range rating: {rating}") |
| 162 | + return False, 0.0 |
| 163 | + |
| 164 | + normalized_score = rating * 0.1 # Normalize 1-10 to 0-1 scale |
| 165 | + return True, normalized_score |
| 166 | + |
| 167 | + except json.JSONDecodeError as e: |
| 168 | + self.logger.warning(f"Failed to parse JSON from judger response: {e}") |
| 169 | + return False, 0.0 |
| 170 | + except Exception as e: |
| 171 | + self.logger.warning(f"Unexpected error when processing judger response: {e}") |
| 172 | + return False, 0.0 |
0 commit comments