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.

ArgumentSDK defaultPurpose
min_examples, max_examples2, 8Inclusive range for the trial’s proposed demonstration count.
allow_repeatsFalseAllow the same row to be sampled more than once. Without repeats, the available rows limit the count.
fixed_example_indicesNoneDataset indices to include first in every trial. They are not trimmed if there are more than the proposed count.
n_trials, seed10, 42Number 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", NoneLiteLLM task model and generation options for scoring trials.
eval_subset_size, eval_subset_strategyNone, "random"By default, score every row. For a smaller subset, sample "random" rows or take the "first" rows. "all" uses the entire dataset.
score_aggregatorNoneFunction 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, prunerNone, NoneOptuna 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_nameNone, NoneOptuna storage and study name. Supplying both lets the optimizer reopen an existing study.

Formatting demonstrations

ArgumentSDK defaultPurpose
example_formatterNoneFunction from one row to one formatted demonstration; overrides template-based formatting.
example_templateNonePython format string using row keys, such as "Customer: {message}\nAgent: {reply}".
example_template_fields, field_aliasesNone, NoneFallback 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", NoneSeparator 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_builderNoneCustom function receiving the base prompt and a list containing the joined demonstration block. Returns the complete prompt.

Optional teacher for inferring a format

ArgumentSDK defaultPurpose
infer_example_template_via_teacherFalseAsk a teacher for a formatting template before the trials. Not needed when you supply example_template.
teacher_model_name, teacher_model_kwargs"gpt-5", NoneTeacher model and overrides for its completion options (initially temperature=1.0, max_tokens=16000).
template_infer_n_samples8Maximum number of rows sent to the teacher for format inference.
teacher_system_promptTEACHER_SYSTEM_PROMPTBuilt-in instructions asking the teacher to infer a Python format string from the rows.
teacher_infer_max_retries, teacher_infer_retry_sleep2, 0.5Retries 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_prompt without 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, supply example_template and leave infer_example_template_via_teacher=False.
  • Keep aside tickets that are not in dataset to 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_prompts list raises ValueError. If no trial produces a history entry, the optimizer raises RuntimeError: Optimization stopped before any trials completed successfully. Check that n_trials is positive, the example indices exist, and the placeholders in the task prompt match the row keys.

Next steps

Was this page helpful?

Questions & Discussion