Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 13
Module 6 · Case studies: recommenders and reward design · Chapter 13 of 24
Building a reward-design agent
Builds on Working with model APIs, AI agents and multi-agent systems, Agent design fundamentals and Case study: an agent that writes reward functions. Next up: Case study: a smart parking agent system.
Part 1 · The environment
A small world to test rewards
A reward search needs a world where training is cheap enough to run dozens of times in seconds. This chapter builds that world and the search around it, small enough to read in full and to run on one machine.
The world is a six by six grid. The agent starts in some cell and must pick up a key and then reach the goal. Four cells are hazards, and entering one ends the episode. Each step moves one cell up, down, left or right, and walking into the edge leaves the agent where it is. An episode also ends after 60 steps. That makes three ways for an episode to end: the agent reached the goal with the key, entered a hazard, or ran out of steps. Reaching the goal cell without the key does not count and does not end the episode.
Two design choices make the grid useful for studying rewards. The key makes the task two-stage: the goal only pays after a detour to a different cell, so a reward that mentions only the goal gives the learner almost no signal. The hazards give the reward something to avoid, so a candidate can be wrong in the opposite direction by being timid or reckless. The previous chapter explained why a separate ground-truth measure matters. Here it is simple to state: success means the agent reached the goal while holding the key.
The world is plain Python with no libraries. Its transition function is pure: it takes a position, whether the key is held, and an action, and it returns the new position, the new key state and a small record of what happened. Rewards never see the world directly. They see that record, which keeps every reward a function of a few named facts and nothing else.
The environment in code
The layout is written as six strings. S marks the start, H a hazard, K the key and G the goal. The constants below are derived from it, so changing the layout changes the whole world.
LAYOUT = [
"S.....",
".HH...",
"....H.",
".K....",
"..H...",
".....G",
]
SIZE = 6
CAP = 60 # steps per episode
ACTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
HAZARDS = {(r, c) for r in range(SIZE) for c in range(SIZE)
if LAYOUT[r][c] == "H"}
KEY = next((r, c) for r in range(SIZE) for c in range(SIZE)
if LAYOUT[r][c] == "K")
GOAL = next((r, c) for r in range(SIZE) for c in range(SIZE)
if LAYOUT[r][c] == "G")
START = (0, 0)
STARTS = [(r, c) for r in range(SIZE) for c in range(SIZE)
if (r, c) not in HAZARDS and (r, c) != GOAL]The layout and the facts derived from it.
The record of one move is a Step. It holds the old and new positions and four facts: whether the key was just picked up, whether the goal was reached with the key, whether a hazard was entered, and whether the episode is over. The function move builds it.
def move(pos, has_key, action): """Pure transition. Returns (new_pos, new_has_key, Step).""" dr, dc = ACTIONS[action] r, c = pos[0] + dr, pos[1] + dc new = (r, c) if 0 <= r < SIZE and 0 <= c < SIZE else pos s = Step() s.old, s.new, s.old_has_key = pos, new, has_key s.got_key = (not has_key) and new == KEY new_key = has_key or s.got_key s.has_key = new_key s.hit_hazard = new in HAZARDS s.reached_goal = new == GOAL and new_key s.done = s.hit_hazard or s.reached_goal return new, new_key, s
One transition. It changes nothing outside its arguments.
Because move is pure, the same function serves the learner, the evaluator and the tests. A reward is later defined as a function from a Step to a number, and that is the whole interface between the world and the idea of a reward.
A random baseline
Before building a learner, measure what doing nothing clever achieves. The script plays 2,000 episodes from the start cell with an agent that chooses a random action each step, counts the episodes that end in success, and prints the layout.
def random_policy_success(episodes=2000, seed=0): rnd = random.Random(seed) wins = 0 for _ in range(episodes): pos, key = START, False for _ in range(CAP): pos, key, s = move(pos, key, rnd.randrange(4)) if s.done: wins += s.reached_goal break return wins if __name__ == "__main__": print("\n".join(LAYOUT)) n = random_policy_success() print(f"random policy: {n} successes in 2000 episodes")
A random policy, as the floor for every later number.
S..... .HH... ....H. .K.... ..H... .....G random policy: 8 successes in 2000 episodes
Output from one run; yours will differ.
Eight successes in 2,000 episodes is 0.4 per cent. The agent has to find the key and then the goal by accident, so a reward that pays only on success would fire about once in 250 episodes for a random learner. That is the sparse-reward problem in numbers. A learner that is only paid on success has almost nothing to learn from until it stumbles into a win, and the next lesson shows how long that can take.
What are the three ways an episode in this grid can end, and which one is success?
- It ends at the goal with the key, in a hazard, or after 60 steps; reaching the goal without the key does not end it.
- Only the first is success: the goal reached while holding the key.
Why is the key part of the design?
- It makes the goal need a detour, so a reward that only names the goal gives almost no signal.
- That makes the choice of reward matter, which is the subject of the chapter.
The random policy succeeded 8 times in 2,000 episodes. What does that number tell you about a reward that pays only on success?
- It fires about 0.4 per cent of the time for a random learner, so there is very little to learn from at first.
Part 2 · A learner to test rewards
Q-learning in one rule
To test a reward you need something that learns from it. We use tabular Q-learning, the simplest widely used learner for a world with few states. It keeps a table with one number for each state and action, written Q(s, a): its current estimate of the total future reward from taking action a in state s and playing well afterwards. A state here is the position plus whether the key is held, so the table has up to 72 rows of four numbers, filled in as states are visited.
Learning is one update rule applied after every step. If the step moved from s to s' with reward r, the new estimate is the old one plus a fraction alpha of the error between what happened and what was expected:
Q(s, a) <- Q(s, a) + alpha * (r + gamma * max Q(s', a') - Q(s, a))alpha is the step size, gamma discounts the future.
The term in brackets is the surprise: reward received plus the best value the table believes is available next, minus what the table said. Alpha is the step size and gamma, between 0 and 1, discounts the future so that nearer rewards count more. At the end of an episode there is no next state, so the future term is zero. The rule is the one-step Q-learning update in section 6.5 of Sutton and Barto, "Reinforcement Learning: An Introduction", second edition, which is equation 6.6 in the draft copy hosted at web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf (the final edition may number it differently). That section's algorithm box also sets the value of a terminal state to zero, as the code here does, and a test in the last lesson checks that the code follows the rule.
To choose actions while training, the learner uses epsilon-greedy exploration: with probability epsilon it picks a random action, otherwise the action with the highest Q. Epsilon starts at 1.0 and falls in a straight line to 0.05 by about three quarters of the way through, and stays there, so early episodes explore and later ones exploit what was learned. Training starts each episode from a random start cell, which spreads experience over the grid.
The learner in code
def update(old, reward, best_next, alpha=ALPHA, gamma=GAMMA): """Q(s,a) += alpha * (r + gamma * max Q(s',.) - Q(s,a))""" return old + alpha * (reward + gamma * best_next - old)
The update rule as a function, so it can be tested alone.
def train(reward, episodes=400, seed=0): """reward(step) -> float. Returns the Q table.""" rnd = random.Random(seed) table = new_table() for ep in range(episodes): eps = max(0.05, 1.0 - ep / (0.8 * episodes)) pos, key = rnd.choice(STARTS), False for _ in range(CAP): qs = q(table, pos, key) a = (rnd.randrange(4) if rnd.random() < eps else max(range(4), key=lambda i: qs[i])) new, new_key, s = move(pos, key, a) r = reward(s) nxt = 0.0 if s.done else max(q(table, new, new_key)) qs[a] = update(qs[a], r, nxt) pos, key = new, new_key if s.done: break return table
Train for a fixed number of episodes. reward maps a Step to a number.
train takes the reward as a function, a number of episodes and a seed. The seed fixes every random choice, so the same inputs give the same table. The episode budget is fixed per candidate in the search, which is what makes candidates comparable.
Scoring is separate and never uses the reward. evaluate follows the greedy policy (always the best action in the table) from every legal start cell, which is 31 cells once the hazards and the goal are removed, and reports the share that reach the goal with the key, the share that end in a hazard, the share that pick up the key, and the mean steps of the successes.
def evaluate(table): """Ground truth: success from every start, whatever the reward.""" wins = hazards = keys = 0 lengths = [] for p in STARTS: steps = greedy_rollout(table, p) last = steps[-1] wins += last.reached_goal hazards += last.hit_hazard keys += any(s.got_key for s in steps) or last.has_key if last.reached_goal: lengths.append(len(steps)) n = len(STARTS) return {"success": round(wins / n, 3), "hazard": round(hazards / n, 3), "key": round(keys / n, 3), "mean_steps": round(sum(lengths) / len(lengths), 1) if lengths else None}
Ground truth: success from every start, whatever the reward.
The update rule is checked by a test rather than trusted. One test applies the formula by hand to two cases and then repeats one fixed transition 60 times to confirm that the value converges to r + gamma times the next value, which is what the rule must do. It is in the test file of lesson 5.
Two rewards, one budget
The first reward is the one a person would write at once: one point on success, nothing otherwise. The second is a hand-written reward with several parts: a point for picking up the key, 5 for success, minus 5 for a hazard, a small cost of 0.02 per step, and 0.1 per step of progress toward the current target, which is the key until it is held and then the goal.
def sparse(s): return 1.0 if s.reached_goal else 0.0 def hand(s): """A hand-written reward: key, goal, hazard, step cost, progress.""" r = -0.02 + 0.1 * progress(s) if s.got_key: r += 1.0 if s.reached_goal: r += 5.0 if s.hit_hazard: r -= 5.0 return r
The two rewards. Progress comes from the grid module.
The script trains each reward for five seeds with a budget of 25 episodes and prints the ground-truth success of each trained policy. A second script sweeps the budget for one seed.
sparse success per seed: [0.0, 0.0, 0.0, 0.0, 0.0] hand-written success per seed: [0.935, 0.935, 0.871, 0.903, 0.839]
Output from one run; yours will differ.
episodes reward success hazard key ms
25 sparse 0.0 0.323 0.065 2
25 hand-written 0.935 0.0 0.935 1
400 sparse 0.0 0.323 0.065 13
400 hand-written 1.0 0.0 1.0 7
2000 sparse 0.0 0.323 0.065 72
2000 hand-written 1.0 0.0 1.0 46
20000 sparse 1.0 0.0 1.0 364
20000 hand-written 1.0 0.0 1.0 665Output from one run; yours will differ.
What the numbers say
With 25 episodes the hand-written reward reaches success from 26 to 29 of the 31 starts depending on the seed, and with 400 episodes the seed-0 run reaches all of them. The success-only reward scored zero at 25, 400 and 2,000 episodes and scored 1.0 at 20,000. The next script explains the gap by counting how often the reward fired while training.
400 episodes: reward fired 0 times, greedy success 0.0 2000 episodes: reward fired 0 times, greedy success 0.0 20000 episodes: reward fired 10771 times, greedy success 1.0
Output from one run; yours will differ.
In 2,000 training episodes the success-only reward never fired once, so the table never held a single nonzero number to learn from. At 20,000 episodes it fired often enough to learn. The cost was a few hundred milliseconds on this machine against a few milliseconds for the 25-episode runs, and the timings vary from run to run. The shaped reward is not cleverer. It simply gives the learner something to follow from the first step, and that is what a reward search is trying to find.
Watch for the values rising toward the key at row 3, column 1
Read it as steps
Values after 25 episodes, from the run above (seed 0).
Why must the evaluation never use the reward that trained the policy?
- A reward can be hacked, so its own total can be high while the task fails.
- Success from every start is measured by the world, independent of the reward.
Part 3 · A reward language the model writes
From weights to a reward
The reward design case study argued for candidates written as data. This lesson builds that language for the grid. A candidate is a JSON object with one key, weights, mapping feature names to numbers. A feature is a plain function of a Step. The reward of a step is the sum of weight times feature value over the features named.
Six features are offered, and the model is told what each one means in words: got_key is 1 on the step the key is picked up; reached_goal is 1 on the step the goal is reached with the key; hit_hazard is 1 on entering a hazard; step is 1 on every step, so a negative weight is a time cost; progress is +1 for a step toward the current target, minus 1 for a step away and 0 if the distance is unchanged; near_hazard is 1 when the step ends next to a hazard. The first four are events and the last two shape behaviour between events.
FEATURES = {
"got_key": lambda s: 1.0 if s.got_key else 0.0,
"reached_goal": lambda s: 1.0 if s.reached_goal else 0.0,
"hit_hazard": lambda s: 1.0 if s.hit_hazard else 0.0,
"step": lambda s: 1.0,
"progress": _progress,
"near_hazard": lambda s: 1.0 if _near_hazard(s.new) else 0.0,
}The only features a candidate can use.
A feature list is a design decision with consequences. near_hazard can be given a positive weight, which would pay the agent to hover beside a hazard, and a model may try that. We keep it in the list on purpose because it is a feature a thoughtful person might choose with the wrong sign, and the ground-truth score is what exposes the mistake.
The validator
Everything the model returns passes through one function before any use. It accepts a JSON string or an already parsed object and returns clean weights or raises an error naming the reason. It checks the shape (an object with exactly the key weights), the names (every one a known feature), the count (at most six), the type (a number, and not a boolean, which Python treats as a number), the range (finite and between -20 and 20) and that something is not zero.
class RewardError(ValueError): pass def validate(raw): """Return a clean {feature: weight} dict or raise RewardError.""" if isinstance(raw, str): try: raw = json.loads(raw) except ValueError as e: # bad JSON, or a number too long msg = getattr(e, "msg", "bad number") raise RewardError(f"not JSON: {msg}") if not isinstance(raw, dict) or set(raw) != {"weights"}: raise RewardError('expected an object with one key, "weights"') w = raw["weights"] if not isinstance(w, dict) or not w: raise RewardError("weights must be a non-empty object") if len(w) > MAX_FEATURES: raise RewardError(f"more than {MAX_FEATURES} features")
Validate model output, part one: the shape of the reply.
clean = {}
for name, value in w.items():
if name not in FEATURES:
raise RewardError(f"unknown feature {name!r}")
if isinstance(value, bool) or not isinstance(
value, (int, float)):
raise RewardError(f"weight for {name} is not a number")
if abs(value) > MAX_ABS or not math.isfinite(value):
big = isinstance(value, int) and abs(value) > 10**15
shown = "a huge integer" if big else value
raise RewardError(
f"weight for {name} out of range ({shown})")
clean[name] = float(value)
if all(v == 0 for v in clean.values()):
raise RewardError("all weights are zero")
return cleanPart two: names, types and ranges, one weight at a time.
def build(weights): """Turn validated weights into reward(step) -> float.""" items = list(weights.items()) def reward(s): return sum(w * FEATURES[n](s) for n, w in items) return reward
Turn clean weights into a reward function.
A range check matters because the learner is sensitive to scale. A weight of one million would swamp every other term of the reward. The count check bounds the size of a candidate. The boolean check closes a gap: True passes an isinstance(value, (int, float)) test in Python, so it is excluded by name. Each of these was added because a plausible bad input exists, and the next page runs them.
Feeding it bad input
The probe script feeds one good candidate and fourteen bad ones to the validator and prints what happens to each. The bad ones are empty text, prose, a feature name that is Python code, an unknown feature, a string weight, a boolean weight, a huge weight, a not-a-number weight, all zeros, an empty object, an extra key, a list, and two integers with hundreds or thousands of digits. The last two were added after a bad run: the first version of the validator tested for a finite number before the range, and Python raised OverflowError when it tried to turn a 400-digit integer into a float. A 5,000-digit integer exceeds the interpreter's limit on integer text and raises a plain ValueError, which the JSON step did not catch. Both are model outputs a guard must turn into an ordinary rejection, so the range test now comes first and the JSON step catches ValueError.
CASES = [
("good", '{"weights": {"got_key": 1, "reached_goal": 5, '
'"step": -0.02}}'),
("empty reply", ""),
("prose", "I would reward reaching the goal."),
("code", '{"weights": {"__import__(\'os\').system(\'x\')": 1}}'),
("unknown feature", '{"weights": {"speed": 2}}'),
("string weight", '{"weights": {"reached_goal": "high"}}'),
("bool weight", '{"weights": {"reached_goal": true}}'),
("too large", '{"weights": {"reached_goal": 1e9}}'),
("not finite", '{"weights": {"reached_goal": NaN}}'),
("all zero", '{"weights": {"reached_goal": 0, "step": 0}}'),
("empty weights", '{"weights": {}}'),
("extra key", '{"weights": {"step": -1}, "note": "x"}'),
("a list", '[1, 2, 3]'),
("400-digit integer",
'{"weights": {"step": 1' + "0" * 400 + '}}'),
("5000-digit integer",
'{"weights": {"step": 1' + "0" * 5000 + '}}'),
]The cases. The loop that prints them is omitted.
good ok {'got_key': 1.0, 'reached_goal': 5.0, 'step': -0.02}
empty reply rejected: not JSON: Expecting value
prose rejected: not JSON: Expecting value
code rejected: unknown feature
"__import__('os').system('x')"
unknown feature rejected: unknown feature 'speed'
string weight rejected: weight for reached_goal is not a number
bool weight rejected: weight for reached_goal is not a number
too large rejected: weight for reached_goal out of range
(1000000000.0)
not finite rejected: weight for reached_goal out of range (nan)
all zero rejected: all weights are zero
empty weights rejected: weights must be a non-empty object
extra key rejected: expected an object with one key, "weights"
a list rejected: expected an object with one key, "weights"
400-digit integer rejected: weight for step out of range (a huge
integer)
5000-digit integer rejected: not JSON: bad numberOutput from one run; yours will differ. Long lines are wrapped here.
Part 4 · The propose, train, reflect loop
One round in code
The loop follows the case chapter. Each round asks the model for four candidates, three rounds in all. The model writes one candidate per call, so the four proposals in a round are independent samples. Every candidate passes the validator. A valid, new candidate trains three times, once for each of three seeds, with the same 25-episode budget, and its score is the mean ground-truth success over the seeds. The best candidate so far, with its statistics, is kept.
def search(propose, trainer=train, rounds=ROUNDS, per_round=CANDIDATES, max_trainings=MAX_TRAININGS): history = {"best": None, "last_round": [], "rounds": [], "trainings": 0, "rejected": 0, "duplicates": 0} seen = {} for rnd in range(1, rounds + 1): row = {"round": rnd, "proposed": 0, "rejected": 0, "trained": 0, "best_success": None, "errors": []} history["last_round"] = [] for k in range(per_round): if history["trainings"] + len(SEEDS) > max_trainings: row["stop"] = "training_budget" # no model call either break raw = propose(render_feedback(history)) row["proposed"] += 1 try: w = validate(raw) except RewardError as e: # guard: never train this row["rejected"] += 1 history["rejected"] += 1 row["errors"].append(str(e)) history["last_round"].append( f"A candidate was rejected: {e}.") continue
The guard: nothing is trained until the validator passes it.
key = canonical(w)
if key in seen:
history["duplicates"] += 1
continue
tables = [trainer(build(w), EPISODES, seed=s)
for s in SEEDS]
history["trainings"] += len(SEEDS)
row["trained"] += 1
evs = [evaluate(t) for t in tables]
succ = statistics.mean(e["success"] for e in evs)
st = stats_for(w, tables[0])
st["success"] = round(succ, 3)
seen[key] = succ
history["last_round"].append(
f"Candidate {key} got success {st['success']}.")
cand = {"weights": w, "stats": st}
if (history["best"] is None
or succ > history["best"]["stats"]["success"]):
history["best"] = cand
if (row["best_success"] is None
or succ > row["best_success"]):
row["best_success"] = round(succ, 3)Train, score by ground truth, keep the best.
A real search
The proposer is one function that asks the local model for one candidate, with the system prompt that lists the features and the rules and a request for JSON only. The full search then runs against the model.
def model_proposer(): from llm import chat def propose(feedback): msg, _ = chat([{"role": "system", "content": SYSTEM}, {"role": "user", "content": feedback}], max_tokens=200, response_format={"type": "json_object"}) return msg.content or "" return propose
One call per candidate; the reply is a string for the validator.
The validator covers what the model returns, not whether the call succeeds. If propose raises an error, such as a timeout from the model server, search does not catch it and the whole search ends. A probe that makes the proposer raise confirmed this. The retries and timeouts from the model APIs chapter belong inside propose, and a longer search would save its history after every round so that a crash does not lose it.
Three runs of the search follow. Each is a separate run of the same code and the same model, so the three differ in what the model proposed. Every printed run is one real output. The seconds on the last line include time spent waiting for the shared model server, so they vary a great deal, and the 453 seconds of the first run says nothing about the code.
round 1: proposed 4, rejected 1, trained 3, best success 0.914 round 2: proposed 4, rejected 3, trained 0, best success - round 3: proposed 4, rejected 2, trained 1, best success 0.914 best weights: {"got_key": 20.0, "reached_goal": 20.0, "hit_hazard": -20.0, "step": -1.0, "progress": 5.0, "near_hazard": -2.0} best result: success 0.914, hazard 0.0, key 0.935, mean steps 9.4 training runs 12, rejected 6, duplicates 2 rejected because: {'weight for got_key out of range': 2, 'weight for reached_goal out of range': 2, 'weight for hit_hazard out of range': 2} 453 s on this machine
Output from one run; yours will differ. Long lines are wrapped here.
round 1: proposed 4, rejected 2, trained 2, best success 0.914 round 2: proposed 4, rejected 1, trained 3, best success 0.914 round 3: proposed 4, rejected 2, trained 2, best success 0.914 best weights: {"got_key": 10.0, "reached_goal": 15.0, "hit_hazard": -20.0, "step": -0.1, "progress": 1.0, "near_hazard": -0.5} best result: success 0.914, hazard 0.0, key 0.935, mean steps 9.4 training runs 21, rejected 5, duplicates 0 rejected because: {'weight for reached_goal out of range': 4, 'weight for hit_hazard out of range': 1} 86 s on this machine
Output from one run; yours will differ. Long lines are wrapped here.
Reading the runs
Read the counts before the scores. Across the three runs the validator turned away 18 of the 36 proposals (6, 5 and 7), and every rejection was a weight outside the range of -20 to 20, even though the prompt gave that range. Those proposals cost model calls and never trained. The best candidate in each run scored 0.914. Only the third run improved from one round to the next, from 0.892 to 0.914; the other two reached 0.914 in their first rounds and did not beat it. That is about the level of the hand-written reward of the last lesson, whose five seeds ranged from 0.839 to 0.935. The best weights in the three runs are close to each other. That may be one reason later rounds found little new, but we did not test it. This is one model and these runs, not a general result. The same script was run three more times later, with the same model. The validator turned away 24 of 36 proposals (7, 9 and 8), again every one for a weight outside the range. The best scores were 0.946, 0.946 and 0.914, and this time the best score rose between rounds in all three runs (for example from 0.892 to 0.946). So three runs cannot say whether the feedback helps: the same code gave an improvement in one run of three the first time and in three of three the second time.
The loop as an agent
Watch for the validator stopping a candidate before the learner sees it
Read it as steps
A condensed run of the loop; the scores are those of run 3 above.
In the language of the agents chapter, this is an agent loop whose only tool is training. The model proposes, the guard decides, and the result returns to the model, with a step budget around it. Here the guard is not the model's judgement but a function in your code. The scene condenses run 3 to one rejection and two trainings. The scores 0.892 and 0.914 are the ones that run printed, and the proposals are shortened.
What this shows is the split of responsibilities. The model's job is narrow: write weights. Everything with a cost or a risk is in code that you can read, test and bound: the validator, the trainer, the evaluator and the caps.
Why does the loop check the training budget before calling the model?
- A model call that cannot lead to a training run wastes time and tokens.
- Checking first stops the search exactly at its limit.
In the three runs, what did the validator reject, and what does that say about the prompt?
Part 5 · Mapping to a framework
The same loop in a framework
Frameworks package the pieces above. Google's Agent Development Kit (ADK) is one. Its documentation lists agents driven by a model, workflow agents that run sub-agents in sequence, in a loop or in parallel, and model integrations that include Ollama and LiteLLM. The loop agent takes a list of sub-agents and an optional max_iterations, and a sub-agent can end the loop early by setting an escalate flag, for example from a tool. These names come from the ADK documentation as read on 22 November 2026; nothing from ADK is installed or run in this chapter. The latest release at that date, 2.15.0, was two days old, so anyone trying it should pin the newest release that is at least two weeks old, which was 2.14.0.
Mapped onto our loop, the model agent is the proposer, a Python function registered as its tool does the validate, train and score, and the loop agent repeats the pair. The framework replaces the outer for loop and the plumbing that carries messages. It does not replace the checks, and the sketch shows why they stay.
# Shape only, not run. Names follow the ADK docs of 2026-11-22. from google.adk.agents import LlmAgent, LoopAgent def train_reward(weights_json: str) -> dict: # your code: validate, budget check, train, score try: w = validate(weights_json) except RewardError as e: return {"error": str(e)} return run_training(w) proposer = LlmAgent( name="reward_proposer", model=YOUR_MODEL_CONFIG, instruction=SYSTEM, tools=[train_reward], ) search = LoopAgent(name="reward_search", sub_agents=[proposer], max_iterations=3)
Not run. The framework wraps the loop; the checks stay in your function.
There is one real change in behaviour. In our code the loop is a fixed procedure and the model only writes a candidate. In this sketch the model calls a tool, so it chooses how many times to train within an iteration. The budget therefore has to move inside the tool, or a model that keeps asking can spend the whole allowance. This is the difference between a workflow and an agent from the agent design chapter, seen in a small example.
What stays in your code
| Piece | In our code | In a framework |
|---|---|---|
| Repeat for a number of rounds | A for loop in search | A loop agent with a maximum |
| Ask the model | chat with a system prompt | A model agent with an instruction |
| Run training | A trainer function | A tool the model agent can call |
| Validate, bound, score | validate, caps, evaluate | Still your code, inside the tool |
| Record what happened | The history dictionary | Session state and events |
The last column shows that a framework removes loop and message plumbing, and adds conveniences such as state storage and a standard way to run an agent. The row on validating, bounding and scoring stays yours. It is the row that decides cost, safety and correctness, and no framework knows what a safe weight is for your task. A good rule is to write the checks as ordinary functions with their own tests first and then to decide whether a framework earns its place around them.
Choosing one is a trade. A framework brings a vocabulary shared across a team and tools for tracing and deployment. It also brings a dependency that changes quickly. The ADK releases listed on its package page in the weeks before this was written ran from 2.9 to 2.15 in about ten weeks. The plain-Python loop of this chapter is about 50 lines of search code and has no such dependency.
Tests: no invalid reward is ever trained
The most important property of the loop is stated as tests. They use a scripted stand-in for the model, a function that returns a fixed list of replies, so they are fast and do not depend on what a model happens to write. The first test feeds the loop eight kinds of bad input followed by good ones and checks that the trainer received only the valid reward, once per seed. The second feeds only bad input and checks that nothing trained and that there is no best candidate. A third checks that the training budget stops the search, and a fourth that the episode budget is the same for every candidate.
def scripted(replies): it = iter(replies) return lambda feedback: next(it) def recording_trainer(): seen = [] def trainer(reward, episodes, seed): seen.append((reward, episodes, seed)) return train(reward, episodes, seed) trainer.seen = seen return trainer def test_invalid_rewards_are_never_trained(): t = recording_trainer() h = search(scripted(BAD + [GOOD] * 4), trainer=t, rounds=3, per_round=4) assert h["rejected"] == len(BAD) # one distinct valid reward, trained once per seed, nothing else assert len(t.seen) == 3 assert h["duplicates"] == 3 and h["best"] is not None
The trainer records what it was given; the test inspects it.
The remaining tests cover the Q-learning update formula, the claim that success is measured without the reward, and the match between the reward language and the hand-written reward. They run with uv run python -m pytest -q, and the result is below. A last script runs the two worst cases without a model, in the way the tests do, and prints what the loop reports.
....... [100%] 7 passed in 0.06s
Output from one run; yours will differ.
-- every proposal is invalid round 1: proposed 4, rejected 4, trained 0, best success - round 2: proposed 4, rejected 4, trained 0, best success - round 3: proposed 4, rejected 4, trained 0, best success - no valid candidate -- valid proposals, but only 6 training runs allowed round 1: proposed 2, rejected 0, trained 2, best success 0.462 best weights: {"reached_goal": 2.0, "progress": 0.1} best result: success 0.462, hazard 0.258, key 0.742, mean steps 8.8 training runs 6, rejected 0, duplicates 0 rejected because: {} stop reason: training_budget
Output from one run; yours will differ.
When every proposal is invalid the loop reports no valid candidate rather than inventing one. When the training budget is spent it stops and says why. A search that hits a limit must look different from a search that finished, which is the same rule as for any agent loop.
All chapters · Previous: Case study: an agent that writes reward functions