ProTeGi

Use ProTeGi in Agent Learning Kit to generate edits from failing examples, tune the number of critiques, and keep the best candidate prompts.

About

Use ProTeGi when your prompt works on most inputs but you can identify a recurring mistake. A teacher model writes a short critique of the failures (a textual gradient) and proposes edits. Rather than committing to the first rewrite, you can keep several promising prompts (the beam) for the next round.

Revise a prompt that asks the wrong question

Ridgeline Outfitters’ current returns prompt asks why a customer wants a return. The agent should ask for the order number first. Put an example of the desired reply in each row so the teacher sees it when analyzing failures. The task prompt itself includes only the customer message, not the desired reply.

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 protegi.py and run python protegi.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.generators import LiteLLMGenerator
from fi.opt.optimizers import ProTeGi

model = "gpt-4o-mini"
tickets = [
    {"message": "The rain shell is too big. Can I send it back?",
     "expected_reply": "Could you share your order number?"},
    {"message": "I would like to return my unused headlamp.",
     "expected_reply": "What is the order number for your headlamp?"},
]
prompt = (
    "You work at Ridgeline Outfitters. Ask why the customer wants a return. "
    "Reply with just that question. Customer message: {message}"
)
evaluator = Evaluator(metric=Contains(config={"keyword": "order number"}))
mapper = BasicDataMapper(key_map={"response": "generated_output"})

teacher = LiteLLMGenerator(model=model, prompt_template="{prompt}")
optimizer = ProTeGi(
    teacher_generator=teacher, num_gradients=1, errors_per_gradient=2,
    prompts_per_gradient=1, beam_size=1,
)
result = optimizer.optimize(
    evaluator=evaluator,
    data_mapper=mapper,
    dataset=tickets,
    initial_prompts=[prompt],
    num_rounds=1,
)
print(f"Score: {result.final_score:.2f}")
print(result.best_generator.get_prompt_template())

optimize() returns an OptimizationResult. The two printed values are the best candidate’s mean score and template. result.history lets you compare that candidate with the starting instruction. A score of 0.00 means neither ticket got a reply containing the target phrase; a rewrite is not a guaranteed fix.

How it works

  1. Find failures. For each prompt in the beam, ProTeGi runs the task model on up to 32 sampled rows. If any replies score below 0.5, it sends the teacher a sample of the original rows. In the Ridgeline example, the teacher can see expected_reply on those rows even though the task model only sees message.
  2. Request edits. The teacher gets one request for num_gradients critiques, then one rewrite request per returned critique. errors_per_gradient controls how many failed rows the teacher sees in each request, not how many rewrites it produces. With the example’s settings, even if both tickets fail, ProTeGi asks for one critique and one rewrite.
  3. Select the next beam. ProTeGi scores the original prompts and distinct rewrites on the same random sample of rows. It ranks them by mean score and keeps the top beam_size. The original prompt can survive if a rewrite scores worse.

To estimate how many new prompts you request, use beam_size x num_gradients x prompts_per_gradient for a full beam where every prompt has failures and the teacher returns the requested critiques. In round one, use the number of distinct starting prompts instead of beam_size. To compare more fixes in one round, raise num_gradients or prompts_per_gradient. To refine the surviving fixes again, raise num_rounds.

Parameters

WhereArgumentSDK defaultPurpose
ProTeGi(...)teacher_generatorRequiredLiteLLMGenerator with {prompt} as its template. Receives critique and rewrite requests.
ProTeGi(...)num_gradients4Distinct critiques requested for a prompt with failures.
ProTeGi(...)errors_per_gradient4Maximum failed rows sampled for each critique or rewrite request.
ProTeGi(...)prompts_per_gradient1Rewrites requested for each critique.
ProTeGi(...)beam_size4Top candidates retained after a round. Does not cap the number scored within that round.
ProTeGi(...)task_modelNoneModel used to run candidate prompts. Defaults to the teacher’s model.
optimize()evaluator, data_mapper, datasetRequiredMetric wrapper, evaluator input mapping, and rows.
optimize()initial_promptsRequiredList of templates. The distinct templates form the initial beam. Supply at least one.
optimize()num_rounds3Number of expand, score and select cycles.
optimize()eval_subset_size32Up to this many randomly sampled rows for ranking candidates each round.
optimize()early_stoppingNoneOptional EarlyStoppingConfig, checked after selecting the new beam.

The platform form prefills Beam size, Number of gradients, Errors per gradient, Prompts per gradient, and Number of Rounds with the same defaults as the SDK.

Limits and troubleshooting

If you see no rewrites, check that your metric catches the mistake. ProTeGi skips the teacher requests for a prompt when it finds no failures in its sample; increasing num_gradients won’t change that.

If you set task_model separately, best_generator still uses the teacher’s model. Copy its selected template into a generator configured for your task model to use the same model you scored.

Next steps