Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 18
Module 8 · Case studies: web and multimodal agents · Chapter 18 of 24
Case study: a multimodal agent for multi-object image generation
Builds on Agent design fundamentals and Building a multimodal web agent. Next up: Case study: a multi-agent medical diagnosis simulator.
Part 1 · Why one-shot generation fails on many objects
Many objects, one prompt
Ask an image model for "two red circles on the left and a blue square on the right" and you may get a red circle, a blue circle and a square of no clear colour. This chapter builds a small system that plans such a picture, draws it one object at a time and checks every step.
A text-to-image model turns a short text prompt into a picture. Many are diffusion models: they start from random noise and refine it step by step into an image that fits the text (Ho et al., 2020, *Denoising Diffusion Probabilistic Models*). The model reads the whole prompt once and produces the whole picture in one go. That works well for one subject and badly for a crowded scene.
The MuLan paper (Li et al., 2024) names the difficulty: text-to-image models struggle with the spatial positions, relative sizes, overlaps and attribute bindings of several objects in one prompt. Each term is easier to see with an example.
| Failure | Prompt says | Picture shows |
|---|---|---|
| Count | three yellow circles | two yellow circles |
| Attribute binding | a red square and a blue circle | a blue square and a red circle |
| Position | a circle left of a square | the circle on the right |
| Relative size | a large square and a small circle | both about the same size |
| Overlap | two circles side by side | two circles merged into one blob |
Requirements for a planning system
The idea in the paper is to work like a painter: decide what goes where, paint one object, look at the canvas, and repaint if the result is wrong. In this case study that becomes a system with a planner, a generator, a checker and a canvas. Before designing it, write down what it must do.
Functional requirements:
- Take a prompt that names several objects with colours and positions.
- Split it into single objects, each with a shape, a colour and a box on the canvas.
- Draw the objects one at a time, each on top of what is already there.
- After each object, check that the canvas now shows what was planned, and redo the object when it does not.
- Stop after a fixed number of redos, and record which objects are still unverified in the log.
Non-functional requirements decide how it is built:
| Quality | Target | What it forces |
|---|---|---|
| Correctness | Judged by code against the prompt, not by a model's opinion | Rules for count, binding and position that a program can check |
| Bounded cost | A known maximum number of model calls per picture | A redo budget per object and a limit on objects |
| Latency | Seconds per picture reported, not guessed | A timer around every stage |
| Safe inputs | A prompt is data; model replies are untrusted | Schema validation and box checks before anything is drawn |
| Honesty |
Correctness as code
"Does the picture match the prompt" sounds like a judgement call, but for a multi-object prompt most of it is a list of rules. Count the objects of each kind. Check that each has the colour the prompt gave it. Compare centres to decide left, right, above and below. A program can check all of that from a list of objects, and a program does not get tired or change its mind.
The script below holds one prompt's requirements, "two red circles left of a blue square", and four candidate layouts. Each layout is a list of colour, shape and box. The first is right. The others break one rule each.
def check(objects): """objects: list of (colour, shape, box). Returns failed rules.""" failed = [] got = Counter((c, s) for c, s, _ in objects) if got != WANT: failed.append(f"count: want [{show(WANT)}], got [{show(got)}]") squares = [b for c, s, b in objects if (c, s) == ("blue", "square")] circles = [b for c, s, b in objects if (c, s) == ("red", "circle")] for sq in squares: for ci in circles: if centre_x(ci) >= centre_x(sq): failed.append("position: a circle is not left of the " "square") break return failed
The rules for one prompt: two red circles left of a blue square.
LAYOUTS = {
"correct": [("red", "circle", [20, 100, 100, 180]),
("red", "circle", [120, 100, 200, 180]),
("blue", "square", [260, 100, 340, 180])],
"one circle too few": [("red", "circle", [20, 100, 100, 180]),
("blue", "square", [260, 100, 340, 180])],
"wrong binding": [("red", "circle", [20, 100, 100, 180]),
("blue", "circle", [120, 100, 200, 180]),
("red", "square", [260, 100, 340, 180])],
"circle on the right": [("red", "circle", [20, 100, 100, 180]),
("red", "circle", [300, 20, 380, 100]),
("blue", "square", [180, 200, 260, 280])],
}Four layouts: the first is right, each other breaks a rule.
correct pass one circle too few ['count: want [1 blue square, 2 red circle], got [1 blue square, 1 red circle]'] wrong binding ['count: want [1 blue square, 2 red circle], got [1 blue circle, 1 red circle, 1 red square]'] circle on the right ['position: a circle is not left of the square']
Output from constraints.py. No model is involved, so the output never changes. Long lines are wrapped here.
Two details are worth noticing. The count rule catches the binding mistake too, because swapping colours between objects changes the (colour, shape) pairs that are present. A position rule alone would have passed it. And each rule reports its reason as text, which becomes the message the system can hand back to the planner when a layout fails.
Part 2 · The design: plan, draw one object, check
Entities and relationships
Five things appear in every run. A prompt is the user's text. A plan is the planner's answer: a list of objects, each with a shape, a colour and a box. The canvas is the picture so far. A stage is one attempt to draw one object, and a verdict is what the checker concludes about that stage.
| Entity | Fields | Relationship |
|---|---|---|
| Prompt | text | has exactly one Plan per planning round |
| Plan | objects, in drawing order | has 1 to 8 Objects |
| Object | shape, colour, box [x0, y0, x1, y1] | has 1 to 3 Stages (first try plus two redos) |
| Canvas | pixels, 384 by 384 | is changed by one Stage at a time |
| Stage | attempt number, picture, fault (for tests) | has one Verdict |
| Verdict | what the checker saw, ok or not | decides whether the Stage is redone |
Two rules keep the relationships honest. Every try at an object starts from the canvas as it was before that object, so a failed attempt never stays under a redo. And an object has a hard limit of three stages, so a stubborn failure ends the loop instead of running forever. The stage budget is the system's cost cap: eight objects at three stages each is at most 24 generator calls and 24 checker calls per picture.
The components in motion
The planner is a language model call. It reads the prompt and returns structured data, not prose. The generator takes one object and the current canvas and returns a new canvas. The checker is a vision-language model call that looks at the new canvas and reports what it sees. A small controller in plain code owns the loop, the budget and the canvas.
MuLan's design has the same cast. Its abstract describes a language model that splits the prompt into sub-tasks, one object per stage, a diffusion model that draws each object conditioned on the objects already made, and a vision-language model that reviews each stage and asks for a redo when the image breaks the prompt. One difference is worth stating. The paper's planner makes only a high-level plan and chooses each object's size and place during its stage. Ours fixes the boxes up front, because that lets plain code validate the layout before anything is drawn.
Watch for the checker sending one object back to the generator
Read it as steps
A stage fails the check, the generator is called again and the second try passes.
The scene shows one stage going wrong. The checker does not repair the picture. It only reports, and the controller decides to call the generator again, up to the budget. That separation is the evaluator-optimiser shape from the agent design chapter: one part produces, another judges, and a loop with a cap joins them.
The planner and its schema
The planner is the only part of the system that reads free text. Everything after it works on structured data, so the planner's job is to turn a sentence into a list of objects that code can trust. It is asked for JSON in a fixed shape. A schema says which fields exist and what values they may hold: the shape is one of three, the colour one of six, the box a list of exactly four integers, and the plan holds one to eight objects.
class Obj(BaseModel): shape: Shape colour: Colour box: list[int] = Field(min_length=4, max_length=4) class Plan(BaseModel): objects: list[Obj] = Field(min_length=1, max_length=8)
The schema, written as Pydantic classes.
The schema cannot say everything. It can say that a box has four integers. It cannot say that the first is smaller than the third, that the box lies inside the canvas, or that two boxes do not overlap. Those are geometry, and they are checked by a plain function after the model has answered. The system message states the same rules in words, so the model usually gets them right, and the function is there for the times it does not.
SYSTEM = (
f"You plan a picture on a {SIZE} by {SIZE} pixel canvas. The "
"origin is the top-left corner, x grows to the right and y grows "
"downward. "
"Split the request into single objects. Give each object a box "
"[x0, y0, x1, y1] in pixels with x0 < x1 and y0 < y1, at least 40 "
"pixels on each side, inside the canvas, and not overlapping any "
"other box. List objects in drawing order."
)The planner's instructions, with the coordinate convention spelled out.
def box_errors(plan): """Return a list of messages; empty means the layout is usable.""" errs = [] for i, o in enumerate(plan.objects): x0, y0, x1, y1 = o.box if not (0 <= x0 < x1 <= SIZE and 0 <= y0 < y1 <= SIZE): errs.append(f"object {i}: box {o.box} is outside the " f"canvas or not ordered x0<x1, y0<y1") elif x1 - x0 < 40 or y1 - y0 < 40: errs.append(f"object {i}: box {o.box} is smaller " f"than 40 px") for i, a in enumerate(plan.objects): for j in range(i + 1, len(plan.objects)): b = plan.objects[j] w = min(a.box[2], b.box[2]) - max(a.box[0], b.box[0]) h = min(a.box[3], b.box[3]) - max(a.box[1], b.box[1]) if w > 0 and h > 0: errs.append(f"objects {i} and {j} overlap") return errs
Each problem becomes a sentence the model can act on.
The repair loop on ten prompts
When the layout is invalid, the controller sends the problems back as a follow-up message and asks again, once. A second failure ends the attempt with no plan. One repair keeps the cost bounded: a planner that cannot fix its layout after being told exactly what is wrong is unlikely to do so on a third try, and every extra call is paid for.
def plan_prompt(prompt, repairs=1): """Returns (plan or None, calls, notes). Bad layouts go back.""" msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}] notes = [] for calls in range(1, repairs + 2): plan, note, raw = ask_plan(msgs) errs = box_errors(plan) if plan else [note] if not errs: return plan, calls, notes notes.append("; ".join(errs)) if raw: msgs.append({"role": "assistant", "content": raw}) msgs.append({"role": "user", "content": "Fix these problems and answer again: " + "; ".join(errs)}) return None, calls, notes
At most two calls per prompt. Each failure becomes a message back to the model.
Each line of the output below is one prompt: the run number, the prompt number, whether the objects were right, whether the stated positions held, how many calls the plan took and how long, then any repair note. This is one run of ten prompts, scored by code against the expected objects.
0 1 count True rel True calls 2 9.2s ['objects 0 and 1 overlap'] 0 2 count True rel True calls 1 5.3s [] 0 3 count True rel True calls 1 7.0s [] 0 4 count True rel True calls 1 4.8s [] 0 5 count True rel True calls 1 22.6s [] 0 6 count True rel True calls 1 12.4s [] 0 7 count True rel True calls 1 14.0s [] 0 8 count True rel True calls 1 12.2s [] 0 9 count True rel True calls 1 9.3s [] 0 10 count True rel True calls 2 20.9s ['object 1: box [280, 80, 400, 250] is outside the canvas or not ordered x0<x1, y0<y1'] {'valid': 10, 'count': 10, 'rel': 10, 'repair': 2, 'n': 10}
Output from run_plan.py, run 1 of three. Times are on a shared server and vary. Long lines are wrapped here.
Two prompts needed a repair, and the notes show what the guard caught. In prompt 1 two boxes overlapped, and in prompt 10 a box ran past the canvas edge. In both cases the first reply was well-formed JSON that matched the schema, and still unusable. Without the geometry check, those boxes would have gone to the generator as they were. Both were fixed on the second call.
All ten plans in this run had the expected objects, which is not guaranteed: lesson 5 shows runs where it was not. For now the point is the split of work: the model proposes, plain code disposes.
Part 3 · A runnable stand-in for the generator
The interface a generator must meet
The controller treats the generator as a function. It gets the canvas so far and one object, and returns a new canvas. It must not change the canvas it was given, so a failed attempt can be thrown away. Everything else, including how the object gets drawn, is the generator's business.
A real implementation would put an image model behind that signature, for example one that fills a chosen region of an existing picture from a text description. The shape below is the contract only. It was not run, and no image model was used anywhere in this chapter.
def generate_object(canvas, obj, fault=None): """Return a NEW canvas with obj drawn inside obj["box"]. A diffusion-backed version would send the canvas, a mask of the box and the text "<colour> <shape>" to an image model and return the result. Shape only, not run. """
Shape only, not run: the contract the controller relies on.
Because the controller only knows the contract, replacing the stand-in with a real model later changes one function. The planner, the checker, the budget and the tests stay as they are. That is the reason to write the rest of the system first with a stand-in you can control.
The stand-in with Pillow
Pillow is a Python imaging library. The stand-in uses it to make a 384 by 384 white canvas and to draw a filled circle, square or triangle in the object's box. There are six colours and three shapes. The renderer draws no text on the canvas, on purpose: a printed label such as "red circle" would let the checker read the answer instead of looking at the shape.
def draw_shape(draw, shape, box, fill): x0, y0, x1, y1 = box if shape == "circle": draw.ellipse(box, fill=fill) elif shape == "square": draw.rectangle(box, fill=fill) else: top = ((x0 + x1) // 2, y0) draw.polygon([top, (x0, y1), (x1, y1)], fill=fill)
def generate_object(canvas, obj, fault=None): """Draw obj on a copy of canvas. fault imitates a mistake.""" out = canvas.copy() colour, shape = obj["colour"], obj["shape"] if fault == "missing": return out if fault == "wrong_colour": colour = next(c for c in COLOURS if c != colour) if fault == "wrong_shape": shape = next(s for s in SHAPES if s != shape) box = obj["box"] if fault == "similar_colour": colour = SIMILAR[colour] if fault == "too_small": # a third of the planned size x0, y0, x1, y1 = box w, h = (x1 - x0) // 3, (y1 - y0) // 3 cx, cy = (x0 + x1) // 2, (y0 + y1) // 2 box = [cx - w // 2, cy - h // 2, cx + w // 2, cy + h // 2] draw_shape(ImageDraw.Draw(out), shape, box, COLOURS[colour]) return out
The stand-in. fault imitates a mistake an image model could make.
The fault argument is what makes the stand-in useful. A real model makes mistakes you cannot schedule. The stand-in makes the ones you ask for: wrong_colour draws the right shape in the wrong colour (a binding error), wrong_shape draws the right colour as the wrong shape, and missing draws nothing (a count error). Two further faults, similar_colour and too_small, are kept for a blind-spot test in lesson 4. Since you know which stages were faulty, you can later measure how many of them the checker caught. With a real model you would need people to label every picture first.
Drawing stage by stage
The script below draws three objects one stage at a time and prints the number of non-white pixels after each stage, which should grow, plus the pixel at a point inside the object, which should have the object's colour. It then forces two faults and draws a thousand fault choices to show the rate.
canvas = new_canvas() print(f"canvas {SIZE}x{SIZE}, ink {ink(canvas)}") for i, obj in enumerate(PLAN, start=1): canvas = generate_object(canvas, obj) cx = (obj["box"][0] + obj["box"][2]) // 2 cy = (obj["box"][1] + obj["box"][3]) // 2 + 20 canvas.save(f"stage_{i}.png") print(f"stage {i}: {obj['colour']} {obj['shape']:8} " f"ink {ink(canvas):6} pixel at ({cx},{cy}) = " f"{canvas.getpixel((cx, cy))}") bad = generate_object(new_canvas(), PLAN[0], "wrong_colour") print("wrong_colour pixel at (80,210) =", bad.getpixel((80, 210))) miss = generate_object(new_canvas(), PLAN[0], "missing") print("missing ink =", ink(miss)) draws = Counter(pick_fault(f"demo-{i}", 0.35) for i in range(1000)) print("1000 draws at rate 0.35:", dict(sorted( draws.items(), key=lambda kv: str(kv[0]))))
demo_canvas.py: stages, forced faults and the fault rate.
canvas 384x384, ink 0 stage 1: red circle ink 8005 pixel at (80,210) = (220, 40, 40) stage 2: blue square ink 18206 pixel at (300,210) = (40, 80, 220) stage 3: green triangle ink 23307 pixel at (190,90) = (40, 160, 70) wrong_colour pixel at (80,210) = (40, 80, 220) missing ink = 0 1000 draws at rate 0.35: {None: 666, 'missing': 122, 'wrong_colour': 109, 'wrong_shape': 103}
Output from demo_canvas.py. The pictures are saved as stage_1.png to stage_3.png; they are described here, not shown. Long lines are wrapped here.
Reading the output: ink grows from 0 to 8,005, 18,206 and 23,307 pixels, so each stage added something. The pixels sampled inside the objects match the palette's red, blue and green. A forced wrong_colour fault drew blue where red was planned, and a forced missing fault left no ink at all. Over a thousand deterministic draws at a rate of 0.35, 666 were clean, which is close to the 65 per cent expected, and the other 334 split between the three faults. The draws are seeded by a string, so the same run produces the same faults every time. That matters when you compare two versions of the checker: both see the same mistakes.
One more property to remember. The stand-in is easy to check because it is simple: flat colours on white. A checker that works here may fail on real generated images, with texture, lighting and partial overlap. Passing this chapter's check is evidence about the loop, not about a real model's pictures.
Part 4 · Checking each stage
Describe, then compare
The checker has to answer one question: does the object just drawn match the plan? The obvious way to ask is "Is there a red circle in this picture?" and read yes or no. That question leads the witness: it names the answer it hopes for. This chapter did not measure how strongly that sways a model, and the design avoids the question. It asks a neutral one and compares in code.
The vision model is shown a crop of the canvas around the object's box, with a margin of 16 pixels, and asked for the colour and the shape of the main coloured shape it sees. Both answers come from fixed lists, with none for a blank crop. The controller then compares the two answers with the plan. The crop matters for two reasons: the object fills more of the image, and the neighbouring objects are mostly out of the frame, so a correct object elsewhere cannot hide a missing one here.
class Seen(BaseModel): colour: Literal[tuple(COLOURS) + ("none",)] shape: Literal[tuple(SHAPES) + ("none",)]
def look(image): """Returns (Seen or None, note). Bad replies never raise.""" msgs = [{"role": "user", "content": [ {"type": "text", "text": ASK}, {"type": "image_url", "image_url": {"url": to_data_url(image)}}]}] try: r = client.chat.completions.parse( model=MODEL, messages=msgs, response_format=Seen, max_tokens=60, reasoning_effort="none") except LengthFinishReasonError: return None, "truncated" m = r.choices[0].message if m.parsed is None: return None, "unparsable" return m.parsed, ""
One call. A truncated or invalid reply returns a note, never an exception.
def verdict(canvas, obj): """True when the crop around obj's box shows what the plan wants.""" seen, note = look(crop_for(canvas, obj["box"])) if seen is None: return False, None, note # no answer counts as a failed check ok = seen.colour == obj["colour"] and seen.shape == obj["shape"] return ok, seen, ""
The comparison is plain code. No answer counts as a failed check.
Two choices in verdict are deliberate. A reply that could not be read counts as a failed check, so the object is redone, instead of being waved through. And the comparison is exact: colour and shape must both match. Five small tests run these rules against scripted answers, with no model and no picture sent.
The redo loop
The controller walks the plan in order. For each object it asks the generator for a new canvas, asks the checker about it, and stops at the first pass. It allows two redos, so an object gets at most three tries, and each try starts from the canvas as it was before the object. After the last try the canvas keeps that try, passed or not. A real system would mark an object that never passed as unverified in its output instead of hiding it, and the log here records it for that reason.
canvas = new_canvas()
for i, o in enumerate(plan.objects):
obj = o.model_dump()
for attempt in range(REDOS + 1):
seed = f"{RUN}-{spec['id']}-{i}-{attempt}"
fault = pick_fault(seed, RATE)
t = time.time()
trial = generate_object(canvas, obj, fault)
ok, seen, note = verdict(trial, obj)
rec["stages"].append({
"obj": i, "attempt": attempt, "fault": fault, "ok": ok,
"seen": seen.model_dump() if seen else note,
"sec": round(time.time() - t, 1)})
if ok:
break
canvas = trial # keep the last try, ok or notFrom run_stages.py: the loop over objects, with the stand-in's faults switched on.
In the test runs the generator is told to fail on purpose. Each try draws a fault with probability 0.35, chosen from the three faults by a seed built from the run, the prompt, the object and the attempt. The seed makes every run repeatable. It also means that a redo is a fresh draw, not a repeat of the same failure, which is also how an image model behaves when you sample it again.
Watch for the same object failing twice before it passes
Read it as steps
What the checker caught
Ten prompts were run twice, 20 pictures in all. One plan was never valid after its repair, so 19 pictures reached the drawing stage. The generator made 81 attempts in total, and the script knows for each one whether a fault was injected, which is what lets us score the checker.
images 19, stages 81 faulty stages 29: caught 28, missed 1 clean stages 52: false alarms 0, passed 52 missing caught 9/10 wrong_colour caught 11/11 wrong_shape caught 8/8 images right with no checker 8/19 images right with checker 15/19 redos per object {0: 39, 1: 9, 2: 8} objects per image 2.9, attempts per object 1.45 model calls per image: mean 5.4 min 3 max 10 seconds per image: median 29.6, min 5.4, max 74.1
Output from analyze.py over both runs. One model, these runs. Times vary on this machine.
Read the first block as a confusion table. Of 29 faulty attempts, the checker flagged 28 and missed one. Of 52 clean attempts, it flagged none. That is a near-perfect score on this test, and the next two paragraphs say why it is less impressive than it sounds. The second block is the payoff: with no checker, 8 of 19 pictures came out exactly right, and with the checker and two redos, 15 of 19. Three of the four others had an object whose three tries all drew a fault, which at a rate of 0.35 happens for about 4 objects in 100. The fourth is the miss.
The miss is worth reading. In the second run the prompt was "three yellow circles in a row across the middle" and the planner put the circles in boxes 10 pixels apart. The generator drew nothing for the middle circle, and the checker said it saw a yellow circle. The crop around a box reaches 16 pixels past it, which is more than the gap, so the crop held the edge of a neighbouring circle. The earlier paragraph said neighbours are mostly out of the frame; here they were not, and a correct object next door hid a missing one. Two fixes follow from it: leave gaps wider than the crop margin, or shrink the margin. An earlier saved run of the same ten prompts did not miss, and the faults are seeded, so the difference comes from different plans.
Where the checker is blind
Why the perfect score is not a promise. The shapes are flat colours on white, the crop is tight, and the faults are blunt. A second test gives the checker faults it was not designed to see: a colour that is close to the right one, and an object drawn at a third of its planned size.
BOX = [120, 120, 264, 264] stages = [] for colour in COLOURS: for shape in SHAPES[:2]: stages.append({"colour": colour, "shape": shape, "box": BOX}) tally = Counter() for fault in (*HARD_FAULTS, None): for obj in stages: canvas = generate_object(new_canvas(), obj, fault) ok, seen, note = verdict(canvas, obj) tally[(fault, ok)] += 1 for fault in (*HARD_FAULTS, None): flagged, passed = tally[(fault, False)], tally[(fault, True)] print(f"{str(fault):15} flagged {flagged:2} passed {passed:2}")
Twelve stages per condition: two hard faults and a clean control.
similar_colour flagged 12 passed 0 too_small flagged 0 passed 12 None flagged 0 passed 12
Output from hard_faults.py. One model, one run.
The checker flagged all 12 close-colour stages, so it can tell orange from red and purple from blue on flat shapes, which is better than a reader might expect. It flagged none of the 12 too-small objects. Every one passed, because the check asks about colour and shape and nothing else, and a small red circle is still a red circle. The 12 clean controls produced no false alarms. The lesson is general: a check covers what it asks and nothing more. The failure to catch size would show up only in a test that included size, which is why the benchmark advice in the next lesson groups prompts by failure kind.
The checker flagged 28 of 29 faults and 0 of 52 clean attempts. Why is that not proof it works on real generated images?
- The shapes are flat colours on white, the crop is tight, and the injected faults are blunt. Real images have texture, lighting and partial overlap.
- The score shows the loop and the checker work together on this stand-in, nothing more.
Why is a checker answer that cannot be read treated as a failed check?
- Passing an unchecked object would hide a possible fault. A failed check costs one redo.
- The cost of a false alarm is a repeated call; the cost of a missed fault is a wrong picture.
Part 5 · Evaluation and review
Measuring the whole system
There are three things to measure, and they answer different questions. Does the plan fit the prompt? The planner is scored in code: the right count of each (colour, shape) pair, and each stated relation true. Does the checker see what it should? That needs known faults, which is why the stand-in generator injects them. Does the loop improve the picture at a cost worth paying? That compares pictures right with and without the checker, and counts calls and time.
Three planner runs of the ten prompts give 30 requests. In these three planner-only runs all 30 layouts were usable. 27 of the 30 had the right objects, and all 30 had the stated positions right. Four of the 30 needed a second call because a box was outside the canvas or two boxes overlapped, and all four were repaired. The two separate runs that also fed the checker test made 20 plans, and one of them stayed invalid after its repair. Look at the misses, because they are informative.
0 1 count True rel True calls 1 4.7s [] 0 2 count True rel True calls 1 14.3s [] 0 3 count True rel True calls 1 8.5s [] 0 4 count True rel True calls 1 9.8s [] 0 5 count False rel True calls 1 5.4s [] plan: [('blue', 'circle', [160, 100, 224, 160])] 0 6 count True rel True calls 1 7.3s [] 0 7 count True rel True calls 1 5.5s [] 0 8 count False rel True calls 1 13.5s [] plan: [('yellow', 'square', [152, 160, 232, 224]), ('purple', 'circle', [80, 160, 130, 224]), ('purple', 'circle', [254, 160, 304, 224]), ('purple', 'circle', [166, 110, 218, 150]), ('purple', 'circle', [166, 234, 218, 274])] 0 9 count True rel True calls 1 22.7s [] 0 10 count True rel True calls 1 14.9s [] {'valid': 10, 'count': 8, 'rel': 10, 'repair': 0, 'n': 10}
Output from run_plan.py, one of the three planner runs. Each line is run, prompt, count right, relations right, calls, seconds and any repair note. The last line is the tally. Long lines are wrapped here.
Three layouts had the wrong objects, and they are two kinds of miss. Prompt 5, "a blue circle above an orange square", got a plan with only the blue circle: the planner dropped an object, and its box was perfectly valid, so the geometry check could not see it. A count against the prompt is a separate check, and this chapter's loop does not make one before drawing. The other two were the prompt "a yellow square in the centre with a purple circle on each side": both times the planner drew four purple circles around the square, as in the listing above. That is an ambiguous prompt more than a planner mistake, since "each side" can mean left and right or all four. The scoring rule expected two, so it counted a miss. A good benchmark either avoids ambiguous prompts or accepts every reasonable reading, and this one did neither.
Cost and time per picture
Every picture costs one planner call, plus one checker call per attempt. The stand-in generator is free. The scene works the numbers out from the 19 pictures that reached drawing.
Time per picture: median 30 s (shared server; quickest 5 s, slowest 74 s)
Read it as steps
Calls and time for one picture, from nineteen recorded pictures.
The call count is steady and small: 5.4 on average, between 3 and 10. The time is not. The median picture took 30 seconds, the quickest 5 and the slowest 74. A stage, which is one generator call and one check, took a median of 5.1 seconds and at the quickest 0.6. The model server is shared with other jobs, so some of that time is waiting in a queue: the first run had a median stage of 3.1 seconds and the second 5.6. Timings on this machine vary from run to run. The structure is the thing to remember: time grows with objects times attempts, and a real generator would add its own time to every attempt.
A real diffusion generator changes the balance. Each attempt would take far longer than a check, so the redo budget becomes the main cost control. A budget of two redos on four objects means up to twelve generator calls. Whether the fewer wrong pictures are worth that depends on what a wrong picture costs the user, and no number in this chapter answers that.
Design review and extensions
The system works end to end on its stand-in. A reviewer would ask where it is thin. The table lists the main extensions, what each one buys and what it costs.
| Extension | What it buys | What it costs |
|---|---|---|
| Pass the checker's reason to the next try | Fewer wasted redos | A generator that can use a hint; longer prompts |
| Check position and size, not only colour and shape | Catches the too-small and moved objects that passed | More fields to compare and a harder vision question |
| Check the whole canvas at the end | Catches an object that a later one covered | One more call, and a rule for which object to redo |
| Let the user edit between stages | Corrections early, where they are cheap | State to keep and a user interface |
| A bigger redo budget | More pictures right | More calls and more time per picture |
| Plan boxes per stage, not up front | Closer to the paper's design, flexible layouts | Boxes are no longer validated before drawing |
Breakout prompts for you to work through, with no model needed:
- The checker passed an object that is too small. Which of its inputs would you change, and what would the new rule cost in false alarms?
- A prompt asks for "a red circle behind a blue square". Which entity in the design has to change to represent depth, and which rule in the constraint checker?
What the chapter shows
The most important limit to restate is the first one. Nothing here ran a real image model. The planner, the checker, the redo loop and the tests are real, and the numbers come from them. The claim they support is that the loop catches the faults it is built to catch, and no claim is made about how well it does with real pictures.
| Term | Meaning |
|---|---|
| Text-to-image model | A model that makes a picture from a text prompt |
| Diffusion model | A text-to-image model that refines noise into an image |
| Attribute binding | Attaching the right colour or size to the right object |
| Planner | The step that splits a prompt into objects and boxes |
| Checker | A vision model that reports what it sees on the canvas |
| Redo budget | The most extra tries an object gets after a failed check |
| Stand-in generator | A simple renderer used in place of a real model |
A user wants a smaller cost per picture and accepts a few wrong ones. Which one setting would you change first?
- The redo budget: lowering it from two to one or zero cuts the worst case, at the price of more wrong pictures.
- The checker could also use a smaller crop or image, which cuts the cost of each check.
Why is a ten-prompt test a smoke test and not a benchmark?
- Ten prompts cannot separate failure kinds or show a difference bigger than the noise, and one prompt was ambiguous.
- A benchmark needs prompts grouped by failure type, checkable specifications and a held-out set.