Optimizers API Reference
Ragas provides optimizers to improve metric prompts through automated optimization. This page documents the available optimizer classes and their configuration.
Overview
Optimizers use annotated datasets with ground truth scores to refine metric prompts, improving accuracy through:
- Instruction optimization: Finding better prompt wording
- Demonstration optimization: Selecting effective few-shot examples
- Search strategies: Exploring the prompt space efficiently
Core Classes
Optimizer
dataclass
Optimizer(metric: Optional[MetricWithLLM] = None, llm: Optional[BaseRagasLLM] = None)
Bases: ABC
Abstract base class for all optimizers.
optimize
abstractmethod
optimize(dataset: SingleMetricAnnotation, loss: Loss, config: Dict[Any, Any], run_config: Optional[RunConfig] = None, batch_size: Optional[int] = None, callbacks: Optional[Callbacks] = None, with_debugging_logs=False, raise_exceptions: bool = True) -> Dict[str, str]
Optimizes the prompts for the given metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
MetricWithLLM
|
The metric to optimize. |
required |
train_data
|
Any
|
The training data. |
required |
config
|
InstructionConfig
|
The training configuration. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, str]
|
The optimized prompts for given chain. |
Source code in src/ragas/optimizers/base.py
GeneticOptimizer
dataclass
GeneticOptimizer(metric: Optional[MetricWithLLM] = None, llm: Optional[BaseRagasLLM] = None)
DSPyOptimizer
dataclass
DSPyOptimizer(metric: Optional[MetricWithLLM] = None, llm: Optional[BaseRagasLLM] = None, num_candidates: int = 10, max_bootstrapped_demos: int = 5, max_labeled_demos: int = 5, init_temperature: float = 1.0, auto: Optional[Literal['light', 'medium', 'heavy']] = 'light', num_threads: Optional[int] = None, max_errors: Optional[int] = None, seed: int = 9, verbose: bool = False, track_stats: bool = True, log_dir: Optional[str] = None, metric_threshold: Optional[float] = None, cache: Optional[CacheInterface] = None)
Bases: Optimizer
Advanced prompt optimizer using DSPy's MIPROv2.
MIPROv2 performs sophisticated prompt optimization by combining: - Instruction optimization (prompt engineering) - Demonstration optimization (few-shot examples) - Combined search over both spaces
Requires: pip install dspy-ai or uv add ragas[dspy]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_candidates
|
int
|
Number of prompt variants to try during optimization. |
10
|
max_bootstrapped_demos
|
int
|
Maximum number of auto-generated examples to use. |
5
|
max_labeled_demos
|
int
|
Maximum number of human-annotated examples to use. |
5
|
init_temperature
|
float
|
Exploration temperature for optimization. |
1.0
|
auto
|
str
|
Automatic configuration level: 'light', 'medium', or 'heavy'. Controls the depth of optimization search. |
'light'
|
num_threads
|
int
|
Number of parallel threads for optimization. |
None
|
max_errors
|
int
|
Maximum errors tolerated during optimization before stopping. |
None
|
seed
|
int
|
Random seed for reproducibility. |
9
|
verbose
|
bool
|
Enable verbose logging during optimization. |
False
|
track_stats
|
bool
|
Track and report optimization statistics. |
True
|
log_dir
|
str
|
Directory for saving optimization logs and progress. |
None
|
metric_threshold
|
float
|
Minimum acceptable metric value to achieve. |
None
|
cache
|
CacheInterface
|
Cache backend for storing optimization results. |
None
|
optimize
optimize(dataset: SingleMetricAnnotation, loss: Loss, config: Dict[Any, Any], run_config: Optional[RunConfig] = None, batch_size: Optional[int] = None, callbacks: Optional[Callbacks] = None, with_debugging_logs: bool = False, raise_exceptions: bool = True) -> Dict[str, str]
Optimize metric prompts using DSPy MIPROv2.
Steps:
- Convert Ragas PydanticPrompt to DSPy Signature
- Create DSPy Module with signature
- Convert dataset to DSPy Examples
- Run MIPROv2 optimization
- Extract optimized prompts
- Convert back to Ragas format
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
SingleMetricAnnotation
|
Annotated dataset with ground truth scores. |
required |
loss
|
Loss
|
Loss function to optimize. |
required |
config
|
Dict[Any, Any]
|
Additional configuration parameters. |
required |
run_config
|
RunConfig
|
Runtime configuration. |
None
|
batch_size
|
int
|
Batch size for evaluation. |
None
|
callbacks
|
Callbacks
|
Langchain callbacks for tracking. |
None
|
with_debugging_logs
|
bool
|
Enable debug logging. |
False
|
raise_exceptions
|
bool
|
Whether to raise exceptions during optimization. |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, str]
|
Optimized prompts for each prompt name. |
Source code in src/ragas/optimizers/dspy_optimizer.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
GeneticOptimizer
Simple evolutionary optimizer for prompt instructions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
max_steps |
int |
50 | Maximum evolution steps |
population_size |
int |
10 | Population size per generation |
mutation_rate |
float |
0.2 | Probability of mutation |
Usage
from ragas.optimizers import GeneticOptimizer
from ragas.config import InstructionConfig
optimizer = GeneticOptimizer(
max_steps=50,
population_size=10,
)
config = InstructionConfig(llm=llm, optimizer=optimizer)
metric.optimize_prompts(dataset, config)
How it Works
- Generates population of prompt variations
- Evaluates each on annotated dataset
- Selects best performers
- Creates next generation via crossover and mutation
- Repeats for max_steps iterations
Pros: Simple, works with limited data Cons: Slower convergence, instruction-only
DSPyOptimizer
Advanced optimizer using DSPy's MIPROv2 algorithm.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
num_candidates |
int |
10 | Number of prompt variants to try |
max_bootstrapped_demos |
int |
5 | Max auto-generated examples |
max_labeled_demos |
int |
5 | Max human-annotated examples |
init_temperature |
float |
1.0 | Exploration temperature (0.0-2.0) |
Usage
from ragas.optimizers import DSPyOptimizer
from ragas.config import InstructionConfig
optimizer = DSPyOptimizer(
num_candidates=10,
max_bootstrapped_demos=5,
max_labeled_demos=5,
)
config = InstructionConfig(llm=llm, optimizer=optimizer)
metric.optimize_prompts(dataset, config)
How it Works
- Generates candidate prompt instructions
- Bootstraps few-shot demonstrations from data
- Selects best human-annotated examples
- Evaluates all combinations on dataset
- Returns best-performing configuration
Learn more about DSPy concepts: - Signatures - DSPy's approach to defining input/output specifications - Optimizers - Algorithms for improving prompts and LM weights - Modules - Building blocks for LLM programs
Pros: Better results, combines instructions + demos Cons: Requires DSPy installation, more LLM calls
Installation
DSPy is an optional dependency:
Cost Estimation
Approximate LLM calls per optimization:
Examples:
- Default config (10, 5, 5): ~335 calls
- Budget config (5, 2, 3): ~164 calls
- Aggressive config (20, 10, 10): ~670 calls
Optimizer Base Class
Bases: ABC
Abstract base class for all optimizers.
optimize
abstractmethod
optimize(dataset: SingleMetricAnnotation, loss: Loss, config: Dict[Any, Any], run_config: Optional[RunConfig] = None, batch_size: Optional[int] = None, callbacks: Optional[Callbacks] = None, with_debugging_logs=False, raise_exceptions: bool = True) -> Dict[str, str]
Optimizes the prompts for the given metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
MetricWithLLM
|
The metric to optimize. |
required |
train_data
|
Any
|
The training data. |
required |
config
|
InstructionConfig
|
The training configuration. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, str]
|
The optimized prompts for given chain. |
Configuration
Both optimizers are used with InstructionConfig:
from ragas.config import InstructionConfig
config = InstructionConfig(
llm=llm, # LLM for optimization
optimizer=optimizer_instance, # Optimizer to use
)
# Use with metric
metric.optimize_prompts(dataset, config)
Dataset Format
Optimizers require annotated datasets with ground truth scores:
from ragas.dataset_schema import (
PromptAnnotation,
SampleAnnotation,
SingleMetricAnnotation
)
# Create annotated sample
prompt_annotation = PromptAnnotation(
prompt_input={"user_input": "...", "response": "..."},
prompt_output={"score": 0.9},
edited_output=None, # Optional: corrected output
)
sample = SampleAnnotation(
metric_input={"user_input": "...", "response": "..."},
metric_output=0.9, # Ground truth score
prompts={"metric_prompt": prompt_annotation},
is_accepted=True, # Include in optimization
)
# Create dataset
dataset = SingleMetricAnnotation(
name="metric_name",
samples=[sample, ...] # 20-50+ samples recommended
)
Loss Functions
Optimizers use loss functions to evaluate prompt quality:
from ragas.losses import MSELoss, HuberLoss
# Mean Squared Error (default)
loss = MSELoss()
# Huber Loss (robust to outliers)
loss = HuberLoss(delta=1.0)
# Use with config
config = InstructionConfig(llm=llm, optimizer=optimizer, loss=loss)
Comparison
| Feature | GeneticOptimizer | DSPyOptimizer |
|---|---|---|
| Installation | Built-in | Requires ragas[dspy] |
| Optimization Target | Instructions only | Instructions + Demos |
| Min Dataset Size | 10+ samples | 20+ samples |
| Typical LLM Calls | 100-500 | 200-700 |
| Accuracy Improvement | +5-8% | +8-12% |
| Best For | Quick optimization | Production metrics |
See Also
- DSPy Optimizer Guide - Detailed usage
- Metric Customization - Creating metrics
- Prompt API Reference - Understanding prompts
Additional Resources
DSPy Documentation: - DSPy Official Documentation - Complete guide to DSPy - MIPROv2 API Reference - Detailed MIPROv2 documentation - DSPy Optimizers Overview - Guide to all DSPy optimizers - DSPy GitHub Repository - Source code and examples
Research Papers: - Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs - MIPROv2 paper