File size: 10,416 Bytes
2e511b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | """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()
|