use super::ir::{AIOptimizationIR, DSPY_TARGET_VERSION};
fn doc_safe(s: &str) -> String {
s.replace(['\n', '\r'], " ")
.replace('\\', "\\\\")
.replace("\"\"\"", "\\\"\\\"\\\"")
}
fn comment_safe(s: &str) -> String {
s.replace(['\n', '\r'], " ")
}
fn header(ir: &AIOptimizationIR, what: &str) -> String {
format!(
"# Generated by DomainForge (`--format dspy`) from {}.\n\
# {}\n\
# Created: {}. Target DSPy API: {}. Do not edit by hand.\n",
comment_safe(&ir.model_ref),
comment_safe(what),
comment_safe(&ir.created_at),
DSPY_TARGET_VERSION,
)
}
fn label_list(labels: &[String]) -> String {
let items = labels
.iter()
.map(|l| format!("\"{}\"", l.replace('\\', "\\\\").replace('"', "\\\"")))
.collect::<Vec<_>>()
.join(", ");
format!("[{items}]")
}
pub fn program(ir: &AIOptimizationIR) -> String {
let labels_csv = ir.decision_labels.join(", ");
let mut policies = String::new();
if ir.policy_lines.is_empty() {
policies.push_str(" (no authority policies were declared)\n");
} else {
for line in &ir.policy_lines {
policies.push_str(&format!(" - {}\n", doc_safe(line)));
}
}
let mut s = header(
ir,
"Authority-decision signature + module. Optimization is NOT run here.",
);
s.push_str("import dspy\n\n");
s.push_str(&format!(
"# The closed set of decision labels this capability ranges over.\n\
DECISION_LABELS = {}\n\n",
label_list(&ir.decision_labels)
));
s.push_str(&format!(
"class {sig}(dspy.Signature):\n\
\x20 \"\"\"Decide the authorization outcome for a natural-language question about the\n\
\x20 \"{model}\" domain model. Answer strictly from the governing policies below; if no\n\
\x20 policy applies, answer \"unknown\" and do NOT infer permission.\n\n\
\x20 Capability id: {cap}.\n\n\
\x20 Governing policies:\n\
{policies}\
\x20 \"\"\"\n\n\
\x20 question: str = dspy.InputField(\n\
\x20 desc=\"A natural-language authorization question about the domain model.\"\n\
\x20 )\n\
\x20 decision: str = dspy.OutputField(\n\
\x20 desc=\"The authorization outcome; one of: {labels}.\"\n\
\x20 )\n\n\n",
sig = ir.signature_name,
model = doc_safe(&ir.model_ref),
cap = ir.capability_id,
policies = policies,
labels = labels_csv,
));
s.push_str(&format!(
"class {prog}(dspy.Module):\n\
\x20 \"\"\"Wraps {sig} in a {call} module ({strategy} strategy).\"\"\"\n\n\
\x20 def __init__(self):\n\
\x20 super().__init__()\n\
\x20 self.decide = {call}({sig})\n\n\
\x20 def forward(self, question):\n\
\x20 return self.decide(question=question)\n",
prog = ir.program_name,
sig = ir.signature_name,
call = ir.dspy_module_call(),
strategy = ir.module_strategy,
));
s
}
pub fn metric(ir: &AIOptimizationIR) -> String {
let mut s = header(
ir,
"Metric: decision-label agreement between the prediction and the gold label.",
);
s.push('\n');
s.push_str(&format!(
"# The closed set of decision labels, duplicated here so the metric is\n\
# self-contained (importable without the program module).\n\
DECISION_LABELS = {}\n\n\n",
label_list(&ir.decision_labels)
));
s.push_str(
"def _normalize(text):\n\
\x20 \"\"\"Map free text onto one of DECISION_LABELS, else its lowercased form.\"\"\"\n\
\x20 text = str(text).strip().lower()\n\
\x20 for label in DECISION_LABELS:\n\
\x20 if label in text:\n\
\x20 return label\n\
\x20 return text\n\n\n",
);
s.push_str(
"def decision_match(example, prediction, trace=None):\n\
\x20 \"\"\"True when the predicted decision agrees with the resolver-grounded label.\"\"\"\n\
\x20 gold = _normalize(getattr(example, \"decision\", \"\"))\n\
\x20 pred = _normalize(getattr(prediction, \"decision\", \"\"))\n\
\x20 return gold == pred\n",
);
s
}
pub fn optimize(ir: &AIOptimizationIR) -> String {
let mut s = header(
ir,
"Baseline-vs-optimized comparison + regression gate. Run this yourself (needs an LM).",
);
s.push_str(&format!(
"import json\n\
import os\n\n\
import dspy\n\n\
from program import {prog}\n\
from metric import decision_match\n\n\
CONFIG_PATH = os.path.join(os.path.dirname(__file__), \"dspy.config.json\")\n\n\n",
prog = ir.program_name,
));
s.push_str(
"def load_config():\n\
\x20 with open(CONFIG_PATH, \"r\", encoding=\"utf-8\") as handle:\n\
\x20 return json.load(handle)\n\n\n\
def _user_question(record):\n\
\x20 for message in record.get(\"messages\", []):\n\
\x20 if message.get(\"role\") == \"user\":\n\
\x20 return message.get(\"content\", \"\")\n\
\x20 return \"\"\n\n\n\
def load_examples(path, family):\n\
\x20 \"\"\"Build dspy.Example rows from an ai-learning LLM-dataset JSONL file.\n\n\
\x20 The rows are REFERENCED, never copied: run `domainforge project --format\n\
\x20 ai-learning` to produce them at the path recorded in dspy.config.json.\n\
\x20 \"\"\"\n\
\x20 examples = []\n\
\x20 with open(path, \"r\", encoding=\"utf-8\") as handle:\n\
\x20 for line in handle:\n\
\x20 line = line.strip()\n\
\x20 if not line:\n\
\x20 continue\n\
\x20 record = json.loads(line)\n\
\x20 metadata = record.get(\"metadata\", {})\n\
\x20 if metadata.get(\"family\") != family:\n\
\x20 continue\n\
\x20 label = metadata.get(\"label\")\n\
\x20 if label is None:\n\
\x20 continue\n\
\x20 question = _user_question(record)\n\
\x20 example = dspy.Example(question=question, decision=label).with_inputs(\"question\")\n\
\x20 examples.append(example)\n\
\x20 return examples\n\n\n\
def evaluate(program, examples):\n\
\x20 if not examples:\n\
\x20 return 0.0\n\
\x20 correct = 0\n\
\x20 for example in examples:\n\
\x20 prediction = program(question=example.question)\n\
\x20 if decision_match(example, prediction):\n\
\x20 correct += 1\n\
\x20 return correct / len(examples)\n\n\n",
);
s.push_str(&format!(
"def build_optimizer(optimizer_config):\n\
\x20 name = optimizer_config[\"name\"]\n\
\x20 if name == \"LabeledFewShot\":\n\
\x20 return dspy.LabeledFewShot(k=optimizer_config[\"max_labeled_demos\"])\n\
\x20 return dspy.BootstrapFewShot(\n\
\x20 metric=decision_match,\n\
\x20 max_bootstrapped_demos=optimizer_config[\"max_bootstrapped_demos\"],\n\
\x20 max_labeled_demos=optimizer_config[\"max_labeled_demos\"],\n\
\x20 )\n\n\n\
def main():\n\
\x20 if dspy.settings.lm is None:\n\
\x20 raise SystemExit(\n\
\x20 \"No DSPy LM configured. Configure one (e.g. \"\n\
\x20 \"dspy.configure(lm=dspy.LM(...))) before running optimize.py; \"\n\
\x20 \"DomainForge stays vendor-neutral and does not pick a provider for you.\"\n\
\x20 )\n\
\x20 config = load_config()\n\
\x20 dataset = config[\"dataset\"]\n\
\x20 root = os.path.join(os.path.dirname(__file__), dataset[\"root\"])\n\
\x20 trainset = load_examples(os.path.join(root, dataset[\"train\"]), dataset[\"family\"])\n\
\x20 devset = load_examples(os.path.join(root, dataset[\"dev\"]), dataset[\"family\"])\n\n\
\x20 baseline = {prog}()\n\
\x20 baseline_score = evaluate(baseline, devset)\n\n\
\x20 optimizer = build_optimizer(config[\"optimizer\"])\n\
\x20 optimized = optimizer.compile({prog}(), trainset=trainset)\n\
\x20 optimized_score = evaluate(optimized, devset)\n\n\
\x20 threshold = config[\"optimizer\"][\"regression_threshold\"]\n\
\x20 print(\"baseline dev score:\", baseline_score)\n\
\x20 print(\"optimized dev score:\", optimized_score)\n\
\x20 if optimized_score < baseline_score - threshold:\n\
\x20 raise SystemExit(\n\
\x20 \"DSPy optimization regressed: optimized %.4f < baseline %.4f - threshold %.4f\"\n\
\x20 % (optimized_score, baseline_score, threshold)\n\
\x20 )\n\
\x20 return optimized\n\n\n\
if __name__ == \"__main__\":\n\
\x20 main()\n",
prog = ir.program_name,
));
s
}
pub fn config(ir: &AIOptimizationIR) -> Result<String, String> {
let value = serde_json::json!({
"capability_id": ir.capability_id,
"target_dspy_version": DSPY_TARGET_VERSION,
"generator_version": ir.generator_version,
"created_at": ir.created_at,
"signature": {
"name": ir.signature_name,
"module_strategy": ir.module_strategy,
"inputs": ["question"],
"output": "decision",
"decision_labels": ir.decision_labels,
},
"metric": {
"name": ir.metric_name,
"kind": "decision_label_agreement",
},
"dataset": {
"root": ir.dataset.root,
"train": ir.dataset.train,
"dev": ir.dataset.dev,
"family": ir.dataset.family,
"note": "Paths reference the `--format ai-learning` output; generate it first. \
DomainForge never copies example data.",
},
"optimizer": {
"name": ir.optimizer.name,
"max_bootstrapped_demos": ir.optimizer.max_bootstrapped_demos,
"max_labeled_demos": ir.optimizer.max_labeled_demos,
"regression_threshold": ir.optimizer.regression_threshold,
},
"provenance": ir.provenance,
});
serde_json::to_string_pretty(&value)
.map(|s| s + "\n")
.map_err(|e| format!("dspy config serialization failed: {e}"))
}
pub fn readme(ir: &AIOptimizationIR) -> String {
format!(
"# DomainForge DSPy optimization program\n\n\
Generated from `{model}` at {created} (target DSPy API `{version}`).\n\n\
This package turns the model's authority policies into a runnable\n\
[DSPy](https://dspy.ai/) program plus its optimizer config. DomainForge\n\
emits the *program and configuration only*: it does **not** run\n\
optimization. The baseline-vs-optimized comparison and the\n\
regression-threshold gate live in the emitted `optimize.py`, which is\n\
your compute to run.\n\n\
## Layout\n\n\
- `program.py` — the `{sig}` signature (the authority-decision\n \
capability, its prompt carrying the governing policies) and the\n \
`{prog}` module ({strategy} strategy).\n\
- `metric.py` — `{metric}`, decision-label agreement.\n\
- `optimize.py` — loads the referenced ai-learning splits, evaluates a\n \
baseline, compiles an optimized program, and enforces the regression\n \
gate.\n\
- `dspy.config.json` — signature, dataset references, optimizer config,\n \
and provenance.\n\n\
## Examples are referenced, never copied\n\n\
`dspy.config.json` records the dataset paths under `dataset.root`\n\
(default `{root}`): `{train}` (train) and `{dev}` (dev). These are the\n\
exact files `domainforge project --format ai-learning` emits for the\n\
same model, so the DSPy examples and the LLM dataset can never diverge.\n\
Generate them first:\n\n\
```bash\n\
domainforge project --format ai-learning --recipe <recipe.json> model.sea {root}\n\
```\n\n\
## Make it runnable\n\n\
1. `pip install dspy`.\n\
2. Configure an LM (DomainForge stays vendor-neutral): e.g.\n \
`dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))`.\n\
3. Generate the ai-learning dataset (above), then `python optimize.py`.\n\n\
Provenance: capability id `{cap}`, source model hash `{hash}`,\n\
generator `domainforge {gen}`.\n",
model = ir.model_ref,
created = ir.created_at,
version = DSPY_TARGET_VERSION,
sig = ir.signature_name,
prog = ir.program_name,
strategy = ir.module_strategy,
metric = ir.metric_name,
root = ir.dataset.root,
train = ir.dataset.train,
dev = ir.dataset.dev,
cap = ir.capability_id,
hash = ir.model_hash,
gen = ir.generator_version,
)
}