code / scripts /compare_legora_prompts.py
anonymous
[code] Reproduction bundle.
2e511b5
Raw
History Blame Contribute Delete
10.4 kB
"""Compare the per-column prompts of the two Legora runs against prompts v3.
The 2026-08-05 Legora export (``data/raw/legora_2026-08-05_prompts.xlsx``) is a
re-export of the 2026-08-01 tabular review with the "with prompt" option
enabled: the data rows are byte-identical to ``legora_2026-08-01.xlsx``; row 2
additionally carries the question text of every column. As with the values
(see ``scripts/compare_legora_runs.py``), the left column group belongs to
``legora-1`` and the right one to ``legora-2``.
This script extracts both prompt sets — from the raw export, or with
``--prompts-dir`` from the published ``prompts_legora_{1,2}.jsonl`` — aligns
them with the per-variable sections of ``legex/prompts/v3.py``, and writes a
markdown report with word-level diffs (``[-deleted-]`` / ``{+inserted+}``).
uv run python scripts/compare_legora_prompts.py \
[--xlsx data/raw/legora_2026-08-05_prompts.xlsx] \
[--prompts-dir ../inference-results/prompts] \
[--out data/analysis/legora_prompt_comparison.md]
"""
import argparse
import difflib
import json
import re
import sys
from pathlib import Path
import openpyxl
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from legex.prompts import v3 # noqa: E402
MODEL_A, MODEL_B = "legora-1", "legora-2"
DEFAULT_XLSX = Path("data/raw/legora_2026-08-05_prompts.xlsx")
DEFAULT_OUT = Path("data/analysis/legora_prompt_comparison.md")
PROMPT_SUFFIX = " (with prompt)"
# Equal stretches longer than this many words are elided in the diffs.
CONTEXT_WORDS = 6
FINDINGS = """\
## Findings
* Both column groups are per-column adaptations of the v3 coding rules,
rewritten for Legora's tabular-review UI. Structural v3 material that cannot
exist per column is gone in both runs: the JSON-typing preamble, the
JSON-`null` semantics (the columns ask for the literal string `None`
instead), and the companion `Currency_<variable>` fields — the export has no
currency columns at all.
* **legora-2 is the cleaner, complete set**: all 12 prompts follow one template
("Where to find it: … Formatting rules: … Permissible values: …") and carry
the full substance of the matching v3 section.
* **legora-1 deviates from the v3 content twice.**
1. `legal_subject_judgement` is not our rule at all but Legora's
auto-generated question ("What legal subjects or issues are addressed …"),
an essay-style prompt without the underscore/slash coding format. This
explains the essay-like answers of legora-1 on that column and the low
inter-run agreement (39.9 % when both filled, see
`legora_run_comparison.md`).
2. `case_id` has an ad-hoc tail appended ("Put here only the number (with
slahs, dots etc) no more information. No dates or text", note the typo)
that legora-2 lacks.
The other ten legora-1 prompts match legora-2 in substance and differ only
in scaffolding (flowing text vs. labelled sections, "None (the literal
string)" vs. "None").
* **Both runs extend v3** with material that is not in the repo prompt:
a U.S. federal-court hint for `trial_start_date`; Swiss search anchors
("Mit Beschwerde vom", "Lausanne, [date]", "Erwägungen — Eintreten /
recevabilité", "Die Gerichtskosten von Fr. …", "… à titre de dépens";
legora-2 also "Gegenstand/Objet/Oggetto"); "typically item 2"/"item 3"
locations in the operative part; an explicit sum-to-1.0 constraint for
`plaintiff_loosing_share`; and, for the ISIC columns, a dominant-activity
rule for multi-sector entities, extra `no_allocation_possible` examples
(tenant, consumer, patient, unemployed) and anonymized-party examples for
`None`. The wrong-example currency changed from v3's `CHF 150000` to
`USD 150000`.
* **The ISIC category list is handled differently per run**: legora-1 inlines
all 24 permitted values in the prompt; legora-2 only asserts "You MUST enter
exactly one of the 24 permitted coded values" without listing them and
instead adds coding examples (law firm → n_professional_scientific_technical,
hospital → r_human_health_social_work, tradesperson → f_construction). Both
runs nevertheless answered in coded values. Notably,
`defendant_no1_ISIC1_industry_category` is the one field where legora-2 is
clearly worse than legora-1 against the Goldensets (acc 0.522 vs 0.563).
"""
def word_diff(a: str, b: str) -> str:
"""Inline word-level diff of ``a`` → ``b`` with long equal runs elided."""
aw, bw = a.split(), b.split()
sm = difflib.SequenceMatcher(None, aw, bw, autojunk=False)
out: list[str] = []
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
words = aw[i1:i2]
if len(words) > 2 * CONTEXT_WORDS + 2:
words = [*words[:CONTEXT_WORDS], "[…]", *words[-CONTEXT_WORDS:]]
out.append(" ".join(words))
else:
if tag in ("delete", "replace"):
out.append("[-" + " ".join(aw[i1:i2]) + "-]")
if tag in ("insert", "replace"):
out.append("{+" + " ".join(bw[j1:j2]) + "+}")
return " ".join(out)
def similarity(a: str, b: str) -> float:
return difflib.SequenceMatcher(None, a.split(), b.split(), autojunk=False).ratio()
def read_prompts(xlsx: Path) -> dict[str, dict[str, str]]:
"""Return ``{model: {field: prompt}}`` from the export's prompt row."""
wb = openpyxl.load_workbook(xlsx, data_only=True, read_only=True)
ws = wb.worksheets[0]
rows = ws.iter_rows(min_row=1, max_row=2, values_only=True)
header, prompt_row = next(rows), next(rows)
out: dict[str, dict[str, str]] = {MODEL_A: {}, MODEL_B: {}}
for head, prompt in zip(header, prompt_row):
if not head or not str(head).endswith(PROMPT_SUFFIX) or not prompt:
continue
field = str(head)[: -len(PROMPT_SUFFIX)]
model = MODEL_A if field not in out[MODEL_A] else MODEL_B
out[model][field] = " ".join(str(prompt).split())
return out
def read_published_prompts(prompts_dir: Path) -> dict[str, dict[str, str]]:
"""Return ``{model: {field: prompt}}`` from the published prompt JSONL."""
out: dict[str, dict[str, str]] = {}
for model in (MODEL_A, MODEL_B):
path = prompts_dir / f"prompts_{model.replace('-', '_')}.jsonl"
out[model] = {
rec["field"]: rec["prompt"]
for rec in map(json.loads, path.read_text(encoding="utf-8").splitlines())
}
return out
def v3_sections() -> dict[str, str]:
"""Per-variable rule sections of the v3 system prompt, whitespace-flattened."""
match = re.search(
r"## Variable coding rules\n(.*?)\n## Allowed ISIC", v3.PROMPT, re.S
)
if not match:
raise SystemExit("could not locate the variable sections in v3.PROMPT")
sections = {}
for sec in re.finditer(r"### (\S+)\n(.*?)(?=\n### |\Z)", match.group(1), re.S):
sections[sec.group(1)] = " ".join(sec.group(2).split())
return sections
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--xlsx", type=Path, default=DEFAULT_XLSX)
parser.add_argument("--prompts-dir", type=Path, default=None,
help="read the published prompts_legora_{1,2}.jsonl from this "
"directory instead of the raw --xlsx export")
parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
args = parser.parse_args()
prompts = (
read_published_prompts(args.prompts_dir)
if args.prompts_dir is not None
else read_prompts(args.xlsx)
)
rules = v3_sections()
fields = list(prompts[MODEL_A])
if list(prompts[MODEL_B]) != fields:
raise SystemExit("the two column groups carry different field sets")
lines: list[str] = []
lines.append(f"# Legora prompt comparison: {MODEL_A} vs {MODEL_B} vs prompts v3\n")
lines.append(
"Prompts from the 2026-08-05 prompt-bearing re-export of the 2026-08-01 "
"tabular review (published as `prompts/prompts_legora_{1,2}.jsonl` in "
"the inference-results dataset; the data rows are byte-identical to "
f"the 2026-08-01 export). Left column group = `{MODEL_A}`, right group "
f"= `{MODEL_B}`, as established in `legora_run_comparison.md`. The v3 "
"baseline is the per-variable section of `legex/prompts/v3.py`. "
"Similarities are word-level `difflib` ratios (1.0 = identical). "
"Generated by `scripts/compare_legora_prompts.py`.\n"
)
lines.append("## Similarity overview\n")
lines.append(
f"| field | {MODEL_A} words | {MODEL_B} words "
f"| {MODEL_A}{MODEL_B} | v3 ≈ {MODEL_A} | v3 ≈ {MODEL_B} |"
)
lines.append("|---|---|---|---|---|---|")
for field in fields:
a, b, rule = prompts[MODEL_A][field], prompts[MODEL_B][field], rules[field]
lines.append(
f"| {field} | {len(a.split())} | {len(b.split())} "
f"| {similarity(a, b):.2f} | {similarity(rule, a):.2f} "
f"| {similarity(rule, b):.2f} |"
)
lines.append("")
lines.append(FINDINGS)
lines.append("## Per-field prompts and diffs\n")
lines.append(
"Diff notation: `[-only in the left text-]`, `{+only in the right "
"text+}`, `[…]` elides unchanged words. For the ISIC fields the v3 "
"category list lives in a separate shared section and is therefore "
"not part of the v3 rule text below.\n"
)
for field in fields:
a, b, rule = prompts[MODEL_A][field], prompts[MODEL_B][field], rules[field]
lines.append(f"### {field}\n")
lines.append("**v3 rule**\n")
lines.append(f"> {rule}\n")
lines.append(f"**{MODEL_A}{MODEL_B}**\n")
lines.append("```diff-words")
lines.append(word_diff(a, b))
lines.append("```\n")
lines.append(f"**v3 → {MODEL_A}**\n")
lines.append("```diff-words")
lines.append(word_diff(rule, a))
lines.append("```\n")
lines.append(f"**v3 → {MODEL_B}**\n")
lines.append("```diff-words")
lines.append(word_diff(rule, b))
lines.append("```\n")
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text("\n".join(lines), encoding="utf-8")
print(f"wrote {args.out}")
if __name__ == "__main__":
main()