Bayesian Search
Use BayesianSearchOptimizer in Agent Learning Kit to select few-shot examples, format them as demonstrations, and score competing prompts with Optuna.
About
Bayesian Search keeps your instruction and changes the examples shown alongside it. Each Optuna trial chooses a number of examples and a seed for selecting their rows. Use it when you have good sample replies and want to learn which ones help the model follow your instruction.
Compare prompts with one demonstration each
Ridgeline Outfitters wants its support agent to ask for an order number before starting a return. Each row supplies both a customer message and an example reply worth imitating. example_template fills both fields for a demonstration; the task prompt fills only {message} for the ticket being answered.
With Python 3.12, install Agent Learning Kit in a virtual environment:
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install agent-learning-kit==0.3.7
Set OPENAI_API_KEY in the shell where you run the script. Save the example as bayesian_search.py and run python bayesian_search.py. The local Contains metric gives a reply 1 if it includes “order number” (case-insensitive) and 0 otherwise. You do not need Future AGI keys for this example.
from fi.evals.metrics.heuristics.string_metrics import Contains
from fi.opt.base.evaluator import Evaluator
from fi.opt.datamappers import BasicDataMapper
from fi.opt.optimizers import BayesianSearchOptimizer
model = "gpt-4o-mini"
tickets = [
{
"message": "The rain shell is too big. Can I send it back?",
"reply": "What is your order number so I can look up the rain shell?",
},
{
"message": "I would like to return my unused headlamp.",
"reply": "Could you share the order number for the headlamp?",
},
]
prompt = (
"You work at Ridgeline Outfitters. Ask for the detail you need before "
"starting a return. Customer message: {message}"
)
evaluator = Evaluator(metric=Contains(config={"keyword": "order number"}))
mapper = BasicDataMapper(key_map={"response": "generated_output"})
optimizer = BayesianSearchOptimizer(
inference_model_name=model,
example_template="Customer: {message}\nAgent: {reply}",
few_shot_position="prepend",
min_examples=1,
max_examples=1,
n_trials=2,
)
result = optimizer.optimize(
evaluator=evaluator,
data_mapper=mapper,
dataset=tickets,
initial_prompts=[prompt],
)
print(f"Score: {result.final_score:.2f}")
print(result.best_generator.get_prompt_template()) The script prints the best trial’s score and the complete prompt, including the selected demonstration. With min_examples=max_examples=1, trials vary which row to show, not how many. Two trials can draw the same row.
Search and scoring parameters
The options in the next three tables belong to BayesianSearchOptimizer(...). There are no required constructor arguments.
| Argument | SDK default | Purpose |
|---|---|---|
min_examples, max_examples | 2, 8 | Inclusive range for the trial’s proposed demonstration count. |
allow_repeats | False | Allow the same row to be sampled more than once. Without repeats, the available rows limit the count. |
fixed_example_indices | None | Dataset indices to include first in every trial. They are not trimmed if there are more than the proposed count. |
n_trials, seed | 10, 42 | Number of trials and seed for the default Optuna TPE sampler. This does not seed model generation or random evaluation subsets. |
inference_model_name, inference_model_kwargs | "gpt-4o-mini", None | LiteLLM task model and generation options for scoring trials. |
eval_subset_size, eval_subset_strategy | None, "random" | By default, score every row. For a smaller subset, sample "random" rows or take the "first" rows. "all" uses the entire dataset. |
score_aggregator | None | Function from a list of EvaluationResult objects to one trial score. By default, use the mean row score, or 0.0 if there are no results. |
sampler, pruner | None, None | Optuna sampler and pruner passed to the study. The default sampler is a seeded TPESampler. |
direction | "maximize" | Optuna study direction. Use "minimize" for a custom score where lower is better. A trial that fails during scoring receives 0.0; check the trial succeeded before treating a low score as a win. |
storage, study_name | None, None | Optuna storage and study name. Supplying both lets the optimizer reopen an existing study. |
Formatting demonstrations
| Argument | SDK default | Purpose |
|---|---|---|
example_formatter | None | Function from one row to one formatted demonstration; overrides template-based formatting. |
example_template | None | Python format string using row keys, such as "Customer: {message}\nAgent: {reply}". |
example_template_fields, field_aliases | None, None | Fallback field list and optional display-label mapping. If no template or selected fields work, the optimizer serializes the row as JSON. |
example_separator, few_shot_title | "\n", None | Separator between demonstrations and optional heading before the block. |
few_shot_position | "append" | Place the block after the task prompt, or use "prepend" to put it first. |
prompt_builder | None | Custom function receiving the base prompt and a list containing the joined demonstration block. Returns the complete prompt. |
Optional teacher for inferring a format
| Argument | SDK default | Purpose |
|---|---|---|
infer_example_template_via_teacher | False | Ask a teacher for a formatting template before the trials. Not needed when you supply example_template. |
teacher_model_name, teacher_model_kwargs | "gpt-5", None | Teacher model and overrides for its completion options (initially temperature=1.0, max_tokens=16000). |
template_infer_n_samples | 8 | Maximum number of rows sent to the teacher for format inference. |
teacher_system_prompt | TEACHER_SYSTEM_PROMPT | Built-in instructions asking the teacher to infer a Python format string from the rows. |
teacher_infer_max_retries, teacher_infer_retry_sleep | 2, 0.5 | Retries after a failed inference attempt and seconds to wait between attempts. On failure the optimizer falls back to its other formatters. |
Run inputs, results and limits
optimize() requires evaluator, data_mapper, dataset and initial_prompts. It uses only the first starting prompt. Pass early_stopping (default None) to check stopping criteria after each scored trial. The return type is OptimizationResult: history contains scored trial prompts, and best_generator holds the study’s selected template.
- For teacher-based formatting in 0.3.7, supply a
teacher_system_promptwithout literal braces, or double any literal braces in it. The built-in instructions include an unescaped JSON example: formatting fails before the teacher is called and the optimizer falls back. To skip inference entirely, supplyexample_templateand leaveinfer_example_template_via_teacher=False. - Keep aside tickets that are not in
datasetto measure the winning prompt. Here the demonstration pool and the evaluation pool are the same two rows: even a perfect score does not tell you how the agent will respond to a new ticket. - An empty
initial_promptslist raisesValueError. If no trial produces a history entry, the optimizer raisesRuntimeError: Optimization stopped before any trials completed successfully. Check thatn_trialsis positive, the example indices exist, and the placeholders in the task prompt match the row keys.
Next steps
- Random Search changes the instruction instead of the demonstrations.
- Compare optimizer settings for the dashboard equivalents of the few-shot and trial counts.
Questions & Discussion