xiaohongshu
xiaohongshu
dspy-simba-optimizer
This skill should be used when the user asks to "optimize with SIMBA", "use Bayesian optimization", "optimize agents with custom feedback", mentions "SIMBA optimizer", "mini-batch optimization", "statistical optimization", "lightweight optimizer", or needs an alternative to MIPROv2/GEPA for progr...
Full skill instructions
Optimize DSPy programs using mini-batch Bayesian optimization with statistical analysis of feedback signals.
| Input | Type | Description |
|---|---|---|
program | dspy.Module | Program to optimize |
trainset | list[dspy.Example] | Training examples |
metric | callable | Returns float or dspy.Prediction(score=..., feedback=...) |
max_steps | int | Number of optimization steps |
bsize | int | Mini-batch size |
| Output | Type | Description |
|---|---|---|
optimized_program | dspy.Module | SIMBA-optimized program |
SIMBA (Stochastic Introspective Mini-Batch Ascent):
Comparison:
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
# Program to optimize
class QAPipeline(dspy.Module):
def __init__(self):
self.generate = dspy.ChainOfThought("question -> answer")
def forward(self, question):
return self.generate(question=question)
# Metric (can return just score or (score, feedback))
def qa_metric(example, pred, trace=None):
correct = example.answer.lower() in pred.answer.lower()
return 1.0 if correct else 0.0
# SIMBA optimizer
optimizer = dspy.SIMBA(
metric=qa_metric,
max_steps=10, # Optimization iterations
bsize=5 # Mini-batch size
)
program = QAPipeline()
compiled = optimizer.compile(program, trainset=trainset)
compiled.save("qa_simba.json")
SIMBA works best with rich feedback:
import dspy
def detailed_metric(example, pred, trace=None):
"""Metric with feedback signal."""
expected = example.answer.lower()
actual = pred.answer.lower()
if expected == actual:
return dspy.Prediction(score=1.0, feedback="Perfect match")
elif expected in actual:
return dspy.Prediction(score=0.7, feedback=f"Contains answer but verbose: '{actual}'")
else:
overlap = len(set(expected.split()) & set(actual.split()))
if overlap > 0:
return dspy.Prediction(score=0.3, feedback=f"Partial overlap: {overlap} words")
return dspy.Prediction(score=0.0, feedback=f"No match. Expected '{expected}'")
optimizer = dspy.SIMBA(
metric=detailed_metric,
max_steps=20, # Optimization iterations
bsize=8 # Mini-batch size
)
compiled = optimizer.compile(program, trainset=trainset)
import dspy
from dspy.evaluate import Evaluate
import logging
logger = logging.getLogger(__name__)
# Define tools as functions
def search(query: str) -> str:
"""Search knowledge base for relevant information."""
retriever = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
results = retriever(query, k=3)
return "\n".join([r['text'] for r in results])
def calculate(expr: str) -> str:
"""Evaluate Python expressions safely."""
try:
with dspy.PythonInterpreter() as interp:
return str(interp.execute(expr))
except Exception as e:
return f"Error: {e}"
class ResearchAgent(dspy.Module):
def __init__(self):
self.agent = dspy.ReAct(
"question -> answer",
tools=[search, calculate]
)
def forward(self, question):
return self.agent(question=question)
def agent_metric(example, pred, trace=None):
"""Rich metric for agent optimization."""
expected = example.answer.lower().strip()
actual = pred.answer.lower().strip() if pred.answer else ""
# Exact match
if expected == actual:
return dspy.Prediction(score=1.0, feedback="Correct answer")
# Partial match
if expected in actual:
return dspy.Prediction(score=0.7, feedback="Answer contains expected result")
# Check key terms
expected_terms = set(expected.split())
actual_terms = set(actual.split())
overlap = len(expected_terms & actual_terms)
if overlap >= len(expected_terms) * 0.5:
return dspy.Prediction(score=0.5, feedback=f"50%+ term overlap")
return dspy.Prediction(score=0.0, feedback=f"Incorrect: expected '{example.answer}'")
def optimize_agent(trainset, devset):
"""Full SIMBA optimization pipeline."""
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
agent = ResearchAgent()
# Baseline evaluation
eval_metric = lambda ex, pred, trace: agent_metric(ex, pred, trace).score
evaluator = dspy.Evaluate(devset=devset, metric=eval_metric, num_threads=4)
baseline = evaluator(agent)
logger.info(f"Baseline: {baseline:.2%}")
# SIMBA optimization
optimizer = dspy.SIMBA(
metric=agent_metric,
max_steps=25, # Optimization iterations
bsize=6 # Mini-batch size
)
compiled = optimizer.compile(agent, trainset=trainset)
# Evaluate optimized
optimized = evaluator(compiled)
logger.info(f"SIMBA optimized: {optimized:.2%}")
compiled.save("research_agent_simba.json")
return compiled
optimizer = dspy.SIMBA(
metric=metric_fn,
max_steps=20, # Optimization iterations
bsize=32, # Mini-batch size (default: 32)
num_candidates=6, # Candidates per iteration (default: 6)
max_demos=4, # Max demos per predictor (default: 4)
temperature_for_sampling=0.2, # Sampling temperature (default: 0.2)
temperature_for_candidates=0.2 # Candidate selection temperature (default: 0.2)
)
dspy.Prediction(score=..., feedback=...) objectsbsize (default 32) and max_steps (default 8) based on dataset sizexiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience