Code as Policies

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.

Words in, program out, arm moves

Ready

      

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

A robot that takes orders

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.

A skill menu, or a programmer?

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.

The idea in one line: a robot policy can be a program, and a language model can write that program from a sentence. The model brings common sense and coding skill. The primitives bring perception and safe motion.
  1. What a policy is: observation in, action out, and a controller you can tune.
  2. Two ways to build one: learned end-to-end policies against programs, with the paper's numbers.
  3. Prompting a program: hints, examples, and how the code is run safely.
  4. Perception in, actions out: step a program line by line on the robot.
  5. Functions that write functions: hierarchical code generation.
  6. Thinking in numbers: why code beats words for geometry.
  7. Closing the loop: checks after each step, and retries.
  8. How high should the API sit? Success against abstraction level.
  9. How it breaks: invented APIs, brittle perception, no dexterity.
  10. The agentic turn: execution feedback and skill libraries in 2026.
  11. Connections: the cheat sheet and where to go next.
In Code as Policies, what produces the robot's behaviour for a brand-new instruction?

Chapter 1

What a policy is

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.

ot
The observation at time step t: what the sensors report now.
π
The policy: any rule, network or program that turns an observation into an action.
at
The action at time step t: the command sent to the motors.

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:

x
Where the gripper is now (the observation).
x*
Where the block is: the target, as perception reports it.
K
The gain: how much of the gap to close in one step.
a
The step the gripper takes. The next position is x + a.

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 smallest policy

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.

0.40
0 cm

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.

The gripper is at 0 cm, the block at 50 cm, and K = 0.4. Where is the gripper after two steps?

Chapter 2

Two ways to build one

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.

πθ(oi)
The network's action for observation i, with weights θ.
ai
The expert's action in demonstration i.
(1/N) Σi
Average over all N recorded demonstration steps.
L(θ)
The loss. Training changes θ to make it small.

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 head-to-head test

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.

Learned policy against code, in the paper's numbers

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.

In Table III, what happens to CLIPort on spatial-geometric tasks when the attributes are unseen?

Chapter 3

Prompting a program

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:

  1. Hints: import statements that name the available APIs, such as from utils import get_pos, put_first_on_second.
  2. Examples: pairs of an instruction, written as a Python comment, and the code that carries it out. These are few-shot demonstrations of the style.

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.

Build the prompt

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:

TH
Tokens for the hints (imports).
k
How many examples you include.
TE
Average tokens per example (instruction plus code).
TI
Tokens for the new instruction, plus room for the answer.
Tmax
The model's context limit.

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.

Running the code

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
What are the two parts of a Code as Policies prompt, before the new instruction?

Chapter 4

Perception in, actions out

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:

perceive(o)
A perception API call. In: the camera image. Out: names, positions, boxes.
f
Plain Python the model wrote: arithmetic, loops, comparisons, NumPy.
primitive
A control API. In: a few numbers or names. Out: motion on the robot.
action
What the robot does as a result.

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.

Step the program

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.

The buggy line program uses np.linspace(left, right, 2) for three blocks. What happens?

Chapter 5

Functions that write functions

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:

p
The chance a single line is written correctly.
L
How many lines the model must write in one go.
P(correct)
The chance the whole program is right.

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.

Grow the call tree

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

Does it help? The paper's benchmark

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.

MethodGPT-3 6.7BGPT-3 175BCodex cushmanCodex davinci
Flat3685481
Hierarchical5845795

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.

How does hierarchical code generation find which functions it still has to write?

Chapter 6

Thinking in numbers

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:

a, b
The two end points of the line, as (x, y) positions.
b − a
The vector from the first end to the last.
i / (n − 1)
How far along the line point i sits, from 0 to 1, for n points.
pi
Where block i goes. In code: 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.

Words or numbers?

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.

5

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.

TaskPlain languageChain of thoughtCode (LMP)
Object selection396896
Position selection3048100
Total355898

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.

Using pi = a + i/(n−1)·(b−a) with a = (10, 50), b = (50, 10) and n = 5, where is p1?

Chapter 7

Closing the loop

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:

p
The chance one attempt works.
r
How many retries the check allows after the first attempt.
P(success)
The chance that at least one attempt works.

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.

Feedback on, feedback off

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.

One attempt works with probability 0.7. With two retries, what is the chance of success?

Chapter 8

How high should the API sit?

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.

