Ask a robot to stack some blocks, and a language model writes the program. The program calls perception to find things and motion primitives to move them. The robot needs no new training data.
Learn how a code-writing model turns words into a robot policy, why the level of the API decides how often it works, and how feedback loops grew it into today's coding agents.
Pick an instruction and press Run. Watch each line of the program drive the arm. One grasp is rigged to slip: turn Feedback off and see what the program misses.
You need a little Python and a rough idea of what a language model is. We build the rest from zero.
A toy. The programs are fixed, written in the style of the paper's generated code, not produced live by a model. The block, bowls and the rigged slip are made up. The pattern (perception calls feed numbers to control primitives, and Python glues them together) is the paper's CaP · Fig. 1, §III.
Chapter 0
Meet the problem: every new sentence a person says asks the robot for a new behaviour
You have a robot arm over a table. On the table are three blocks and two bowls. You say: "stack the blocks on the empty bowl." Then: "now put them in a line." Then: "move block A a bit to the right."
Each sentence asks for a different behaviour. A person would just do it. A robot needs a policy for each one: a rule that turns what it sees into what it does. Where does a new policy come from, every time someone speaks?
One answer is to train it. Collect thousands of demonstrations of "stack the blocks", and fit a network. That works for the sentences you trained on. But people keep saying new things: "a bit to the right", "the block nearest the bowl", "wait until you see an egg".
Code as Policies gives a second answer. A language model that writes code reads the sentence. It writes a short Python program. The program calls a few primitives, ready-made functions that the robot already has: one to find objects, one to pick and place. Python's loops, if-statements and arithmetic glue them into the new behaviour.
Pick an instruction. The left robot can only run skills it was trained on. The right robot writes a program from three primitives. See which instructions each one can follow.
Illustrative. The skill menu stands for a policy trained on a fixed set of tasks. The instructions echo the kinds the paper runs: relative moves like "a bit", spatial ones like "nearest", and reactive ones like "wait until you see" CaP · §I, Fig. 2.
The trained robot covers one instruction family per skill. Each new family costs new data and retraining. The paper puts it plainly: with skills learned end to end, "the data burden persists" CaP · §I. The programmer covers anything it can spell out with its primitives and Python.
Chapter 1
Define a policy as a map from observation to action, then tune the simplest one, a controller that chases a target
A thermostat reads the room temperature and switches the heater. A driver sees the road and turns the wheel. Both follow a rule from what they sense to what they do. In robotics that rule is a policy.
The observation is what the robot senses at one moment: a camera image, joint angles, a list of detected objects. The action is what it sends to its motors: a target position, a velocity, open or close the gripper. The policy maps one to the other, again and again.
Here is the smallest useful policy. The gripper is at position x. The block is at x*. Each step, move a fraction K of the remaining gap:
Worked numbers. Start at x = 0 with the block at x* = 50 cm and K = 0.4. Step 1: a = 0.4 × 50 = 20, so x = 20. Step 2: a = 0.4 × 30 = 12, so x = 32. Step 3: x = 39.2. The gap shrinks by the factor 1 − K = 0.6 every step. With K = 1.5 the factor is −0.5: the gripper overshoots and swings back. Above K = 2 the swings grow and the arm runs away.
The gripper starts at 0 cm and chases a block at 50 cm. Drag the gain K. Add sensor noise and watch a high gain chase the noise.
A toy, one dimension, 30 steps. Noise is added to the measured block position each step, with a fixed random seed so the curve is repeatable.
This is a closed-loop policy: it measures, acts, and measures again, so it corrects its own errors. Code as Policies can write exactly this kind of thing. The paper shows generated code for a PD controller that balances a cartpole, and for an end-effector impedance controller CaP · App. F. It also writes loops such as "while not detect_object('apple'): move right" CaP · §I.
Chapter 2
Contrast policies learned end to end from demonstrations with programs that compose primitives, and read the paper's head-to-head test
There are two big families of robot policy that take language.
Learned end-to-end policies map raw pixels and an instruction straight to actions with one network. Today's version is the VLA, a vision-language-action model. A typical VLA takes a camera image (say 224 × 224 × 3 numbers) plus the instruction's tokens. It outputs an action vector, often seven numbers: a change in position, a change in rotation, and the gripper command. It runs many times a second.
You train it by behaviour cloning: show it what an expert did, and push its output toward the expert's action.
Worked numbers, with a one-number action. Two demonstration steps: the expert moved +2 and −1. The network says +1.5 and 0. The loss is ((1.5 − 2)2 + (0 − (−1))2) / 2 = (0.25 + 1) / 2 = 0.625. Gradient descent nudges θ to shrink it. The network only learns the situations its data covers.
Programs are the other family. People build a perception module and a few control primitives. Something writes a program that wires them together. In 2022 the writer was a person. Code as Policies made it a language model, with no robot data at all.
The paper compares three systems in a simulated tabletop with 10 coloured blocks and 10 coloured bowls CaP · §IV-D. CLIPort is a learned language-conditioned policy, trained by imitation on 30k demonstrations. The NL Planner is a language model prompted to write a plan in English steps. CaP writes code, prompted with one example rollout per task CaP · §IV-D.
The tasks split into "seen" and "unseen". Seen attributes (SA) are colours, corners and so on that appear in training or in the prompt. Unseen attributes (UA) and unseen instructions (UI) never appeared. Each task runs 50 trials CaP · Table III.
Move from seen to unseen. Watch the learned policy's bars, and compare them with the program's.
All numbers are the paper's success rates in percent, 50 trials per task CaP · Table III. "n/a": the language planner cannot express tasks that need precise numbers, so the paper does not run it on the spatial-geometric family.
On seen tasks, CLIPort is strong: 97.33% on the spatial-geometric family, above CaP's 89.30%. On unseen attributes it collapses: 0.00% on spatial-geometric tasks, where CaP keeps 73.33%. With unseen instructions too, CaP still reaches 80.00% and 62.00% CaP · Table III. The paper's reading: end-to-end systems like CLIPort "struggle to generalize", and code beats reasoning in plain language CaP · §IV-D.
Chapter 3
Build the prompt from hints and examples, see what the model writes without each part, and run the result safely
The model in the paper is OpenAI Codex, code-davinci-002, run at temperature 0 CaP · §III-B. Temperature 0 means greedy decoding: at every step it writes the single most likely next token. The same prompt always gives the same code.
The prompt has two parts CaP · §III-A:
from utils import get_pos, put_first_on_second.The new instruction goes last, as one more comment. The model continues the text, and its continuation is the policy code.
from utils import get_pos, put_first_on_second # hint objs = ['blue bowl', 'red block', 'red bowl', 'blue block'] # move the purple bowl toward the left. # example target_pos = get_pos('purple bowl') + [-0.3, 0] put_first_on_second('purple bowl', target_pos) # move the red block a bit to the right. # new instruction target_pos = get_pos('red block') + [0.1, 0] # the model writes this put_first_on_second('red block', target_pos)
That snippet is from the paper's method section CaP · §III-B. Look at "a bit": the example used 0.3 for "toward the left", and the model chose 0.1 for "a bit". That is behavioural common sense: the model maps vague words to sensible numbers.
Turn the hints and the examples on and off, and pick an instruction. The bar shows how the prompt fills the context. The listing shows what the model writes.
Illustrative outputs and token counts. They show the failure kinds the paper's appendix describes: missing arguments, wrong types, and APIs used wrongly when hints and examples are missing CaP · App. A.
The prompt has a budget. Every example costs tokens, and the whole prompt must fit the model's context window:
Worked numbers, illustrative: hints of 60 tokens, examples of 90 tokens each, 300 tokens for the instruction and answer, and a 4,000-token limit. Then 60 + 90k + 300 ≤ 4,000, so k ≤ 40. The paper meets this limit with a design choice: split the work across several prompts, one per job, and let them call each other CaP · §III-C. One parses object names, one parses positions, one writes new functions.
The output is a string. To run it, the paper first checks it: no import statements, no names that begin with two underscores, no calls to exec or eval. Then it calls Python's exec with two dictionaries. The globals hold every API the code may call. The locals start empty and collect any variables and functions the code defines CaP · §III. Here is that runner, from scratch:
def is_safe(code): banned = ['import ', '__', 'exec(', 'eval('] return not any(b in code for b in banned) def run_lmp(llm, prompt, instruction, apis): code = llm(prompt + '\n# ' + instruction + '\n', temperature=0) if not is_safe(code): raise ValueError('unsafe code') scope = {} # locals: filled by the code exec(code, dict(apis), scope) # globals: only the robot's APIs return scope.get('ret_val') # some prompts return a value
Chapter 4
Step a generated program line by line and watch perception calls turn into numbers, and numbers into motion
A code policy touches the world through two kinds of API.
Perception APIs turn sensor data into symbols and numbers. In the real tabletop the paper used MDETR, an open-vocabulary detector: you give it a phrase like "blue block", and it returns a box and a mask CaP · §IV-C, App. G. The API wraps that: get_obj_pos(name) returns a 2D position, get_bbox(name) a bounding box, is_obj_visible(name) a yes or no CaP · App. I.
Control primitives turn numbers into motion. The tabletop robot had one main primitive: put_first_on_second(obj, target). It moves the suction gripper above the object, moves down until contact, sucks, then does the same at the target and releases CaP · App. I. There is also say(message) for speech.
So the data flow of every line is the same. Perception gives state, Python computes, a primitive acts:
Worked numbers for "move block A a bit to the right". get_pos('A') returns (0.18, 0.62) metres. Python adds [0.1, 0] and gets (0.28, 0.62). pick_place('A', (0.28, 0.62)) moves it. Three numbers in, ten centimetres of motion out.
Pick an instruction and a version of the program. Press Step to run one line. Blue boxes are perception calls; warm motion is a control primitive; a purple bar marks the line now running.
A toy with fixed programs. Our pick_place plays the role of the paper's put_first_on_second, and detect plays its perception APIs. Positions are in metres on a 1 m table. The three buggy programs show three real kinds of error: an invented API, a quiet logic bug, and a wrong number for a vague word.
Try the buggy versions. The first one crashes at once: detect_containers does not exist. The second runs to the end without any error, but leaves block C out of the line. The third obeys "a bit" with 60 cm. Only the first one announces itself. The other two need someone, or something, to look at the table afterwards. That is Chapter 7.
np.linspace(left, right, 2) for three blocks. What happens?Chapter 5
Let the model call functions that do not exist yet, then generate them depth first, and see why that writes better code
Long programs fail more often. Suppose each line is right with probability p, and the lines fail independently. Then a program of L lines is all right with probability:
Worked numbers, illustrative: with p = 0.98, a 10-line program is right 0.9810 ≈ 82% of the time. A 30-line one is right 0.9830 ≈ 55% of the time. Lines are not truly independent, but the shape holds: length costs reliability.
The paper's fix is hierarchical code generation. The model may call a function that does not exist yet, if its name says what it does. Then the system parses the code's syntax tree, finds the undefined names, and asks a function-writing prompt to define each one. It repeats on each new body, depth first CaP · §III-C. Each piece stays short, and it is written with its own focused prompt.
The instruction is the paper's own: "while there are blocks with area bigger than 0.2 that are left of the red bowl, move them toward the right." Press Next to find and write the next undefined function. Switch to Flat to see one long function instead.
The functions and their code are the paper's worked example CaP · §III-B, §III-C. The tree layout and the step order are our drawing of its depth-first procedure.
Here is that procedure in Python. The ast module finds every call to a plain name; anything not defined and not a known API is "yet to be defined".
import ast def undefined_calls(code, known): tree = ast.parse(code) called = {n.func.id for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)} defined = {n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)} return called - defined - set(known) def define_all(fgen_llm, code, known): for name in undefined_calls(code, known): body = fgen_llm(f'# define function: {name}.') # the function-writing prompt known[name] = body define_all(fgen_llm, body, known) # depth first return known
The paper built RoboCodeGen: 37 function-writing problems about robotics. They cover spatial reasoning, geometry such as "is one box inside another", and control such as PD control. Function headers have no docstrings, and NumPy is allowed CaP · §IV-A. Success means the code passes human-written unit tests.
| Method | GPT-3 6.7B | GPT-3 175B | Codex cushman | Codex davinci |
|---|---|---|---|---|
| Flat | 3 | 68 | 54 | 81 |
| Hierarchical | 5 | 84 | 57 | 95 |
Pass rates in percent on RoboCodeGen CaP · Table I. Hierarchical wins for every model, and bigger models do better. It also helps on general code: on HumanEval, the standard 164-problem coding test, P@1 rises from 34.9% to 39.8% and greedy decoding from 45.7% to 53.0% CaP · Table II. The gain is largest on "productivity": instructions that need longer or deeper code than the examples. The gain appears only for the two davinci models, not cushman CaP · §IV-A.
Chapter 6
Place blocks on a diagonal by guessing in words or by computing in code, and see why code wins at geometry
"Put the blocks in a diagonal line." A plan in English says "place block 1 at the top left, block 2 a bit further down…". Somebody still has to turn "a bit further" into centimetres. Code just computes the points.
Points evenly spaced from a to b come from linear interpolation:
np.linspace(a, b, n).Worked numbers. From a = (10, 50) cm to b = (50, 10) cm with n = 3: p0 = (10, 50). p1 = (10, 50) + 0.5 × (40, −40) = (30, 30). p2 = (50, 10). One line of NumPy, exact to the millimetre.
Pick how the model reasons, and how many blocks to place. Each ring is 1 cm around the true point; the paper's test counts an answer as right only inside it.
The language answers are simulated: each coordinate is off by a random amount, larger for plain answers than for step-by-step ones, with a fixed seed. Only the code answer is exact by construction. The real measurements are in the table below.
The paper tested this directly. It built 28 object-selection questions ("find the block closest to the blue bowl") and 23 position-selection questions ("interpolate 3 points on a line from the cyan bowl to the blue bowl"). A position counts as right only if every coordinate is within 1 cm CaP · App. C.
| Task | Plain language | Chain of thought | Code (LMP) |
|---|---|---|---|
| Object selection | 39 | 68 | 96 |
| Position selection | 30 | 48 | 100 |
| Total | 35 | 58 | 98 |
Success in percent CaP · Table IV. Chain of thought helps with order and relations, but "failures occur for precise and multi-step numerical computations". Code hands those to Python CaP · App. C.
Chapter 7
Look at the table after each step, retry what failed, and send errors back to the model
A real gripper slips. A detector misses a block in shadow. A program that never looks again cannot notice. It reports success while the block lies on the table.
The fix is execution feedback: after a step, observe again and check the result. If the check fails, retry. If Python raises an error, give the error text back to the model so it can rewrite the line. Code makes the first kind easy to write: a while loop around the primitive.
pick_place(blk, target) while not on(blk, target): # look again with perception pick_place(blk, target) # retry from the block's new position
How much does a retry buy? If one attempt works with probability p, and you allow r retries:
Worked numbers, illustrative: p = 0.7 and r = 2 give 1 − 0.33 = 1 − 0.027 = 97.3%. A task with three picks then works 0.9733 ≈ 92% of the time, against 0.73 ≈ 34% with no checks. The formula assumes a failure is detectable and leaves the block where a retry can reach it.
A slip is rigged on one grasp. Run with Feedback off, then on. Try the buggy program with Feedback on: the error goes back to the model and it rewrites the line. Switch the API level to watch the same task in low-level calls.
A toy. Green lines are the feedback code; they appear only with Feedback on. The rewrite of a buggy line stands for a second model turn that sees the error, as in the multi-turn agents of Chapter 10. The original 2022 system had the perception loops but did not send errors back to the model.
Which parts of this did the 2022 paper have? It had loops over perception, such as "while the red block is left of the blue bowl, move it right 5 cm at a time" CaP · §III-C. It did not feed execution results back to the model. Its appendix says that tuning a controller "based on execution feedback" is "something our method does not support at the moment" CaP · App. F. The authors also tried letting a model edit buggy code, and found the results inconsistent, so they did not use it CaP · App. A.
Chapter 8
Lower the level of the primitives from pick-and-place to masks and inverse kinematics, and watch success fall and feedback claw it back
The 2022 paper gave the model one strong primitive, put_first_on_second. Somebody had already solved grasping, motion and placing inside it. How much of the success came from the model, and how much from that primitive?
CaP-X (Fu et al., ICML 2026) asked exactly this CaP-X · §1. Its benchmark, CaP-Bench, runs coding agents on manipulation tasks at four single-turn tiers. S1 and S2 offer high-level, human-designed primitives (S1 with exact simulator state, S2 with real perception). S3 and S4 replace them with low-level ones such as solve_ik() and a SAM 3 segmentation call, with usage examples in S3 and without in S4 CaP-X · §3.1.
The finding, in the paper's words: "task success rates improve with human-crafted abstractions but degrade as these priors are removed" CaP-X · abstract. Averaged over the closed-source models, success climbs from 17.5% at S4 to 20.8% at S3, 35.5% at S2 and 55.6% at S1 CaP-X · Fig. 17, averaged in our CaP-X lesson. Human experts using the same primitives averaged 88.5% CaP-X · §3.3.
Why would lower-level calls hurt? Chapter 5's formula answers. A pick at the high level is one line. At the low level it is many: find the mask, compute a grasp pose, solve inverse kinematics, move, close the gripper, lift. Every line is one more chance to be wrong.
Worked numbers, illustrative: at the high level L = 6 and q = 0.975, so qL ≈ 0.86. At the low level L = 30 and q = 0.935, so qL ≈ 0.13. With X = 0.68 in both, that is about 59% against 9%. Same model, same task, different API.
Pick an API level and run 50 trials of the stacking task. Then turn on Feedback and run again. The listing shows the code for one pick at that level.
The success rates here come from the toy formula above, with illustrative q, L and X; feedback lets some code errors be fixed and lets failed grasps retry twice. They are not CaP-X's numbers, which are in the text. The low-level listing is illustrative; its solve_ik and sam3_text_prompt follow the kinds of primitive CaP-X names. The direction matches the paper: lower abstraction costs success, and feedback recovers much of it.
Feedback changes the picture. With multi-turn feedback, CaP-X reports that agents working only with low-level primitives "not only surpass high-level single-turn (S2) but can reach parity with high-level multi-turn performance" CaP-X · §3.3. For Gemini-3-Pro, the low-level single-turn tier S3 averages 24%; add multi-turn feedback with a visual differencing module (tier M4), and it reaches 55% CaP-X · Fig. 8.
Chapter 9
Trace four failure kinds to the layer where they start and the layer, if any, that can catch them
A code policy is a stack of layers: the instruction, the prompt, the model, the safety check, Python, the perception API, the control primitive, and the world. A failure starts in one layer. It shows up, or hides, in another.
A task works only if every layer works. If the layers fail independently, the chances multiply:
Worked numbers, illustrative: code right 90%, perception right 85%, control right 90%. Then P(task) = 0.9 × 0.85 × 0.9 ≈ 69%. A perfect model still leaves 23% of the failures to the other layers.
Pick a failure. The red dot marks where it starts. A green tick marks the layer that catches it. Toggle Feedback to see what changes.
The four kinds come from the paper's limitations and appendix CaP · §V, App. A, App. G. Where feedback can catch each one is our summary, in line with CaP-X's multi-turn results CaP-X · §3.3.
Chapter 10
Follow the idea from one-shot programs to multi-turn coding agents that test their code and keep the skills that work
The 2022 system wrote a program once and ran it. By 2026 the writer is a coding agent: a model in a loop. It writes code, runs it, reads the result, and writes again. Two ideas did most of the work: execution feedback (Chapter 7) and a skill library, a growing store of verified functions the agent can call later.
The earlier non-robot example is Voyager (Wang et al., 2023), an agent that plays Minecraft by writing code with GPT-4. It has three parts: an automatic curriculum, "an ever-growing skill library of executable code", and iterative prompting with "environment feedback, execution errors, and self-verification" Voyager · abstract. A skill joins the library only after it works. Voyager reports 3.3× more unique items, 2.3× longer distances, and key tech-tree milestones up to 15.3× faster than the prior best Voyager · abstract.
Press Next task. Each task needs some helper skills. With the library on, verified skills are reused and only new ones are written. With it off, the agent writes every helper again.
Illustrative. The task list, skill names and line counts are made up to show the mechanism that Voyager, CaP-X and ASPIRE share: verified code is stored and reused, so later tasks need fewer fresh lines.
CaP-X turned its benchmark findings into an agent, CaP-Agent0, with no training. It adds three things to a low-level coding agent CaP-X · §4. A visual differencing module uses a vision-language model to describe in text what changed after each turn. An auto-synthesized skill library holds 9 verified, task-agnostic functions mined from successful runs. Parallel reasoning merges several drafts, from one or three models, into one program.
Start from a one-shot low-level program. Press Add to bring in the next ingredient. The dashed line is the human expert average.
The paper's numbers: Gemini-3-Pro, average over 7 CaP-Bench tasks, 100 trials per task CaP-X · Fig. 8, Table 5. The human line is the experts' 88.5% single-turn average CaP-X · §3.3.
The full agent matches or beats the human experts' code on 4 of the 7 tasks CaP-X · §4.1, while working only with low-level primitives. The skill library is the old Code as Policies idea of accumulated functions, now grown from verified runs instead of written once.
ASPIRE (Lu et al., NVIDIA GEAR, 2026) goes further ASPIRE · abstract. It is "a continual learning system that autonomously writes and refines robot control programs in a code-as-policy paradigm". It has three parts. A closed-loop execution engine exposes detailed traces, so the agent can diagnose and repair failures. A skill library "distills validated fixes into reusable, transferable robotic knowledge". An evolutionary search generates many programs and debugs them. It reports gains over prior methods of up to 77% on manipulation under perturbation, 72% on Robosuite's bimanual handover, and up to 32% on long-horizon household tasks. On unseen long-horizon tasks it reaches 31% success, against 4% for prior methods ASPIRE · abstract.
Chapter 11
Choose between a code policy and a learned one for a job, collect the cheat sheet, and follow the links
Code policies and learned policies are not rivals so much as layers. The question for a real system is which layer does which job. The toy below encodes the trade-offs from this lesson.
Switch on the properties your job has. The bars score three designs.
A rule of thumb, not a measurement. Each property adds or removes points from each design, following the strengths and limits in Chapters 2, 6, 8 and 9.
| Idea | In one line |
|---|---|
| Policy | at = π(ot): any map from observation to action, network or program. |
| Code as Policies | A code-writing LLM turns an instruction into Python that calls perception and control APIs. |
| Prompt | Hints (imports) plus examples (comment, then code); greedy decoding at temperature 0. |
| Execution | Check for imports, dunders, exec and eval; then exec with APIs as globals and empty locals. |
| Hierarchical generation | Call undefined functions; find them in the syntax tree; write each depth first. RoboCodeGen 81 → 95% (davinci). |
| Code for geometry | Let NumPy do the maths: 98% against 58% for chain of thought on spatial questions. |
| Generalization | Unseen attributes: CLIPort 0.00%, CaP 73.33% on spatial-geometric tasks. |
| Feedback | Look again after each step and retry: 1 − (1 − p)r+1. |
| Abstraction | Higher APIs raise success and lower expressivity; CaP-X S4 → S1: 17.5 → 55.6%. |
| Agentic turn | Multi-turn feedback plus verified skill libraries: Voyager, CaP-Agent0 (24 → 68.29%), ASPIRE. |
The paper's quantitative robot results are in simulation; its real-robot domains are demonstrations "without quantitative evaluations" CaP · §IV. It used a single code model, Codex. Its success depends on the primitives people wrote, and CaP-X shows how much. And code is a poor medium for contact-rich skill; that remains the learned policy's job.
Code as Policies sits between two older lines of work. Language planners such as SayCan pick from a fixed set of skills; the paper's example is that they assume a skill like "move a bit right" already exists CaP · §II. End-to-end policies learn everything from data. Code as Policies writes the glue itself. Today it is the root of the coding-agent line in robotics, and it is the background for the agentic vision path.
Now press Present or Teach and explain, out loud and from memory, how a sentence becomes robot motion in Code as Policies, and why the API level matters. Then go back to the hero, turn Feedback off, and predict the failure before you press Run.