/forgewright:prompt-optimizerfrom forgewright
Compiles and optimizes prompts algorithmically using DSPy (Signatures, Modules, BootstrapFewShot/MIPRO) with measurable evaluation metrics. Excludes manual prompt authoring and CI red-teaming.
Ships in forgewright. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
dspy.Signature, dspy.Module, BootstrapFewShot, MIPRO) driven by deterministic evaluation metrics and paired before/after A/B benchmarks.prompt-engineer), CI red-team execution (llm-tester), session compaction (strategic-compaction), or unsupervised auto-mutation of shared Forgewright skills (kernel/SOLVE.md Step 9).DSPY_MODEL, LLM_API_KEY) per skills/_shared/protocols/model-tier.md (never pin retired model snapshots). Validate every candidate against a held-out eval dataset (evals/ or scripts/runtime/skill_quality.py) with VERIFY.md Schema v2 evidence and require explicit human review before updating shared skill files.You are the Prompt Optimizer, tasked with algorithmically improving application or candidate prompts using the DSPy framework. You translate subjective prompt tweaks into reproducible, metric-gated compiled programs.
dspy.Module pipelinesDSPy (Declarative Self-improving Python) is Stanford's framework for algorithmic prompt optimization. Instead of manually crafting prompts, you:
| Concept | Description |
|---|---|
| Signature | Defines input/output fields for a task |
| Module | Composable building blocks (ChainOfThought, ReAct) |
| Teleprompter | Algorithm that selects/optimizes demonstrations |
| Metric | Function to evaluate output quality |
| Bootstrap | Generate examples from LLM for training |
┌─────────────────────────────────────────────────────────────────────┐
│ 1. INFORMATION GATHERING │
│ Read: │
│ - .forgewright/scoring-lessons.md │
│ - .forgewright/plan-lessons.md │
│ - Failed skill's SKILL.md │
│ - Execution traces from failed runs │
└────────────────────────────┬────────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 2. SETUP DSPy ENVIRONMENT │
│ - Install dspy-ai if needed │
│ - Configure language model │
│ - Load historical failure data │
└────────────────────────────┬────────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 3. DEFINE SIGNATURE & METRIC │
│ - Write dspy.Signature for the failing skill │
│ - Define deterministic metric (compile/valid/pass) │
│ - Create example dataset from traces │
└────────────────────────────┬────────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 4. COMPILE │
│ - Choose teleprompter (BootstrapFewShot, MIPRO, etc.) │
│ - Run compilation with example dataset │
│ - Extract optimized demonstrations │
└────────────────────────────┬────────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 5. PROPOSE CANDIDATE (REVIEW-GATED) │
│ - Save compiled candidate demos to an isolated eval artifact │
│ - Run held-out before/after benchmark and secret/injection scan │
│ - Submit candidate for explicit owner review (never auto-mutate) │
└─────────────────────────────────────────────────────────────────────┘
pip install dspy-ai
import os
import dspy
# Configure provider-neutral language model from environment (per model-tier.md)
model_id = os.getenv("DSPY_MODEL")
if not model_id:
raise ValueError("DSPY_MODEL environment variable required (e.g., provider/model-id)")
lm = dspy.LM(
model_id,
api_key=os.getenv("LLM_API_KEY"),
temperature=0.3,
max_tokens=4096,
)
dspy.settings.configure(lm=lm)
# Optional: Use local Ollama runtime when installed
lm_local = dspy.LM(os.getenv("DSPY_LOCAL_MODEL", "ollama/llama3.1"), api_base="http://localhost:11434")
A signature defines the input/output structure for a task:
class SkillSignature(dspy.Signature):
"""Generate an execution plan based on user requirements."""
requirements = dspy.InputField(desc="The user's request")
context = dspy.InputField(desc="Available context about the project")
plan = dspy.OutputField(desc="A structured execution plan")
confidence = dspy.OutputField(desc="Confidence score 0-1")
desc fields — DSPy uses these to generate prompts| Module | Purpose | When to Use |
|---|---|---|
dspy.ChainOfThought | Adds reasoning step before output | Complex reasoning tasks |
dspy.ReAct | Combines reasoning + action | Tool-use tasks |
dspy.Parallel | Multiple outputs in parallel | Multiple independent outputs |
dspy.MIR | Module Integration & Reasoning | Multi-step workflows |
class PlanWithReasoning(dspy.Signature):
requirements = dspy.InputField()
context = dspy.InputField()
plan = dspy.OutputField()
reasoning = dspy.OutputField(desc="Step-by-step reasoning")
class OptimizationModule(dspy.Module):
def __init__(self):
super().__init__()
self.cot = dspy.ChainOfThought(PlanWithReasoning)
def forward(self, requirements, context):
return self.cot(requirements=requirements, context=context)
| Teleprompter | Best For | Pros | Cons |
|---|---|---|---|
BootstrapFewShot | Small datasets | Fast, simple | Needs good examples |
MIPRO | Large search space | Finds better prompts | Slow, expensive |
COPRO | Prompt-only optimization | No examples needed | Limited improvement |
KNNFewShot | Dynamic example selection | Adapts to query | Slower inference |
from dspy.teleprompt import BootstrapFewShot
# Metric function
def plan_metric(example, pred, trace=None):
"""Evaluate if the plan is good."""
# Plan must compile (no syntax errors)
if not pred.plan:
return 0.0
# Check required fields
required_fields = ['phases', 'success_criteria', 'constraints']
has_all_fields = all(
field in pred.plan.lower()
for field in required_fields
)
# High confidence bonus
confidence_bonus = pred.confidence if hasattr(pred, 'confidence') else 0.5
return 1.0 if has_all_fields else 0.5 + (confidence_bonus * 0.5)
# Compile
teleprompter = BootstrapFewShot(
metric=plan_metric,
max_bootstrapped_demos=4,
max_labeled_demos=8,
max_rounds=1,
)
optimized_module = teleprompter.compile(
OptimizationModule(),
trainset=training_examples,
)
from dspy.teleprompt import MIPRO
teleprompter = MIPRO(
metric=plan_metric,
num_trials=50,
max_bootstrapped_demos=4,
verbose=True,
)
optimized_module = teleprompter.compile(
OptimizationModule(),
trainset=training_examples,
valset=validation_examples,
)
import json
from pathlib import Path
def load_execution_traces(traces_dir: Path):
"""Load traces from failed/successful skill executions."""
examples = []
for trace_file in traces_dir.glob("*.json"):
with open(trace_file) as f:
trace = json.load(f)
# Extract input/output pairs
if trace['outcome'] == 'success':
example = dspy.Example(
requirements=trace['input']['requirements'],
context=trace['input'].get('context', ''),
plan=trace['output']['plan'],
confidence=trace['output'].get('confidence', 1.0),
).with_inputs('requirements', 'context')
examples.append(example)
return examples
def load_plan_lessons(lessons_file: Path):
"""Extract examples from plan-lessons.md."""
examples = []
content = lessons_file.read_text()
# Parse successful plans
# Format: ## Example N\n**Requirements:** ...\n**Plan:** ...
pattern = r'## Example (\d+)\s+\*\*Requirements:\*\* (.+?)\s+\*\*Plan:\*\* (.+?)(?=## |\Z)'
for match in re.finditer(pattern, content, re.DOTALL):
example = dspy.Example(
requirements=match.group(2).strip(),
plan=match.group(3).strip(),
).with_inputs('requirements')
examples.append(example)
return examples
#!/usr/bin/env python3
"""
Forgewright Prompt Optimizer
Usage:
python optimize_skill.py --skill software-engineer
python optimize_skill.py --skill game-designer --teleprompter mipro
"""
import argparse
import json
import os
import sys
from pathlib import Path
from typing import List
import dspy
from dspy.teleprompt import BootstrapFewShot, MIPRO
# Parse arguments
parser = argparse.ArgumentParser(description='Optimize Forgewright skill prompts')
parser.add_argument('--skill', required=True, help='Skill name to optimize')
parser.add_argument('--teleprompter', default='bootstrap',
choices=['bootstrap', 'mipro'], help='Teleprompter to use')
parser.add_argument('--trials', type=int, default=25, help='Number of trials for MIPRO')
args = parser.parse_args()
# Setup DSPy (provider-neutral per model-tier.md)
model_id = os.getenv("DSPY_MODEL")
api_key = os.getenv("LLM_API_KEY")
if not model_id or not api_key:
raise ValueError("DSPY_MODEL and LLM_API_KEY environment variables are required")
lm = dspy.LM(model_id, api_key=api_key)
dspy.settings.configure(lm=lm)
# Load skill definition
skill_path = Path(f'skills/{args.skill}/SKILL.md')
if not skill_path.exists():
raise FileNotFoundError(f"Skill not found: {skill_path}")
skill_content = skill_path.read_text()
# Define signature based on skill type
class SkillSignature(dspy.Signature):
"""Generate skill execution based on requirements."""
requirements = dspy.InputField(desc="The user's request or task")
context = dspy.InputField(desc="Available project context")
output = dspy.OutputField(desc="Skill execution output")
# Define module
class SkillModule(dspy.Module):
def __init__(self):
super().__init__()
self.generate = dspy.ChainOfThought(SkillSignature)
def forward(self, requirements, context):
return self.generate(requirements=requirements, context=context)
# Define metric
def skill_metric(example, pred, trace=None):
"""Evaluate skill output quality."""
score = 0.0
if not pred.output:
return 0.0
# Check for required elements (customize per skill)
output_lower = pred.output.lower()
if 'plan' in output_lower or 'phases' in output_lower:
score += 0.3
if 'success' in output_lower or 'checklist' in output_lower:
score += 0.2
if 'error' not in output_lower and 'fail' not in output_lower:
score += 0.3
if len(pred.output) > 500: # Substantive output
score += 0.2
return min(score, 1.0)
# Load or create training examples
def load_examples():
"""Load training examples from Forgewright history."""
examples = []
# Try to load from plan lessons
lessons_path = Path('.forgewright/plan-lessons.md')
if lessons_path.exists():
# Parse examples from lessons
pass
# Try to load from execution traces
traces_path = Path(f'.forgewright/traces/{args.skill}')
if traces_path.exists():
for trace_file in traces_path.glob('*.json'):
with open(trace_file) as f:
trace = json.load(f)
if trace.get('outcome') == 'success':
ex = dspy.Example(
requirements=trace['input'].get('requirements', ''),
context=trace['input'].get('context', ''),
output=trace['output'].get('result', ''),
).with_inputs('requirements', 'context')
examples.append(ex)
# Fallback: Create synthetic examples
if not examples:
print("⚠️ No examples found, generating synthetic examples...")
# DSPy can bootstrap from a few examples
examples = [
dspy.Example(
requirements="Build a REST API for user management",
context="Python FastAPI project",
output="...",
).with_inputs('requirements', 'context'),
]
return examples
# Compile
def optimize(examples: List[dspy.Example], teleprompter_type: str):
"""Compile optimized module."""
print(f"📊 Training with {len(examples)} examples...")
module = SkillModule()
if teleprompter_type == 'bootstrap':
print("🔧 Using BootstrapFewShot teleprompter...")
teleprompter = BootstrapFewShot(
metric=skill_metric,
max_bootstrapped_demos=4,
max_labeled_demos=8,
)
else:
print("🔧 Using MIPRO teleprompter...")
teleprompter = MIPRO(
metric=skill_metric,
num_trials=args.trials,
max_bootstrapped_demos=4,
verbose=True,
)
optimized = teleprompter.compile(module, trainset=examples)
return optimized
# Extract demonstrations
def extract_demos(optimized_module):
"""Extract optimized demonstrations from compiled module."""
demos = []
# Access the compiled demonstrations
for predictor in optimized_module.predictors():
if hasattr(predictor, 'demos') and predictor.demos:
for demo in predictor.demos:
demos.append({
'input': {k: v for k, v in demo.items()
if k in ['requirements', 'context']},
'output': {k: v for k, v in demo.items()
if k == 'output'},
})
return demos
# Write back to skill file
def update_skill_file(demos: List[dict]):
"""Update SKILL.md with optimized examples."""
if not demos:
print("⚠️ No demonstrations to write")
return
# Format demonstrations
examples_section = "\n\n## Optimized Demonstrations (DSPy Generated)\n\n"
examples_section += "The following examples were algorithmically generated by DSPy to maximize pass rates:\n\n"
for i, demo in enumerate(demos[:4], 1):
examples_section += f"### Example {i}\n\n"
examples_section += f"**Requirements:** {demo['input'].get('requirements', 'N/A')}\n"
if demo['input'].get('context'):
examples_section += f"**Context:** {demo['input']['context']}\n"
examples_section += f"**Output:** {demo['output'].get('output', 'N/A')}\n\n"
# Append to skill file
content = skill_path.read_text()
content += examples_section
skill_path.write_text(content)
print(f"✅ Updated {skill_path} with {len(demos)} demonstrations")
# Main
def main():
print(f"🚀 Optimizing skill: {args.skill}")
# Load examples
examples = load_examples()
print(f"📊 Loaded {len(examples)} training examples")
# Optimize
optimized = optimize(examples, args.teleprompter)
# Extract demonstrations
demos = extract_demos(optimized)
# Write back
update_skill_file(demos)
print("✅ Optimization complete!")
if __name__ == '__main__':
main()
Never auto-mutate shared Forgewright SKILL.md files from an optimizer run (kernel/SOLVE.md Step 9). Instead, emit a candidate artifact and verify uplift against the existing local skill-quality harness (scripts/runtime/skill_quality.py) and project eval scenarios under evals/:
# Inspect existing eval scenarios and validate candidate uplift offline
python3 scripts/runtime/skill_quality.py --help
# Run held-out eval comparisons before proposing any reviewed diff
## Output
When optimization runs, it produces:
.forgewright/prompt-optimizer/ ├── {skill-name}/ │ ├── compiled_module.json # Serialized DSPy module │ ├── demonstrations.json # Optimized few-shot examples │ ├── training_results.json # Compilation metrics │ └── evaluation_results.json # Validation metrics └── logs/ └── optimization_{timestamp}.log
## Best Practices
1. **Start with BootstrapFewShot** — Faster, cheaper, good for most cases
2. **Use MIPRO for complex skills** — When Bootstrap doesn't improve enough
3. **Collect diverse examples** — Cover edge cases, not just happy paths
4. **Define good metrics** — Garbage in, garbage out
5. **Iterate** — Optimization is not one-shot; run multiple rounds
6. **Validate** — Test optimized prompts on held-out examples
## Troubleshooting
| Issue | Solution |
|-------|----------|
| "No examples found" | Generate synthetic examples or manually create a few |
| "Compilation too slow" | Reduce trials, use BootstrapFewShot instead of MIPRO |
| "Quality not improving" | Check metric definition; may need more/better examples |
| "Out of memory" | Reduce batch size, use smaller model for compilation |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub buiphucminhtam/forgewright --plugin forgewright93 skills in this plugin
/3d-spatial-engineerUse for 3D spatial layouts, scene-graph coordinate transforms, greybox blockouts, culling volumes, static batching, and LOD optimization across 3D game engines./accessibility-engineerUse for web WCAG 2.1/2.2 AA accessibility audits, ARIA semantics, keyboard navigation, focus management, contrast verification, and automated axe-core remediation./ai-behavior-engineerUse for game AI and NPC decision systems: finite state machines, behavior trees, utility AI, GOAP, perception, navigation, tactical steering, and encounter tuning.Other plugins' skills for the same job