Skip to main content
Bayesian Search uses Bayesian optimization (via Optuna) to intelligently explore the space of few-shot prompt configurations. Instead of randomly trying different prompts, it learns from each trial to make smarter choices about which examples and configurations to test next.

✅ Best For

  • Few-shot learning tasks
  • Efficient exploration
  • Structured Q&A or classification
  • Limited evaluation budget

❌ Not Ideal For

  • Tasks without examples in dataset
  • Purely zero-shot scenarios
  • Very creative/open-ended tasks
  • Tiny datasets (< 10 examples)

How It Works

  1. Few-Shot Selection: Intelligently samples different numbers and combinations of examples from your dataset
  2. Template Optimization: Can automatically infer the best way to format examples (optional)
  3. Bayesian Learning: Uses previous trial results to guide future selections
  4. Efficient Search: Converges faster than random search by learning from history
1

Initialize Search Space

Define range of few-shot examples (e.g., 2-8 examples) and other configurations
2

Sample Configuration

Bayesian optimizer suggests number of examples and which ones to use
3

Build Prompt

Format selected examples and combine with base prompt
4

Evaluate

Generate outputs and score them on eval subset
5

Update & Repeat

Optimizer learns from results and suggests next configuration

Basic Usage


Configuration Parameters

Search Space

int
default:"2"
Minimum number of few-shot examples to try
int
default:"8"
Maximum number of few-shot examples to try
bool
default:"false"
Whether the same example can be used multiple times in few-shot block
List[int]
default:"[]"
Specific example indices that must always be included

Optimization Control

int
default:"10"
Number of different configurations to try. More trials = better results but higher cost.
int
default:"42"
Random seed for reproducibility
str
default:"maximize"
Optimization direction. Use "maximize" for scores, "minimize" for loss/error rates.

Model Configuration

str
default:"gpt-4o-mini"
Model used to generate outputs during optimization
dict
default:"{}"
Additional arguments passed to the inference model

Example Formatting

str
default:"None"
Template string for formatting examples using Python .format() syntax
List[str]
default:"None"
List of fields to include when no template is provided
Dict[str, str]
default:"{}"
Custom labels for fields in examples
str
default:"\\n"
String used to separate multiple examples in the few-shot block
str
default:"append"
Where to place few-shot examples: "append" (after base prompt) or "prepend" (before)
str
default:"None"
Optional title/header for the few-shot examples section

Teacher-Guided Template Inference

bool
default:"false"
Use a teacher model to automatically infer the best example format from your data
str
default:"gpt-5"
Powerful model used for template inference
dict
default:"{'temperature': 1.0, 'max_tokens': 16000}"
Arguments for the teacher model
int
default:"8"
Number of dataset examples to show the teacher for template inference
Template inference is powerful but costs extra API calls. Use it when you’re unsure how to format examples.

Evaluation Controls

int
default:"None"
Number of examples to evaluate per trial (for speed). If None, uses entire dataset.
str
default:"random"
How to select eval subset: "random", "first", or "all"

Underlying Research

Bayesian Search builds on established principles of Bayesian optimization, adapted for the unique challenges of prompt engineering.
  • Core Concept: The method is detailed in papers like “A Bayesian approach for prompt optimization in pre-trained models”, which explores mapping discrete prompts to continuous embeddings for more efficient searching.
  • Few-Shot Learning: Its application in few-shot scenarios is highlighted by tools like Comet’s OPik, which features a “Few-Shot Bayesian Optimizer”.
  • Advanced Implementations: Recent research, such as “Searching for Optimal Solutions with LLMs via Bayesian Optimization (BOPRO)”, investigates using Bayesian optimization to navigate complex LLM search spaces. The popular BayesianOptimization library on GitHub provides the foundational Gaussian process-based modeling.
This approach is noted for its efficiency in prominent frameworks like DSPy and is recognized in surveys for its effectiveness in few-shot learning contexts.

Advanced Examples

With Automatic Template Inference

Let the teacher model determine the best example format:

With Custom Example Formatting

Full control over example formatting:

With Custom Prompt Builder

Control how few-shot examples integrate with base prompt:

With Fixed Examples

Always include certain critical examples:

Understanding the Results

Analyzing Optimization History

Extracting Best Configuration


Performance Tips

Begin with n_trials=10 to validate your setup, then increase to 20-30 for production.
Set eval_subset_size=20 when you have 50+ examples to speed up optimization significantly.
  • Classification: min_examples=2, max_examples=5
  • Complex reasoning: min_examples=3, max_examples=8
  • Creative tasks: min_examples=1, max_examples=4
Run a quick optimization with infer_example_template_via_teacher=True, save the inferred template, then use it explicitly in future runs to save costs.

Common Patterns

Question Answering with Context

Text Classification

Data Extraction


Troubleshooting

Problem: KeyError when formatting examplesSolution: Ensure all fields in example_template exist in your dataset examples. Use example_template_fields to explicitly list available fields.
Problem: Scores stop improving after few trialsSolution:
  • Increase max_examples to explore larger few-shot sizes
  • Try infer_example_template_via_teacher=True
  • Check if your dataset has sufficient diversity
Problem: Each trial takes too longSolution:
  • Set eval_subset_size=10 or smaller
  • Use a faster inference model
  • Reduce max_examples
Problem: Adding examples doesn’t improve scoresSolution:
  • Verify examples are high-quality and diverse
  • Check that example_template formats them clearly
  • Your task might not benefit from few-shot (try Meta-Prompt instead)

Next Steps

Try Meta-Prompt

For tasks that need deeper reasoning

Compare Optimizers

See all optimization strategies