Skip to main content

domainforge_core/projection/dspy/
render.rs

1//! Lower an [`AIOptimizationIR`] to a runnable DSPy program.
2//!
3//! One producer for every artifact: the CLI, the language bindings, and the
4//! tests all render through this module, so their output is byte-identical.
5//! Output is deterministic — the IR is already sorted, and no wall-clock or
6//! random data enters file contents (only the caller-supplied `created_at`).
7//!
8//! Generated Python imports only `dspy` and the Python standard library, so it
9//! is import-clean and `ast.parse`-valid with just `pip install dspy`. The
10//! program is emitted *without* running optimization: `optimize.py` is the
11//! user's compute, and it is where the baseline-vs-optimized comparison and the
12//! regression-threshold gate live — never inside DomainForge.
13
14use super::ir::{AIOptimizationIR, DSPY_TARGET_VERSION};
15
16/// Collapse embedded newlines (a docstring stays readable line-by-line) and
17/// neutralize the two sequences that could break out of a `"""` docstring: a
18/// backslash escape and a literal triple-quote.
19fn doc_safe(s: &str) -> String {
20    s.replace(['\n', '\r'], " ")
21        .replace('\\', "\\\\")
22        .replace("\"\"\"", "\\\"\\\"\\\"")
23}
24
25/// A Python single-quoted-comment-safe rendering for `# ...` header lines.
26fn comment_safe(s: &str) -> String {
27    s.replace(['\n', '\r'], " ")
28}
29
30fn header(ir: &AIOptimizationIR, what: &str) -> String {
31    format!(
32        "# Generated by DomainForge (`--format dspy`) from {}.\n\
33         # {}\n\
34         # Created: {}. Target DSPy API: {}. Do not edit by hand.\n",
35        comment_safe(&ir.model_ref),
36        comment_safe(what),
37        comment_safe(&ir.created_at),
38        DSPY_TARGET_VERSION,
39    )
40}
41
42/// Render a Python list literal of string labels, e.g. `["allow", "deny"]`.
43fn label_list(labels: &[String]) -> String {
44    let items = labels
45        .iter()
46        .map(|l| format!("\"{}\"", l.replace('\\', "\\\\").replace('"', "\\\"")))
47        .collect::<Vec<_>>()
48        .join(", ");
49    format!("[{items}]")
50}
51
52/// `program.py`: the DSPy signature (the authority-decision capability) and the
53/// module that wraps it under the configured strategy.
54pub fn program(ir: &AIOptimizationIR) -> String {
55    let labels_csv = ir.decision_labels.join(", ");
56
57    let mut policies = String::new();
58    if ir.policy_lines.is_empty() {
59        policies.push_str("    (no authority policies were declared)\n");
60    } else {
61        for line in &ir.policy_lines {
62            policies.push_str(&format!("    - {}\n", doc_safe(line)));
63        }
64    }
65
66    let mut s = header(
67        ir,
68        "Authority-decision signature + module. Optimization is NOT run here.",
69    );
70    s.push_str("import dspy\n\n");
71    s.push_str(&format!(
72        "# The closed set of decision labels this capability ranges over.\n\
73         DECISION_LABELS = {}\n\n",
74        label_list(&ir.decision_labels)
75    ));
76    s.push_str(&format!(
77        "class {sig}(dspy.Signature):\n\
78         \x20   \"\"\"Decide the authorization outcome for a natural-language question about the\n\
79         \x20   \"{model}\" domain model. Answer strictly from the governing policies below; if no\n\
80         \x20   policy applies, answer \"unknown\" and do NOT infer permission.\n\n\
81         \x20   Capability id: {cap}.\n\n\
82         \x20   Governing policies:\n\
83         {policies}\
84         \x20   \"\"\"\n\n\
85         \x20   question: str = dspy.InputField(\n\
86         \x20       desc=\"A natural-language authorization question about the domain model.\"\n\
87         \x20   )\n\
88         \x20   decision: str = dspy.OutputField(\n\
89         \x20       desc=\"The authorization outcome; one of: {labels}.\"\n\
90         \x20   )\n\n\n",
91        sig = ir.signature_name,
92        model = doc_safe(&ir.model_ref),
93        cap = ir.capability_id,
94        policies = policies,
95        labels = labels_csv,
96    ));
97    s.push_str(&format!(
98        "class {prog}(dspy.Module):\n\
99         \x20   \"\"\"Wraps {sig} in a {call} module ({strategy} strategy).\"\"\"\n\n\
100         \x20   def __init__(self):\n\
101         \x20       super().__init__()\n\
102         \x20       self.decide = {call}({sig})\n\n\
103         \x20   def forward(self, question):\n\
104         \x20       return self.decide(question=question)\n",
105        prog = ir.program_name,
106        sig = ir.signature_name,
107        call = ir.dspy_module_call(),
108        strategy = ir.module_strategy,
109    ));
110    s
111}
112
113/// `metric.py`: decision-label agreement. No imports — pure standard Python so
114/// it stays import-clean under any environment.
115pub fn metric(ir: &AIOptimizationIR) -> String {
116    let mut s = header(
117        ir,
118        "Metric: decision-label agreement between the prediction and the gold label.",
119    );
120    s.push('\n');
121    s.push_str(&format!(
122        "# The closed set of decision labels, duplicated here so the metric is\n\
123         # self-contained (importable without the program module).\n\
124         DECISION_LABELS = {}\n\n\n",
125        label_list(&ir.decision_labels)
126    ));
127    s.push_str(
128        "def _normalize(text):\n\
129         \x20   \"\"\"Map free text onto one of DECISION_LABELS, else its lowercased form.\"\"\"\n\
130         \x20   text = str(text).strip().lower()\n\
131         \x20   for label in DECISION_LABELS:\n\
132         \x20       if label in text:\n\
133         \x20           return label\n\
134         \x20   return text\n\n\n",
135    );
136    s.push_str(
137        "def decision_match(example, prediction, trace=None):\n\
138         \x20   \"\"\"True when the predicted decision agrees with the resolver-grounded label.\"\"\"\n\
139         \x20   gold = _normalize(getattr(example, \"decision\", \"\"))\n\
140         \x20   pred = _normalize(getattr(prediction, \"decision\", \"\"))\n\
141         \x20   return gold == pred\n",
142    );
143    s
144}
145
146/// `optimize.py`: load the referenced ai-learning splits, evaluate a baseline,
147/// compile an optimized program, and enforce the declared regression gate. This
148/// is the user's compute — DomainForge emits it but never runs it.
149pub fn optimize(ir: &AIOptimizationIR) -> String {
150    let mut s = header(
151        ir,
152        "Baseline-vs-optimized comparison + regression gate. Run this yourself (needs an LM).",
153    );
154    s.push_str(&format!(
155        "import json\n\
156         import os\n\n\
157         import dspy\n\n\
158         from program import {prog}\n\
159         from metric import decision_match\n\n\
160         CONFIG_PATH = os.path.join(os.path.dirname(__file__), \"dspy.config.json\")\n\n\n",
161        prog = ir.program_name,
162    ));
163    s.push_str(
164        "def load_config():\n\
165         \x20   with open(CONFIG_PATH, \"r\", encoding=\"utf-8\") as handle:\n\
166         \x20       return json.load(handle)\n\n\n\
167         def _user_question(record):\n\
168         \x20   for message in record.get(\"messages\", []):\n\
169         \x20       if message.get(\"role\") == \"user\":\n\
170         \x20           return message.get(\"content\", \"\")\n\
171         \x20   return \"\"\n\n\n\
172         def load_examples(path, family):\n\
173         \x20   \"\"\"Build dspy.Example rows from an ai-learning LLM-dataset JSONL file.\n\n\
174         \x20   The rows are REFERENCED, never copied: run `domainforge project --format\n\
175         \x20   ai-learning` to produce them at the path recorded in dspy.config.json.\n\
176         \x20   \"\"\"\n\
177         \x20   examples = []\n\
178         \x20   with open(path, \"r\", encoding=\"utf-8\") as handle:\n\
179         \x20       for line in handle:\n\
180         \x20           line = line.strip()\n\
181         \x20           if not line:\n\
182         \x20               continue\n\
183         \x20           record = json.loads(line)\n\
184         \x20           metadata = record.get(\"metadata\", {})\n\
185         \x20           if metadata.get(\"family\") != family:\n\
186         \x20               continue\n\
187         \x20           label = metadata.get(\"label\")\n\
188         \x20           if label is None:\n\
189         \x20               continue\n\
190         \x20           question = _user_question(record)\n\
191         \x20           example = dspy.Example(question=question, decision=label).with_inputs(\"question\")\n\
192         \x20           examples.append(example)\n\
193         \x20   return examples\n\n\n\
194         def evaluate(program, examples):\n\
195         \x20   if not examples:\n\
196         \x20       return 0.0\n\
197         \x20   correct = 0\n\
198         \x20   for example in examples:\n\
199         \x20       prediction = program(question=example.question)\n\
200         \x20       if decision_match(example, prediction):\n\
201         \x20           correct += 1\n\
202         \x20   return correct / len(examples)\n\n\n",
203    );
204    s.push_str(&format!(
205        "def build_optimizer(optimizer_config):\n\
206         \x20   name = optimizer_config[\"name\"]\n\
207         \x20   if name == \"LabeledFewShot\":\n\
208         \x20       return dspy.LabeledFewShot(k=optimizer_config[\"max_labeled_demos\"])\n\
209         \x20   return dspy.BootstrapFewShot(\n\
210         \x20       metric=decision_match,\n\
211         \x20       max_bootstrapped_demos=optimizer_config[\"max_bootstrapped_demos\"],\n\
212         \x20       max_labeled_demos=optimizer_config[\"max_labeled_demos\"],\n\
213         \x20   )\n\n\n\
214         def main():\n\
215         \x20   if dspy.settings.lm is None:\n\
216         \x20       raise SystemExit(\n\
217         \x20           \"No DSPy LM configured. Configure one (e.g. \"\n\
218         \x20           \"dspy.configure(lm=dspy.LM(...))) before running optimize.py; \"\n\
219         \x20           \"DomainForge stays vendor-neutral and does not pick a provider for you.\"\n\
220         \x20       )\n\
221         \x20   config = load_config()\n\
222         \x20   dataset = config[\"dataset\"]\n\
223         \x20   root = os.path.join(os.path.dirname(__file__), dataset[\"root\"])\n\
224         \x20   trainset = load_examples(os.path.join(root, dataset[\"train\"]), dataset[\"family\"])\n\
225         \x20   devset = load_examples(os.path.join(root, dataset[\"dev\"]), dataset[\"family\"])\n\n\
226         \x20   baseline = {prog}()\n\
227         \x20   baseline_score = evaluate(baseline, devset)\n\n\
228         \x20   optimizer = build_optimizer(config[\"optimizer\"])\n\
229         \x20   optimized = optimizer.compile({prog}(), trainset=trainset)\n\
230         \x20   optimized_score = evaluate(optimized, devset)\n\n\
231         \x20   threshold = config[\"optimizer\"][\"regression_threshold\"]\n\
232         \x20   print(\"baseline dev score:\", baseline_score)\n\
233         \x20   print(\"optimized dev score:\", optimized_score)\n\
234         \x20   if optimized_score < baseline_score - threshold:\n\
235         \x20       raise SystemExit(\n\
236         \x20           \"DSPy optimization regressed: optimized %.4f < baseline %.4f - threshold %.4f\"\n\
237         \x20           % (optimized_score, baseline_score, threshold)\n\
238         \x20       )\n\
239         \x20   return optimized\n\n\n\
240         if __name__ == \"__main__\":\n\
241         \x20   main()\n",
242        prog = ir.program_name,
243    ));
244    s
245}
246
247/// `dspy.config.json`: the machine-readable stamp — signature, module strategy,
248/// dataset references (paths into the ai-learning output, never copies), the
249/// metric, the optimizer + regression gate, and the provenance carried verbatim
250/// from the ai-learning family.
251pub fn config(ir: &AIOptimizationIR) -> Result<String, String> {
252    let value = serde_json::json!({
253        "capability_id": ir.capability_id,
254        "target_dspy_version": DSPY_TARGET_VERSION,
255        "generator_version": ir.generator_version,
256        "created_at": ir.created_at,
257        "signature": {
258            "name": ir.signature_name,
259            "module_strategy": ir.module_strategy,
260            "inputs": ["question"],
261            "output": "decision",
262            "decision_labels": ir.decision_labels,
263        },
264        "metric": {
265            "name": ir.metric_name,
266            "kind": "decision_label_agreement",
267        },
268        "dataset": {
269            "root": ir.dataset.root,
270            "train": ir.dataset.train,
271            "dev": ir.dataset.dev,
272            "family": ir.dataset.family,
273            "note": "Paths reference the `--format ai-learning` output; generate it first. \
274                     DomainForge never copies example data.",
275        },
276        "optimizer": {
277            "name": ir.optimizer.name,
278            "max_bootstrapped_demos": ir.optimizer.max_bootstrapped_demos,
279            "max_labeled_demos": ir.optimizer.max_labeled_demos,
280            "regression_threshold": ir.optimizer.regression_threshold,
281        },
282        "provenance": ir.provenance,
283    });
284    serde_json::to_string_pretty(&value)
285        .map(|s| s + "\n")
286        .map_err(|e| format!("dspy config serialization failed: {e}"))
287}
288
289/// `README.md`: package layout and the scope boundary the plan requires.
290pub fn readme(ir: &AIOptimizationIR) -> String {
291    format!(
292        "# DomainForge DSPy optimization program\n\n\
293         Generated from `{model}` at {created} (target DSPy API `{version}`).\n\n\
294         This package turns the model's authority policies into a runnable\n\
295         [DSPy](https://dspy.ai/) program plus its optimizer config. DomainForge\n\
296         emits the *program and configuration only*: it does **not** run\n\
297         optimization. The baseline-vs-optimized comparison and the\n\
298         regression-threshold gate live in the emitted `optimize.py`, which is\n\
299         your compute to run.\n\n\
300         ## Layout\n\n\
301         - `program.py` — the `{sig}` signature (the authority-decision\n  \
302         capability, its prompt carrying the governing policies) and the\n  \
303         `{prog}` module ({strategy} strategy).\n\
304         - `metric.py` — `{metric}`, decision-label agreement.\n\
305         - `optimize.py` — loads the referenced ai-learning splits, evaluates a\n  \
306         baseline, compiles an optimized program, and enforces the regression\n  \
307         gate.\n\
308         - `dspy.config.json` — signature, dataset references, optimizer config,\n  \
309         and provenance.\n\n\
310         ## Examples are referenced, never copied\n\n\
311         `dspy.config.json` records the dataset paths under `dataset.root`\n\
312         (default `{root}`): `{train}` (train) and `{dev}` (dev). These are the\n\
313         exact files `domainforge project --format ai-learning` emits for the\n\
314         same model, so the DSPy examples and the LLM dataset can never diverge.\n\
315         Generate them first:\n\n\
316         ```bash\n\
317         domainforge project --format ai-learning --recipe <recipe.json> model.sea {root}\n\
318         ```\n\n\
319         ## Make it runnable\n\n\
320         1. `pip install dspy`.\n\
321         2. Configure an LM (DomainForge stays vendor-neutral): e.g.\n   \
322         `dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))`.\n\
323         3. Generate the ai-learning dataset (above), then `python optimize.py`.\n\n\
324         Provenance: capability id `{cap}`, source model hash `{hash}`,\n\
325         generator `domainforge {gen}`.\n",
326        model = ir.model_ref,
327        created = ir.created_at,
328        version = DSPY_TARGET_VERSION,
329        sig = ir.signature_name,
330        prog = ir.program_name,
331        strategy = ir.module_strategy,
332        metric = ir.metric_name,
333        root = ir.dataset.root,
334        train = ir.dataset.train,
335        dev = ir.dataset.dev,
336        cap = ir.capability_id,
337        hash = ir.model_hash,
338        gen = ir.generator_version,
339    )
340}