Mukul Rayana commited on
Commit ·
5405e38
1
Parent(s): c9853ac
fix: MistralJudge uses from_json_schema grammar — correct structure for claim extraction and verification (Day 15)
Browse files- eval/run_ragas.py +30 -28
eval/run_ragas.py
CHANGED
|
@@ -47,37 +47,39 @@ class MistralJudge(DeepEvalBaseLLM):
|
|
| 47 |
|
| 48 |
def generate(self, prompt: str) -> str:
|
| 49 |
from llama_cpp import LlamaGrammar
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
#
|
| 53 |
-
#
|
| 54 |
-
#
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
'string ::= "\\"" ([^\\\\"] | "\\\\" ["\\\\/bfnrt])* "\\""\n'
|
| 62 |
-
'ws ::= ([ \\t\\n])*\n'
|
| 63 |
-
)
|
| 64 |
else:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
try:
|
| 77 |
-
grammar = LlamaGrammar.
|
| 78 |
out = self._llm(prompt, max_tokens=1024, temperature=0.0, grammar=grammar, stop=["[INST]"])
|
| 79 |
-
except Exception:
|
| 80 |
-
# Fallback: no grammar
|
|
|
|
| 81 |
out = self._llm(prompt, max_tokens=1024, temperature=0.0, stop=["[INST]"])
|
| 82 |
return out["choices"][0]["text"].strip()
|
| 83 |
|
|
|
|
| 47 |
|
| 48 |
def generate(self, prompt: str) -> str:
|
| 49 |
from llama_cpp import LlamaGrammar
|
| 50 |
+
import json as _json
|
| 51 |
+
# Use from_json_schema for grammar-constrained sampling.
|
| 52 |
+
# Physically prevents Mistral from generating invalid JSON at token level.
|
| 53 |
+
# Detect call type from prompt tail: claim extraction = array,
|
| 54 |
+
# claim verification = object with verdicts array.
|
| 55 |
+
prompt_tail = prompt[-300:].lower()
|
| 56 |
+
is_extraction = any(w in prompt_tail for w in [
|
| 57 |
+
"claims", "statements", "list", "extract", "identify"
|
| 58 |
+
])
|
| 59 |
+
if is_extraction:
|
| 60 |
+
schema = _json.dumps({"type": "array", "items": {"type": "string"}})
|
|
|
|
|
|
|
|
|
|
| 61 |
else:
|
| 62 |
+
schema = _json.dumps({
|
| 63 |
+
"type": "object",
|
| 64 |
+
"properties": {
|
| 65 |
+
"verdicts": {
|
| 66 |
+
"type": "array",
|
| 67 |
+
"items": {
|
| 68 |
+
"type": "object",
|
| 69 |
+
"properties": {
|
| 70 |
+
"verdict": {"type": "string", "enum": ["yes", "no", "idk"]},
|
| 71 |
+
"reason": {"type": "string"}
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
})
|
| 77 |
try:
|
| 78 |
+
grammar = LlamaGrammar.from_json_schema(schema, verbose=False)
|
| 79 |
out = self._llm(prompt, max_tokens=1024, temperature=0.0, grammar=grammar, stop=["[INST]"])
|
| 80 |
+
except Exception as e:
|
| 81 |
+
# Fallback: no grammar if schema compilation fails
|
| 82 |
+
print(f"[MistralJudge] Grammar fallback: {e}")
|
| 83 |
out = self._llm(prompt, max_tokens=1024, temperature=0.0, stop=["[INST]"])
|
| 84 |
return out["choices"][0]["text"].strip()
|
| 85 |
|