Spaces:
Sleeping
Add SMALL-model domain classifier for Penyusun
Browse filesReplaces the keyword-only domain anchor with a learned classifier that
extracts (sektor, jenjang, instansi, kasus_terkait, kerangka_hukum,
anti_drift) from topic + research + extra_instructions. The keyword path
remains as a fallback for when the SMALL model produces unparseable JSON.
Composition in _derive_domain_constraints:
1. _CASE_FACTS keyword overrides — always applied for known cases
(e.g. Kasus Ibam) since hand-curated facts beat generated ones.
2. classify_domain() SMALL-model call — produces DomainAnalysis,
rendered as constraint string into the BIG system prompt.
3. _keyword_domain_constraints fallback — fires only when classifier
raises (parse error, transport error, validation error).
Few-shot prompt with two worked examples (pendidikan + ketenagakerjaan)
locks the output shape; Pydantic validation rejects malformed responses.
10 new unit tests cover parsing (clean / code-fence / prepended-text),
classifier integration, render_constraints output, and the three-tier
composition logic (case facts + classifier + fallback).
Addresses §8.2 #4 in the Kasus Ibam whitepaper.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- src/legawa/agents/domain.py +185 -0
- src/legawa/agents/penyusun.py +68 -8
- tests/test_domain.py +185 -0
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SMALL-model domain classifier for Penyusun Naskah.
|
| 2 |
+
|
| 3 |
+
Replaces the keyword-based ``_derive_domain_constraints`` heuristic with a
|
| 4 |
+
learned extractor that takes a topic (plus optional research block and
|
| 5 |
+
extra instructions) and returns a structured ``DomainAnalysis``.
|
| 6 |
+
|
| 7 |
+
The output is rendered into a constraint string that is injected into the
|
| 8 |
+
BIG model's system prompt, telling the drafter exactly which sector it is
|
| 9 |
+
working in and which sectors to avoid.
|
| 10 |
+
|
| 11 |
+
Design notes:
|
| 12 |
+
- SMALL model only — this is cheap classification, no need for the BIG.
|
| 13 |
+
- Pydantic schema — invalid JSON triggers fallback in the caller.
|
| 14 |
+
- Few-shot prompt — gives the model 2 worked examples covering different
|
| 15 |
+
sectors (pendidikan + ketenagakerjaan) so its output shape is locked in.
|
| 16 |
+
- No tool calls — single round trip, low temperature.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from pydantic import BaseModel, Field, ValidationError
|
| 25 |
+
from rich.console import Console
|
| 26 |
+
|
| 27 |
+
from ..llm import LLMPool
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
SECTORS = (
|
| 31 |
+
"pendidikan_dasar_menengah",
|
| 32 |
+
"pendidikan_tinggi",
|
| 33 |
+
"ketenagakerjaan",
|
| 34 |
+
"kesehatan",
|
| 35 |
+
"fiskal_anggaran",
|
| 36 |
+
"pertahanan_keamanan",
|
| 37 |
+
"hukum_tipikor",
|
| 38 |
+
"pengadaan_barang_jasa",
|
| 39 |
+
"infrastruktur",
|
| 40 |
+
"lingkungan_hidup",
|
| 41 |
+
"ekonomi_perdagangan",
|
| 42 |
+
"tata_kelola_pemerintahan",
|
| 43 |
+
"agraria_pertanahan",
|
| 44 |
+
"sosial_kemasyarakatan",
|
| 45 |
+
"lain",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
JENJANG_VALUES = ("dasar", "menengah", "dasar_menengah", "tinggi")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class DomainAnalysis(BaseModel):
|
| 52 |
+
sektor_utama: str = Field(..., description=f"Salah satu dari: {SECTORS}")
|
| 53 |
+
jenjang: str | None = Field(None, description=f"Untuk topik pendidikan: {JENJANG_VALUES}")
|
| 54 |
+
instansi_terkait: list[str] = Field(default_factory=list)
|
| 55 |
+
kasus_terkait: str | None = Field(None, description="Nama kasus spesifik bila topik menyebut, mis. 'Kasus Ibam'.")
|
| 56 |
+
kerangka_hukum_utama: list[str] = Field(default_factory=list)
|
| 57 |
+
rangkuman_konteks: str = Field(..., description="1–2 kalimat ringkas.")
|
| 58 |
+
anti_drift: list[str] = Field(default_factory=list, description="Instruksi spesifik mencegah pergeseran sektor.")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
CLASSIFIER_PROMPT = f"""\
|
| 62 |
+
Anda adalah klasifier domain untuk Penyusun Naskah legislatif Indonesia.
|
| 63 |
+
Diberikan topik (dan opsional konteks riset hukum + instruksi tambahan), tentukan
|
| 64 |
+
sektor kebijakan yang relevan dan sediakan instruksi anti-drift untuk mencegah
|
| 65 |
+
model penyusun bergeser ke sektor yang salah.
|
| 66 |
+
|
| 67 |
+
Output WAJIB berupa JSON valid sesuai schema, tanpa teks tambahan, tanpa code fence:
|
| 68 |
+
|
| 69 |
+
{{
|
| 70 |
+
"sektor_utama": "<satu dari: {', '.join(SECTORS)}>",
|
| 71 |
+
"jenjang": "<satu dari: {', '.join(JENJANG_VALUES)} atau null>",
|
| 72 |
+
"instansi_terkait": ["<nama instansi atau komisi DPR>"],
|
| 73 |
+
"kasus_terkait": "<nama kasus jika topik menyebut kasus tertentu, atau null>",
|
| 74 |
+
"kerangka_hukum_utama": ["<kerangka hukum singkat, mis. 'Tipikor (UU 31/1999)'>"],
|
| 75 |
+
"rangkuman_konteks": "<1-2 kalimat ringkas konteks topik>",
|
| 76 |
+
"anti_drift": ["<instruksi spesifik mencegah pergeseran>"]
|
| 77 |
+
}}
|
| 78 |
+
|
| 79 |
+
Contoh 1:
|
| 80 |
+
TOPIK: "respons legislatif atas vonis Kasus Ibam dan akuntabilitas Program Digitalisasi Sekolah"
|
| 81 |
+
OUTPUT:
|
| 82 |
+
{{
|
| 83 |
+
"sektor_utama": "pendidikan_dasar_menengah",
|
| 84 |
+
"jenjang": "dasar_menengah",
|
| 85 |
+
"instansi_terkait": ["Kementerian Pendidikan Dasar dan Menengah", "Komisi X DPR RI", "Komisi III DPR RI"],
|
| 86 |
+
"kasus_terkait": "Kasus Ibam",
|
| 87 |
+
"kerangka_hukum_utama": ["Tipikor (UU 31/1999 jo UU 20/2001)", "Pengadaan Barang/Jasa (Perpres 16/2018 jo Perpres 12/2021)"],
|
| 88 |
+
"rangkuman_konteks": "Topik mengangkat akuntabilitas pengadaan teknologi pendidikan jenjang dasar/menengah pasca vonis kasus korupsi Chromebook.",
|
| 89 |
+
"anti_drift": [
|
| 90 |
+
"JANGAN bergeser ke pendidikan tinggi, perguruan tinggi (PTN/PTS), kampus, atau rektorat — kasus ini bukan tentang itu.",
|
| 91 |
+
"JANGAN gunakan UU 12/2012 Pendidikan Tinggi sebagai kerangka utama.",
|
| 92 |
+
"Fokus eksklusif pada pengadaan teknologi untuk sekolah dasar dan menengah."
|
| 93 |
+
]
|
| 94 |
+
}}
|
| 95 |
+
|
| 96 |
+
Contoh 2:
|
| 97 |
+
TOPIK: "regulasi outsourcing pasca UU Cipta Kerja"
|
| 98 |
+
OUTPUT:
|
| 99 |
+
{{
|
| 100 |
+
"sektor_utama": "ketenagakerjaan",
|
| 101 |
+
"jenjang": null,
|
| 102 |
+
"instansi_terkait": ["Kementerian Ketenagakerjaan", "Komisi IX DPR RI"],
|
| 103 |
+
"kasus_terkait": null,
|
| 104 |
+
"kerangka_hukum_utama": ["Ketenagakerjaan (UU 13/2003)", "Cipta Kerja (UU 6/2023)", "PKWT/Alih Daya (PP 35/2021)"],
|
| 105 |
+
"rangkuman_konteks": "Topik tentang perlindungan pekerja alih daya pasca UU Cipta Kerja dan peraturan pelaksana.",
|
| 106 |
+
"anti_drift": [
|
| 107 |
+
"Fokus pada hukum ketenagakerjaan dan perlindungan pekerja.",
|
| 108 |
+
"JANGAN menggeser isu ke sektor lain seperti pendidikan atau infrastruktur."
|
| 109 |
+
]
|
| 110 |
+
}}
|
| 111 |
+
|
| 112 |
+
Sekarang klasifikasikan topik yang diberikan.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _parse_analysis(raw: str) -> DomainAnalysis:
|
| 117 |
+
cleaned = raw.strip()
|
| 118 |
+
if cleaned.startswith("```"):
|
| 119 |
+
cleaned = cleaned.strip("`")
|
| 120 |
+
if cleaned.lower().startswith("json"):
|
| 121 |
+
cleaned = cleaned[4:].strip()
|
| 122 |
+
if not cleaned.startswith("{"):
|
| 123 |
+
start = cleaned.find("{")
|
| 124 |
+
end = cleaned.rfind("}")
|
| 125 |
+
if start != -1 and end != -1 and end > start:
|
| 126 |
+
cleaned = cleaned[start : end + 1]
|
| 127 |
+
data = json.loads(cleaned)
|
| 128 |
+
return DomainAnalysis.model_validate(data)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def classify_domain(
|
| 132 |
+
pool: LLMPool,
|
| 133 |
+
topic: str,
|
| 134 |
+
research_block: str = "",
|
| 135 |
+
extra_instructions: str | None = None,
|
| 136 |
+
*,
|
| 137 |
+
console: Console | None = None,
|
| 138 |
+
) -> DomainAnalysis:
|
| 139 |
+
"""Run the SMALL-model domain classifier.
|
| 140 |
+
|
| 141 |
+
Raises ``json.JSONDecodeError`` or ``pydantic.ValidationError`` on failure;
|
| 142 |
+
callers should wrap with their own fallback.
|
| 143 |
+
"""
|
| 144 |
+
user_msg_parts = [f"TOPIK: {topic}"]
|
| 145 |
+
if extra_instructions:
|
| 146 |
+
user_msg_parts.append(f"INSTRUKSI TAMBAHAN: {extra_instructions}")
|
| 147 |
+
if research_block:
|
| 148 |
+
# Trim the research block to keep the SMALL classifier prompt tight.
|
| 149 |
+
snippet = research_block.strip()
|
| 150 |
+
if len(snippet) > 4000:
|
| 151 |
+
snippet = snippet[:4000] + "\n[... dipotong ...]"
|
| 152 |
+
user_msg_parts.append(f"KONTEKS RISET (potongan):\n{snippet}")
|
| 153 |
+
|
| 154 |
+
raw = pool.small.chat(
|
| 155 |
+
[
|
| 156 |
+
{"role": "system", "content": CLASSIFIER_PROMPT},
|
| 157 |
+
{"role": "user", "content": "\n\n".join(user_msg_parts)},
|
| 158 |
+
],
|
| 159 |
+
temperature=0.1,
|
| 160 |
+
max_tokens=1024,
|
| 161 |
+
)
|
| 162 |
+
analysis = _parse_analysis(raw)
|
| 163 |
+
if console is not None:
|
| 164 |
+
console.print(
|
| 165 |
+
f"[dim]domain: sektor={analysis.sektor_utama} "
|
| 166 |
+
f"jenjang={analysis.jenjang or '-'} kasus={analysis.kasus_terkait or '-'}[/dim]"
|
| 167 |
+
)
|
| 168 |
+
return analysis
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def render_constraints(analysis: DomainAnalysis) -> str:
|
| 172 |
+
"""Render a DomainAnalysis as the constraint string injected into the BIG prompt."""
|
| 173 |
+
parts: list[str] = []
|
| 174 |
+
parts.append(f"Konteks domain: {analysis.rangkuman_konteks}")
|
| 175 |
+
parts.append(f"Sektor utama: {analysis.sektor_utama}")
|
| 176 |
+
if analysis.jenjang:
|
| 177 |
+
parts.append(f"Jenjang: {analysis.jenjang}")
|
| 178 |
+
if analysis.instansi_terkait:
|
| 179 |
+
parts.append("Instansi terkait: " + ", ".join(analysis.instansi_terkait) + ".")
|
| 180 |
+
if analysis.kerangka_hukum_utama:
|
| 181 |
+
parts.append("Kerangka hukum yang berlaku: " + "; ".join(analysis.kerangka_hukum_utama) + ".")
|
| 182 |
+
if analysis.kasus_terkait:
|
| 183 |
+
parts.append(f"Kasus yang dirujuk: {analysis.kasus_terkait}.")
|
| 184 |
+
parts.extend(analysis.anti_drift)
|
| 185 |
+
return " ".join(parts)
|
|
@@ -15,6 +15,7 @@ from ..llm import LLMPool
|
|
| 15 |
from ..tools.citations import extract_citations_with_context, verify_citations
|
| 16 |
from ..tools.pasal import PasalClient
|
| 17 |
from . import peneliti
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
NaskahKind = Literal["pidato", "naskah_akademik", "memo_kebijakan", "siaran_pers"]
|
|
@@ -130,18 +131,35 @@ _PT_TRIGGERS = (
|
|
| 130 |
)
|
| 131 |
|
| 132 |
|
| 133 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
blob = " ".join(part for part in [topic, research_block, extra_instructions or ""] if part).lower()
|
| 135 |
# Pad with spaces so " sd " and " ptn " patterns match at edges.
|
| 136 |
padded = f" {blob} "
|
| 137 |
constraints: list[str] = []
|
| 138 |
|
| 139 |
-
# If the topic mentions a known case, prepend authoritative facts. These
|
| 140 |
-
# override the model's prior — the most consequential domain-drift fix.
|
| 141 |
-
for keywords, facts in _CASE_FACTS:
|
| 142 |
-
if any(keyword in padded for keyword in keywords):
|
| 143 |
-
constraints.append(facts)
|
| 144 |
-
|
| 145 |
has_k12 = any(term in padded for term in _K12_TRIGGERS)
|
| 146 |
has_pt = any(term in padded for term in _PT_TRIGGERS)
|
| 147 |
|
|
@@ -204,6 +222,46 @@ def _derive_domain_constraints(topic: str, research_block: str = "", extra_instr
|
|
| 204 |
return " ".join(constraints)
|
| 205 |
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
def _verify_output_citations(
|
| 208 |
pasal: PasalClient,
|
| 209 |
text: str,
|
|
@@ -254,7 +312,9 @@ def draft(
|
|
| 254 |
memo = peneliti.research(pool, pasal, topic, console=console)
|
| 255 |
research_block = f"\n\nBASIS RISET:\n{memo}\n"
|
| 256 |
|
| 257 |
-
domain_constraints = _derive_domain_constraints(
|
|
|
|
|
|
|
| 258 |
|
| 259 |
user_msg = (
|
| 260 |
f"Topik: {topic}\n"
|
|
|
|
| 15 |
from ..tools.citations import extract_citations_with_context, verify_citations
|
| 16 |
from ..tools.pasal import PasalClient
|
| 17 |
from . import peneliti
|
| 18 |
+
from .domain import classify_domain, render_constraints
|
| 19 |
|
| 20 |
|
| 21 |
NaskahKind = Literal["pidato", "naskah_akademik", "memo_kebijakan", "siaran_pers"]
|
|
|
|
| 131 |
)
|
| 132 |
|
| 133 |
|
| 134 |
+
def _case_fact_overrides(topic: str, research_block: str = "", extra_instructions: str | None = None) -> list[str]:
|
| 135 |
+
"""Authoritative case-fact blocks for known cases — always applied as a fast-path.
|
| 136 |
+
|
| 137 |
+
The classifier may also detect ``kasus_terkait`` and emit relevant guidance,
|
| 138 |
+
but these hand-curated facts are kept as a guaranteed prepend because they
|
| 139 |
+
are higher-fidelity than anything the SMALL model would generate on its own.
|
| 140 |
+
"""
|
| 141 |
+
blob = " ".join(part for part in [topic, research_block, extra_instructions or ""] if part).lower()
|
| 142 |
+
padded = f" {blob} "
|
| 143 |
+
facts: list[str] = []
|
| 144 |
+
for keywords, fact_block in _CASE_FACTS:
|
| 145 |
+
if any(keyword in padded for keyword in keywords):
|
| 146 |
+
facts.append(fact_block)
|
| 147 |
+
return facts
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _keyword_domain_constraints(
|
| 151 |
+
topic: str, research_block: str = "", extra_instructions: str | None = None
|
| 152 |
+
) -> str:
|
| 153 |
+
"""Fallback domain anchor when the SMALL classifier fails or is unavailable.
|
| 154 |
+
|
| 155 |
+
Pattern-matches on a curated trigger list. Less flexible than the classifier
|
| 156 |
+
but deterministic, fast, and offline-friendly.
|
| 157 |
+
"""
|
| 158 |
blob = " ".join(part for part in [topic, research_block, extra_instructions or ""] if part).lower()
|
| 159 |
# Pad with spaces so " sd " and " ptn " patterns match at edges.
|
| 160 |
padded = f" {blob} "
|
| 161 |
constraints: list[str] = []
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
has_k12 = any(term in padded for term in _K12_TRIGGERS)
|
| 164 |
has_pt = any(term in padded for term in _PT_TRIGGERS)
|
| 165 |
|
|
|
|
| 222 |
return " ".join(constraints)
|
| 223 |
|
| 224 |
|
| 225 |
+
def _derive_domain_constraints(
|
| 226 |
+
pool: LLMPool,
|
| 227 |
+
topic: str,
|
| 228 |
+
research_block: str = "",
|
| 229 |
+
extra_instructions: str | None = None,
|
| 230 |
+
*,
|
| 231 |
+
console: Console | None = None,
|
| 232 |
+
) -> str:
|
| 233 |
+
"""Build the domain constraint string for the BIG model's system prompt.
|
| 234 |
+
|
| 235 |
+
Composition:
|
| 236 |
+
1. Authoritative case-fact overrides (keyword fast-path) — these are
|
| 237 |
+
hand-curated and always applied when matching.
|
| 238 |
+
2. SMALL-model domain classifier — produces ``DomainAnalysis`` with
|
| 239 |
+
sektor/jenjang/instansi/anti_drift fields.
|
| 240 |
+
3. Keyword-based fallback — used only when the classifier raises
|
| 241 |
+
(parse error, transport error, or model output that doesn't validate).
|
| 242 |
+
"""
|
| 243 |
+
parts = list(_case_fact_overrides(topic, research_block, extra_instructions))
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
analysis = classify_domain(
|
| 247 |
+
pool,
|
| 248 |
+
topic,
|
| 249 |
+
research_block=research_block,
|
| 250 |
+
extra_instructions=extra_instructions,
|
| 251 |
+
console=console,
|
| 252 |
+
)
|
| 253 |
+
parts.append(render_constraints(analysis))
|
| 254 |
+
except Exception as e: # noqa: BLE001 — classifier may fail in many ways; we always need a result
|
| 255 |
+
if console is not None:
|
| 256 |
+
console.print(
|
| 257 |
+
f"[yellow]penyusun: domain classifier failed ({type(e).__name__}: {e}); "
|
| 258 |
+
f"falling back to keyword anchor[/yellow]"
|
| 259 |
+
)
|
| 260 |
+
parts.append(_keyword_domain_constraints(topic, research_block, extra_instructions))
|
| 261 |
+
|
| 262 |
+
return " ".join(p for p in parts if p)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
def _verify_output_citations(
|
| 266 |
pasal: PasalClient,
|
| 267 |
text: str,
|
|
|
|
| 312 |
memo = peneliti.research(pool, pasal, topic, console=console)
|
| 313 |
research_block = f"\n\nBASIS RISET:\n{memo}\n"
|
| 314 |
|
| 315 |
+
domain_constraints = _derive_domain_constraints(
|
| 316 |
+
pool, topic, research_block, extra_instructions, console=console
|
| 317 |
+
)
|
| 318 |
|
| 319 |
user_msg = (
|
| 320 |
f"Topik: {topic}\n"
|
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
SRC = Path(__file__).resolve().parents[1] / "src"
|
| 9 |
+
if str(SRC) not in sys.path:
|
| 10 |
+
sys.path.insert(0, str(SRC))
|
| 11 |
+
|
| 12 |
+
from legawa.agents.domain import (
|
| 13 |
+
DomainAnalysis,
|
| 14 |
+
_parse_analysis,
|
| 15 |
+
classify_domain,
|
| 16 |
+
render_constraints,
|
| 17 |
+
)
|
| 18 |
+
from legawa.agents.penyusun import _derive_domain_constraints
|
| 19 |
+
from legawa.config import LLMConfig, Settings
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FakeLLM:
|
| 23 |
+
def __init__(self, response: str):
|
| 24 |
+
self.response = response
|
| 25 |
+
self.calls: list[tuple[list[dict], dict]] = []
|
| 26 |
+
|
| 27 |
+
def chat(self, messages, **kwargs):
|
| 28 |
+
self.calls.append((messages, kwargs))
|
| 29 |
+
return self.response
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class FakePool:
|
| 33 |
+
def __init__(self, settings: Settings, small_response: str, big_response: str = ""):
|
| 34 |
+
self.settings = settings
|
| 35 |
+
self.small = FakeLLM(small_response)
|
| 36 |
+
self.big = FakeLLM(big_response)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def make_settings() -> Settings:
|
| 40 |
+
cfg = LLMConfig(
|
| 41 |
+
base_url="http://example.invalid",
|
| 42 |
+
api_key="x",
|
| 43 |
+
model="qwen3",
|
| 44 |
+
temperature=0.3,
|
| 45 |
+
max_tokens=4096,
|
| 46 |
+
)
|
| 47 |
+
return Settings(
|
| 48 |
+
pasal_token="t",
|
| 49 |
+
pasal_base_url="http://pasal.invalid",
|
| 50 |
+
big=cfg,
|
| 51 |
+
small=cfg,
|
| 52 |
+
run_date="2026-04-30",
|
| 53 |
+
corpus_watermark="2026-04-30",
|
| 54 |
+
strict_citations=True,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
VALID_K12_JSON = json.dumps(
|
| 59 |
+
{
|
| 60 |
+
"sektor_utama": "pendidikan_dasar_menengah",
|
| 61 |
+
"jenjang": "dasar_menengah",
|
| 62 |
+
"instansi_terkait": ["Kementerian Pendidikan Dasar dan Menengah", "Komisi X DPR RI"],
|
| 63 |
+
"kasus_terkait": "Kasus Ibam",
|
| 64 |
+
"kerangka_hukum_utama": [
|
| 65 |
+
"Tipikor (UU 31/1999 jo UU 20/2001)",
|
| 66 |
+
"Pengadaan Barang/Jasa (Perpres 16/2018 jo Perpres 12/2021)",
|
| 67 |
+
],
|
| 68 |
+
"rangkuman_konteks": "Topik tentang akuntabilitas pengadaan teknologi pendidikan dasar/menengah.",
|
| 69 |
+
"anti_drift": [
|
| 70 |
+
"JANGAN bergeser ke pendidikan tinggi atau PTN.",
|
| 71 |
+
"Fokus eksklusif pada jenjang SD/SMP/SMA.",
|
| 72 |
+
],
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
VALID_KETENAGAKERJAAN_JSON = json.dumps(
|
| 78 |
+
{
|
| 79 |
+
"sektor_utama": "ketenagakerjaan",
|
| 80 |
+
"jenjang": None,
|
| 81 |
+
"instansi_terkait": ["Kementerian Ketenagakerjaan", "Komisi IX DPR RI"],
|
| 82 |
+
"kasus_terkait": None,
|
| 83 |
+
"kerangka_hukum_utama": ["Ketenagakerjaan (UU 13/2003)", "Cipta Kerja (UU 6/2023)"],
|
| 84 |
+
"rangkuman_konteks": "Perlindungan pekerja alih daya pasca UU Cipta Kerja.",
|
| 85 |
+
"anti_drift": ["Fokus pada hukum ketenagakerjaan."],
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class ParseAnalysisTests(unittest.TestCase):
|
| 91 |
+
def test_parses_clean_json(self) -> None:
|
| 92 |
+
analysis = _parse_analysis(VALID_K12_JSON)
|
| 93 |
+
self.assertEqual(analysis.sektor_utama, "pendidikan_dasar_menengah")
|
| 94 |
+
self.assertEqual(analysis.jenjang, "dasar_menengah")
|
| 95 |
+
self.assertEqual(analysis.kasus_terkait, "Kasus Ibam")
|
| 96 |
+
|
| 97 |
+
def test_strips_code_fence(self) -> None:
|
| 98 |
+
wrapped = "```json\n" + VALID_K12_JSON + "\n```"
|
| 99 |
+
analysis = _parse_analysis(wrapped)
|
| 100 |
+
self.assertEqual(analysis.sektor_utama, "pendidikan_dasar_menengah")
|
| 101 |
+
|
| 102 |
+
def test_isolates_object_when_model_prepends_text(self) -> None:
|
| 103 |
+
wrapped = "Berikut hasil klasifikasi:\n" + VALID_KETENAGAKERJAAN_JSON + "\n\nDemikian."
|
| 104 |
+
analysis = _parse_analysis(wrapped)
|
| 105 |
+
self.assertEqual(analysis.sektor_utama, "ketenagakerjaan")
|
| 106 |
+
self.assertIsNone(analysis.jenjang)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class ClassifyDomainTests(unittest.TestCase):
|
| 110 |
+
def test_classify_returns_analysis_for_valid_response(self) -> None:
|
| 111 |
+
pool = FakePool(make_settings(), small_response=VALID_K12_JSON)
|
| 112 |
+
analysis = classify_domain(
|
| 113 |
+
pool,
|
| 114 |
+
"respons legislatif atas vonis Kasus Ibam dan akuntabilitas Program Digitalisasi Sekolah",
|
| 115 |
+
)
|
| 116 |
+
self.assertIsInstance(analysis, DomainAnalysis)
|
| 117 |
+
self.assertEqual(analysis.sektor_utama, "pendidikan_dasar_menengah")
|
| 118 |
+
self.assertIn("Komisi X DPR RI", analysis.instansi_terkait)
|
| 119 |
+
|
| 120 |
+
def test_classify_raises_on_invalid_json(self) -> None:
|
| 121 |
+
pool = FakePool(make_settings(), small_response="this is not json")
|
| 122 |
+
with self.assertRaises(Exception):
|
| 123 |
+
classify_domain(pool, "topik bebas")
|
| 124 |
+
|
| 125 |
+
def test_classify_passes_research_and_extra_to_prompt(self) -> None:
|
| 126 |
+
pool = FakePool(make_settings(), small_response=VALID_KETENAGAKERJAAN_JSON)
|
| 127 |
+
classify_domain(
|
| 128 |
+
pool,
|
| 129 |
+
"regulasi outsourcing",
|
| 130 |
+
research_block="UU 13/2003 mengatur outsourcing pasal 64-66.",
|
| 131 |
+
extra_instructions="prioritaskan dapil Jawa Barat",
|
| 132 |
+
)
|
| 133 |
+
user_msg = pool.small.calls[0][0][1]["content"]
|
| 134 |
+
self.assertIn("regulasi outsourcing", user_msg)
|
| 135 |
+
self.assertIn("dapil Jawa Barat", user_msg)
|
| 136 |
+
self.assertIn("UU 13/2003", user_msg)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class RenderConstraintsTests(unittest.TestCase):
|
| 140 |
+
def test_renders_full_analysis(self) -> None:
|
| 141 |
+
analysis = _parse_analysis(VALID_K12_JSON)
|
| 142 |
+
rendered = render_constraints(analysis)
|
| 143 |
+
self.assertIn("pendidikan_dasar_menengah", rendered)
|
| 144 |
+
self.assertIn("dasar_menengah", rendered)
|
| 145 |
+
self.assertIn("Komisi X DPR RI", rendered)
|
| 146 |
+
self.assertIn("Kasus Ibam", rendered)
|
| 147 |
+
self.assertIn("JANGAN bergeser ke pendidikan tinggi", rendered)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class DeriveDomainConstraintsTests(unittest.TestCase):
|
| 151 |
+
def test_uses_classifier_output_when_valid(self) -> None:
|
| 152 |
+
pool = FakePool(make_settings(), small_response=VALID_KETENAGAKERJAAN_JSON)
|
| 153 |
+
constraints = _derive_domain_constraints(
|
| 154 |
+
pool, "regulasi outsourcing pasca UU Cipta Kerja"
|
| 155 |
+
)
|
| 156 |
+
self.assertIn("ketenagakerjaan", constraints)
|
| 157 |
+
self.assertIn("Komisi IX DPR RI", constraints)
|
| 158 |
+
# SMALL was called once (the classifier).
|
| 159 |
+
self.assertEqual(len(pool.small.calls), 1)
|
| 160 |
+
|
| 161 |
+
def test_falls_back_to_keyword_anchor_when_classifier_fails(self) -> None:
|
| 162 |
+
pool = FakePool(make_settings(), small_response="not json at all")
|
| 163 |
+
constraints = _derive_domain_constraints(
|
| 164 |
+
pool, "respons atas pengadaan Chromebook sekolah dasar"
|
| 165 |
+
)
|
| 166 |
+
# Classifier ran, failed, fell back to keyword. Keyword path emits this.
|
| 167 |
+
self.assertIn("pendidikan dasar/menengah", constraints)
|
| 168 |
+
|
| 169 |
+
def test_case_facts_prepended_alongside_classifier(self) -> None:
|
| 170 |
+
# Both the keyword-based case-fact override AND the classifier should fire
|
| 171 |
+
# for a Kasus Ibam topic.
|
| 172 |
+
pool = FakePool(make_settings(), small_response=VALID_K12_JSON)
|
| 173 |
+
constraints = _derive_domain_constraints(
|
| 174 |
+
pool,
|
| 175 |
+
"respons legislatif atas vonis Kasus Ibam dan akuntabilitas Program Digitalisasi Sekolah",
|
| 176 |
+
)
|
| 177 |
+
# Authoritative case-fact block (always applied for known cases):
|
| 178 |
+
self.assertIn("FAKTA KASUS IBAM", constraints)
|
| 179 |
+
self.assertIn("Ibrahim Arief", constraints)
|
| 180 |
+
# Classifier output is also present:
|
| 181 |
+
self.assertIn("pendidikan_dasar_menengah", constraints)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
unittest.main()
|