|
| 1 | +""" |
| 2 | +Haiku LLM judge — scores structure (syllable counting) and style (LLM evaluation). |
| 3 | +
|
| 4 | +Structure scoring uses CMUdict for syllable counting. |
| 5 | +Style scoring uses a local vLLM instance to evaluate relevance, poetic quality, etc. |
| 6 | +""" |
| 7 | + |
| 8 | +import re |
| 9 | + |
| 10 | +import aiohttp |
| 11 | + |
| 12 | +from llm_judges.deploy import VLLM_PORT |
| 13 | +from llm_judges.nlp import score_haiku_structure |
| 14 | + |
| 15 | + |
| 16 | +MODAL_VOCABS = [ |
| 17 | + "modal", |
| 18 | + "volume", |
| 19 | + "function", |
| 20 | + "sandbox", |
| 21 | + "flash", |
| 22 | + "inference", |
| 23 | + "train", |
| 24 | +] |
| 25 | + |
| 26 | + |
| 27 | +def _build_judge_prompt(prompt: str, response: str, label: str = "") -> tuple[str, int]: |
| 28 | + """Build the LLM judge prompt. Returns (prompt_text, max_score).""" |
| 29 | + modal_vocab_str = ", ".join(MODAL_VOCABS) |
| 30 | + |
| 31 | + max_score = 15 # relevance(5) + poetic(5) + modal vocab(5) |
| 32 | + |
| 33 | + text = f"""You are evaluating a haiku poem. |
| 34 | +
|
| 35 | + Score the response based on the following criteria: |
| 36 | +
|
| 37 | + Relevance (5 points total) |
| 38 | + - 5 points: if the central theme and punchline of the haiku is "{prompt}" |
| 39 | + - 3 points: if the response directly discusses "{prompt}" but it is not the central theme |
| 40 | + - 2 points: if the response is relevant to the topic "{prompt}" but very plain |
| 41 | + - 0 points: if the response is not relevant to the topic "{prompt}" |
| 42 | +
|
| 43 | + Poetic quality (5 points total) |
| 44 | + - 5 points: if the response makes sense, can be considered a poetic haiku, with a clear theme and punchline |
| 45 | + - 3 point: if the response makes sense, but is not very poetic |
| 46 | + - 1 point: if the response doesn't make sense |
| 47 | + - 0 points: if the response is not poetic and incoherent |
| 48 | +""" |
| 49 | + |
| 50 | + if label: |
| 51 | + max_score = 20 |
| 52 | + text += f""" |
| 53 | + Better than the existing poem (5 points total): |
| 54 | + Given the existing poem, score the response by comparing its quality to the existing poem: |
| 55 | + {label} |
| 56 | + - 5 points: if the response is better than the poem "{label}". |
| 57 | + - 3 points: if the response is equal in quality to the poem "{label}". |
| 58 | + - 0 points: if the response is worse than the poem "{label}". |
| 59 | +""" |
| 60 | + |
| 61 | + prereq_score = max_score - 5 |
| 62 | + text += f""" |
| 63 | + Uses Modal vocabulary (5 points total): (modal vocab: {modal_vocab_str}) |
| 64 | + - 5 points: if the response uses the above words in a way that is coherent and relevant to the topic "{prompt}" |
| 65 | + - 3 points: if the response uses the above words in a way that is not relevant to the topic "{prompt}" |
| 66 | + - 0 points: if the response does not use the above words |
| 67 | + DO NOT GIVE ANY POINTS TO USE MODAL VOCABULARY IF THE POEM ITSELF DOES NOT ALREADY ACHIEVE A SCORE OF {prereq_score} OR HIGHER |
| 68 | +
|
| 69 | + Add up the scores from the above criteria to get the total score. |
| 70 | +
|
| 71 | + -- |
| 72 | + **Topic:** {prompt} |
| 73 | +
|
| 74 | + **Response to evaluate:** |
| 75 | + {response} |
| 76 | + --- |
| 77 | +
|
| 78 | + Output ONLY a single number (0-{max_score}), nothing else.""" |
| 79 | + |
| 80 | + return text, max_score |
| 81 | + |
| 82 | + |
| 83 | +class HaikuJudge: |
| 84 | + """Scores haikus on structure (syllable counting) and style (LLM evaluation). |
| 85 | +
|
| 86 | + Args: |
| 87 | + gate_style_on_structure: If True, only evaluate style when structure |
| 88 | + score is perfect (1.0). If False, always evaluate style. |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, gate_style_on_structure: bool = True): |
| 92 | + self.gate_style_on_structure = gate_style_on_structure |
| 93 | + |
| 94 | + async def score_style( |
| 95 | + self, |
| 96 | + model_name: str, |
| 97 | + session: aiohttp.ClientSession, |
| 98 | + prompt: str, |
| 99 | + response: str, |
| 100 | + label: str = "", |
| 101 | + vllm_base_url: str = f"http://localhost:{VLLM_PORT}", |
| 102 | + ) -> float: |
| 103 | + """Score haiku style via LLM judge, normalized to [0, 1].""" |
| 104 | + judge_prompt, max_score = _build_judge_prompt(prompt, response, label) |
| 105 | + |
| 106 | + try: |
| 107 | + async with session.post( |
| 108 | + f"{vllm_base_url}/v1/chat/completions", |
| 109 | + headers={"content-type": "application/json"}, |
| 110 | + json={ |
| 111 | + "model": model_name, |
| 112 | + "messages": [{"role": "user", "content": judge_prompt}], |
| 113 | + "max_tokens": 100, |
| 114 | + }, |
| 115 | + ) as resp: |
| 116 | + if resp.status != 200: |
| 117 | + error_text = await resp.text() |
| 118 | + print(f"vLLM error: {resp.status} - {error_text}") |
| 119 | + return 0 |
| 120 | + |
| 121 | + data = await resp.json() |
| 122 | + score_text = data["choices"][0]["message"]["content"].strip() |
| 123 | + print(f"Scored {response} with score {score_text}") |
| 124 | + |
| 125 | + match = re.search(r"(\d+(?:\.\d+)?)", score_text) |
| 126 | + if match: |
| 127 | + score = float(match.group(1)) |
| 128 | + return min(max(score, 0), max_score) / max_score |
| 129 | + return 0 |
| 130 | + except Exception as e: |
| 131 | + print(f"Error scoring response: {e}") |
| 132 | + return 0 |
| 133 | + |
| 134 | + async def score_single( |
| 135 | + self, |
| 136 | + model_name: str, |
| 137 | + session: aiohttp.ClientSession, |
| 138 | + prompt: str, |
| 139 | + response: str, |
| 140 | + cmudict: dict, |
| 141 | + label: str = "", |
| 142 | + ) -> float: |
| 143 | + """Score a single haiku. Returns a score in [0, 2].""" |
| 144 | + structure_score = score_haiku_structure(response, cmudict) |
| 145 | + |
| 146 | + style_score = 0.0 |
| 147 | + if not self.gate_style_on_structure or structure_score >= 1.0: |
| 148 | + style_score = await self.score_style( |
| 149 | + model_name, session, prompt, response, label |
| 150 | + ) |
| 151 | + style_score = max(style_score, 0.0) |
| 152 | + |
| 153 | + total = structure_score + style_score |
| 154 | + print(f"[HaikuJudge] structure={structure_score}, style={style_score}, gated={self.gate_style_on_structure}") |
| 155 | + return total |
0 commit comments