q
Chance one line at this level is written right. Lower levels have more parameters per line, so q drops.
L
Lines needed for the task at this level.
X
Chance the physical execution works: grasps hold, detections are right.
S(level)
Chance the whole task succeeds.

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.

Drop the abstraction

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.

What did CaP-X find as human-designed abstractions were removed from the API?

Chapter 9

How it breaks

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:

P(code)
The program is right for the instruction.
P(perception)
Every detection the program uses is right.
P(control)
Every primitive does its job physically.
P(task)
The whole task succeeds.

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.

Where does it break?

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.

The four kinds

  1. Invented APIs. The model calls a function that does not exist, or calls a real one with missing arguments. The paper's fix was better hints and examples; it found model-based code editing "inconsistent" CaP · App. A.
  2. Brittle perception. "Many real-world failures could be attributed to inaccurate detections". MDETR found blocks more reliably when asked for a "square" than a "block" CaP · App. G. The tabletop prompt also could not handle duplicate objects, because the detector could not keep their identities apart CaP · App. I.
  3. No low-level dexterity. CaP is limited by "which control primitives are available" CaP · §V. A program can call a grasp; it cannot invent the finger forces for folding a shirt.
  4. Beyond the examples. CaP struggles with commands much longer, more complex, or at "a different abstraction level than the given Examples". "Build a house with the blocks" fails because no example shows 3D structures CaP · §V.
Why can no amount of better code fix a task that needs fine finger forces, such as folding cloth?

Chapter 10

The agentic turn

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.

Voyager: a skill library in Minecraft

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.

Grow a skill library

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: CaP-Agent0

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.

Build CaP-Agent0, one part at a time

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: skills discovered by search

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.

In CaP-X's ablation with Gemini-3-Pro, what took average success from 24% to 55%?

Chapter 11

Connections

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.

Which policy fits the job?

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.

The cheat sheet

IdeaIn one line
Policyat = π(ot): any map from observation to action, network or program.
Code as PoliciesA code-writing LLM turns an instruction into Python that calls perception and control APIs.
PromptHints (imports) plus examples (comment, then code); greedy decoding at temperature 0.
ExecutionCheck for imports, dunders, exec and eval; then exec with APIs as globals and empty locals.
Hierarchical generationCall undefined functions; find them in the syntax tree; write each depth first. RoboCodeGen 81 → 95% (davinci).
Code for geometryLet NumPy do the maths: 98% against 58% for chain of thought on spatial questions.
GeneralizationUnseen attributes: CLIPort 0.00%, CaP 73.33% on spatial-geometric tasks.
FeedbackLook again after each step and retry: 1 − (1 − p)r+1.
AbstractionHigher APIs raise success and lower expressivity; CaP-X S4 → S1: 17.5 → 55.6%.
Agentic turnMulti-turn feedback plus verified skill libraries: Voyager, CaP-Agent0 (24 → 68.29%), ASPIRE.

Honest limits

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.

Where it sits in the field

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.

  1. A New Era for Agentic Vision and Robotics: the hub lesson of this path, on agents as teachers for fast models.
  2. CaP-X: the full benchmark, the tiers, CaP-Agent0 and CaP-RL.
  3. ASPIRE: agentic skill discovery with evolutionary search (lesson being built).
  4. Code as Agent Harness: code as the medium that structures an agent's work.
  5. GPT-Policy and Claude Plays Robotics: frontier models driving robots.
  6. microVLA and imitation learning: the learned family, from behaviour cloning up.
  7. Agents and tool use, agent skills and harness engineering: the loop around the model.
  8. SayCan: the skill-selection planner that Code as Policies contrasts with.
The takeaway. A robot policy can be a program. A language model can write it from a sentence, if people give it good perception and good primitives. How high those primitives sit decides how often it works. Feedback and verified skills let today's agents climb back up from low-level calls on their own.
Which job suits a pure code policy worst?

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.

Based on "Code as Policies: Language Model Programs for Embodied Control" by Jacky Liang, Wenlong Huang, Fei Xia, Peng Xu, Karol Hausman, Brian Ichter, Pete Florence and Andy Zeng (ICRA 2023), arXiv:2209.07753. Later work: CaP-X by Letian Fu et al. (ICML 2026, arXiv:2603.22435), ASPIRE by Runyu Lu et al. (2026, arXiv:2607.00272), and Voyager by Guanzhi Wang et al. (2023, arXiv:2305.16291).
Back to Gleams