People leave a gap of about 200 ms before they answer. Learn how a robot earns that: eyes that follow, gestures that fit the words, and layers of motion that never freeze.
Turn the three layers on one at a time, then change how long the robot waits to reply. Watch what makes it a statue and what makes it feel alive. Then we build, piece by piece, the motion curves, the gaze, the turn-taking cues, the gestures, the joint mapping, the behavior tree and the timing underneath.
You need a little trigonometry (sine and cosine of an angle) and a little Python for the code. We build the rest from zero.
Built from primary sources, each linked in the Field Guide: Thomas and Johnston on animation, Stivers and colleagues on turn-taking, Andrist and colleagues on robot gaze, Kucherenko and colleagues and Yoon and colleagues on gesture generation, Gleicher on retargeting, and Colledanchise and Ögren on behavior trees. Every idea is re-taught here in our own words and devices.
Toy scene. The 200 ms gap is the typical gap between turns that Stivers and colleagues measured in ten languages (2009). The blink timing, the arm swing and the glance away are made up to show the idea, not measured from a robot.
Chapter 0
See why timing and motion carry as much meaning as the words, and meet the nine parts that make a robot feel alive
Picture a small robot on a desk. You ask it, “What is the weather like today?” Nothing happens. A second and a half later, a voice says, “It is sunny, with a high of 21 degrees.” The answer is right. But the body never moved, the eyes never turned, and the voice came out of a statue.
You do not think, “good answer.” You think, “is it broken?” You talked to a speaker with a face painted on it. The words were perfect and the conversation still failed.
This lesson explains why, and how to fix it. A robot like this hears speech in a noisy room, thinks, speaks, and moves. Each of those is a solved problem on its own. This lesson is about the layer on top: the part of behavior that is not the words, but tells the person that someone is there.
The robot above failed in three separate ways. Name them, because each has its own cure.
It was late. Its reply came far after the gap that people leave. It was still. Between words, nothing moved, not even a blink. And it was stiff. When it did speak, the body did not move with the speech.
People are very good at noticing all three, and they notice within a fraction of a second. You do not need a lab to feel it. A video call with a one second lag feels wrong before you can say why.
Researchers measured this. Stivers and colleagues (2009) recorded conversations in ten languages, from large world languages to small traditional communities. In every one, speakers avoided talking over each other. And in every one, they kept the silence between turns very short. In all ten languages the most common gap fell between 0 and 200 milliseconds. A millisecond (ms) is one thousandth of a second.
That is remarkable. Planning a sentence takes longer than 200 ms. So listeners cannot wait for you to finish, then start thinking. They plan their reply while you are still speaking, and they guess when you will stop. Chapter 3 shows how a robot can do the same.
For a builder, the lesson is plain. A pause of 1,500 ms is not “a bit slow”. To a human it is a signal: the other party did not hear me, or does not understand, or is not there. Try your own feel for it below.
Set the slider to how long you think people usually wait between one person finishing and the next one starting. Then press Reveal and compare.
The band from 0 to 200 ms is the range where the most common gap fell in all ten languages (Stivers et al., 2009, PNAS). The 1,500 ms robot is illustrative: a slow pipeline that waits, then transcribes, thinks and speaks one stage after another.
The real number is small enough that a robot cannot get it by accident. It must be designed. And the design has more parts than timing.
In a quiet lab, a robot hears one clean voice. A real room is not quiet. A fan hums, a second talker laughs, and the robot’s own motors whirr a few centimeters from its microphones. Every decision in this lesson has to survive that.
Three things go wrong first. The robot may think you are still talking when you are done, because a noise keeps the voice detector firing. It may think you are done when you are only thinking. And it may hear its own voice and stop in the middle of a word. Chapter 3 names each failure and gives a measurement and a fix.
Every chapter after this one ends the same way. First the symptom: what a person watching the robot sees. Then the measurement: the number you log to prove it. Then the fix. This habit matters more than any single trick. A robot that feels wrong is a robot you have not yet measured.
One more point before we start. The words of the reply are not the topic here. They come from a language model or a script, and other lessons cover them. Our topic is what the body and the clock do around those words. Hold on to that split, because it lets you improve the behavior without touching the model.
Animators have studied this for a century. They learned that a character feels alive because of how it moves, not because of how it looks. In 1981 two Disney animators, Frank Thomas and Ollie Johnston, wrote down the twelve principles that their studio had found. Hoffman and Ju (2014) argued that the same idea belongs in robot design: choose the movement first, then build the body around it.
A robot that speaks, listens and moves needs all of these parts. This lesson takes them one at a time, one chapter each.
The hero at the top of this page already shows the stakes. It has three layers: idle life, gaze and gesture. Chapters 1 to 4 build those layers. Chapters 5 to 8 make them work together on a real body.
Chapter 1
Shape one head turn with an easing curve and learn which animation principles survive on a robot with only a few joints
A cartoon character has no body. It is a stack of drawings, flipped fast. Yet you believe it is alive, and you believe it has a mood. The animators found that the belief comes from how the drawings change, not from how they look.
A robot has the opposite problem. It has a real body and real motors, and it can still look like a machine. Here is a scene. You say your name. The robot’s head turns toward you in a straight, even sweep, stops dead, and a servo clunks. Nothing is wrong. But it looks like a printer carriage, not a creature.
First, a plain fact. A robot joint does not jump to an angle. Every motion is a trajectory: a list of angles, one per tick of a control loop. One common choice is a loop that sends a new target to the motor every 10 ms, which is 100 targets per second. A 400 ms head turn is then 40 targets.
You choose the numbers. The simplest choice is a straight line from the start angle to the end angle. That is linear interpolation. It looks wrong for a reason you can compute. At the first tick the head goes from standing still to full speed, and at the last tick it goes from full speed to still. A change of speed with no ramp means infinite acceleration. A real motor cannot do that, so it lags, overshoots, and clunks.
Animators call the fix slow in and slow out (Thomas and Johnston, 1981). A living thing speeds up gently and slows down gently. Roll a ball and watch it. Raise your arm and feel it. Neither starts or stops in an instant.
The simplest curve with that shape is a smooth S. Let t run from 0 (start) to 1 (end). The smoothstep curve gives the fraction of the move that is done at time t.
Take the slope to get the speed. The slope of s is 6t − 6t2. At t = 0 it is 0. At t = 1 it is 0. At t = 0.5 it is 6 × 0.5 − 6 × 0.25 = 1.5. So the move starts gently, peaks in the middle at 1.5 times the average speed, and ends gently.
40° in 400 ms: average = 100°/s, peak with smoothstep = 1.5 × 100 = 150°/s
Try it. The plot shows the angle on top and the speed below. The robot on the right plays the same curve.
Top plot: head angle over the move. Bottom plot: head speed. Choose a curve, then drag the duration and watch the speed peak change.
A 40 degree turn at the duration you pick. Speeds are computed from the curves by sampling them 200 times. The anticipate curve is the standard ease-in-out-back curve with its usual constant of 1.70158, a stand-in for a hand-animated curve, not a measured human motion.
Linear shows a speed plot shaped like a box: the speed jumps up at the start and drops at the end. Ease in and out draws a hill. The hill is the whole story. Make the move slower and the hill gets lower. Make it faster and the peak rises, so a fast eased move can need a faster motor than a slow linear one.
Two more principles matter for a robot. Anticipation is a small move in the opposite direction before the main move. A person crouches before a jump and leans back before a throw. For a head turn, the head dips a few degrees away first. The viewer reads this as “it is about to turn”. Without it, the move arrives with no warning, and that is why a fast robot motion can feel like a jump scare.
Follow-through is the opposite end. The body part overshoots its goal a little, then settles back. A hand does not stop where the arm stops. Pick the third curve above. The angle first dips below zero, then passes 40 degrees, then settles. The device reports both numbers.
The third curve in the device is worth a measurement. For a 40 degree turn it first swings back 4.0 degrees, then overshoots the goal by 4.0 degrees. That is a tenth of the move on each side, which is large enough to see and small enough to look like intent. Its peak speed is about 5.6 times the average, so in 400 ms the head moves at up to 560 degrees per second. Anticipation is not free. It spends motor speed to buy readability.
This is the central trade of robot animation. A cartoon can draw any pose in any frame. A robot pays for every curve with torque and speed, and with the noise the motor makes. So you choose the principles that give the most readable motion for the least speed. Easing the ends costs a little. Anticipation costs more. Large follow-through costs the most, because the overshoot must also be braked.
Three more principles are cheap to use. Arcs say that living limbs move along curves, not straight lines. When two joints move together, delay one by 30 to 60 ms and the hand swings on an arc without any extra planning. Secondary action is a small motion that supports the main one: a blink, a breath, a tilt. It is the idle life layer from the hero. And Thomas and Johnston warned against twins, where both sides of a body do the same thing at the same time. A robot with two identical arms should not swing them in perfect mirror.
Not every principle fits a robot. Squash and stretch needs a body that bends; a rigid shell cannot do it, so animators of robots use a quick tilt or a short scale of a screen face instead. Treat the twelve principles as a menu. Take what your joints can express.
Two principles concern the viewer, not the motor. Staging means that one idea is clear at a time. If the head turns while the arm waves and the torso leans, the eye does not know where to look. Sequence the parts: the head leads, the arm follows 100 ms later.
Exaggeration means to push a pose a little further than real life. A robot with a small head and a small range is easy to miss. A nod of 5 degrees looks like nothing from three meters away. A nod of 12 degrees reads as a nod. Test every motion from the distance at which people will actually stand.
The symptom: the head turn looks jerky and the servo makes a knock at the end. Measure it: log the commanded angle at 100 Hz and take the difference twice. A linear move shows one huge spike of acceleration at each end. The fix: replace the line with an eased curve, then raise the duration until the peak speed is below what the motor can deliver. Always check the peak speed before you ship a curve.
pythondef smoothstep(t): # t in [0, 1] -> fraction done return t * t * (3 - 2 * t) def head_turn(a0, a1, ms, hz=100): # returns one joint target per control tick n = round(ms * hz / 1000) # 400 ms at 100 Hz -> 40 ticks return [a0 + (a1 - a0) * smoothstep(i / n) for i in range(n + 1)] targets = head_turn(0, 40, 400) # 41 floats; peak speed = 150 deg/s
Chapter 2
Point the robot’s eyes at the right person at the right moment, and learn when looking away is the right thing to do
Three people stand around a robot. Anna asks a question. The robot’s head stays pointed at Ben, who spoke first, ten seconds ago. Anna feels ignored. Ben feels stared at. Nobody can tell who the robot is answering.
The robot heard every word. It just looked at the wrong place. In human conversation, where your eyes point is part of the message. This chapter teaches a robot to use that signal.
Gaze is the direction a creature is looking. It carries three messages. It says who is being addressed: you look at the person you talk to. It says what is being attended to: you glance at the object you mention. And it says who holds the turn, a point Chapter 3 returns to.
Two terms help. Mutual gaze, or eye contact, is when two parties look at each other. Gaze aversion is looking away on purpose. People do both all the time, and both are signals. Staring without a break feels intense. Never looking feels cold.
A gaze controller is a small pipeline. Sensors say where the people are. A rule picks one target. A smoother turns the target into head and eye motion. Here are the steps with their real inputs and outputs.
A worked example for step 1. The camera image is 640 pixels wide and the field of view is 60 degrees. Then f = 320 / tan(30°) = 320 / 0.577 = 554 pixels. A face centered at column 480 is 160 pixels right of the middle. The angle is atan(160 / 554) = atan(0.289) = 16.1 degrees to the right. The head pans 16.1 degrees to look at that face.
A robot like NAO has no articulated eyes, so it points its head. Andrist and colleagues (2014) used exactly such a robot. Their eyes are fixed on the head, so the head is the gaze. Robots with moving eyes can add a quick eye move first and let the head follow, the way people do.
The simplest rule is: look at whoever is speaking. It works if the robot is quick. Every switch of speaker costs a delay: the time to hear a new voice, decide, and move the head. During that delay the robot looks at the old speaker.
The device below plays a conversation with three people and the robot. Turns arrive in a fixed order. Choose a gaze rule, then drag the delay.
Top view of the room: three people and the robot at the bottom. The teal line is where the robot looks. The bar below shows who talks and, underneath, whether the robot was looking at the right person.
Toy conversation of 15.8 s: Anna, then the robot answers Anna, Ben, the robot answers Ben, Cai, the robot answers Cai. The look away lasts 800 ms and points 40 degrees off the person. These numbers are made up. The percentages count your delay and ignore the time the head needs to travel.
Follow beats stare by a wide margin, and the delay slider shows the price of a slow reaction. Each of the two speaker switches costs exactly one delay of wrong gaze. At 1,500 ms that is a big part of a three second turn.
People look at what they talk about. Say “the red cup” and your eyes go to the cup, and the listener’s eyes follow. This is joint attention: two parties attending to the same object. A robot can use it in both directions. It can look at the object it names, and it can follow your gaze or your pointing hand to learn what you mean.
The data flow is the same as for faces, with an object detector in place of a face detector. The detector gives a box and a label. The same pixel-to-angle formula turns the box into a head angle. The new part is the timing: the glance should land on the object just before or as the word is spoken, so the listener looks too.
Gaze reaction has a hard floor, set by the head itself. Suppose the head motor can turn at 200 degrees per second at most. Anna and Cai in the device are 100 degrees apart. A smoothstep move peaks at 1.5 times the average speed, so the shortest possible move takes 1.5 × 100 / 200 = 0.75 seconds. No tuning of the delay slider can beat that.
Real heads are slower than eyes, which is why people move their eyes first. A robot with only a head should therefore decide early, and it should start turning before the other person has finished the first word. A short head turn can start on the sound alone, and a later correction can fix a wrong guess.
The third rule looks odd: it makes the robot look away at the start of its own turn. Andrist, Tan, Gleicher and Mutlu (2014) studied this with a NAO robot and 30 participants. They timed the robot’s gaze aversions the way people do them, and they blended the aversions with small idle head moves so the gaze stayed smooth. Participants rated the aversions as intentional. The robot appeared more thoughtful. And the aversions helped it manage the conversational floor.
The study also found a limit. When the aversions had bad timing, or came too often, they backfired. Looking away at the wrong moment reads as embarrassment or as dislike. So the rule is not “look away more”. It is “look away briefly, at the start of an answer, then come back”.
In a noisy room the speaker angle jumps. A door slams and the array reports a voice from the wall. The head snaps to the wall, then back. The symptom is a robot that twitches between people. The measurement: count gaze target changes per minute. A calm conversation has a few. A flickering robot has dozens.
The fix has two parts. First, add hysteresis: keep the current target until a new candidate has been the best for a set time, for example 300 ms. Second, add a minimum dwell: once the head turns, hold for at least a moment. Both trade a little delay for a lot of calm.
pythondef pick_target(state, speaker_id, now_ms, hold_ms=300, dwell_ms=600): if speaker_id == state.target: # nothing to change state.cand = None; return state.target if speaker_id != state.cand: # a new candidate: start its clock state.cand, state.cand_since = speaker_id, now_ms stable = now_ms - state.cand_since >= hold_ms # hysteresis: it must stay best for 300 ms rested = now_ms - state.moved_at >= dwell_ms # dwell: no new move for 600 ms if stable and rested: state.target, state.moved_at = speaker_id, now_ms return state.target
Chapter 3
Decide when a person has finished speaking, in a room full of noise, without interrupting them and without making them wait
You are in a busy café and you tell a robot barista, “I would like a…” and stop to think. Half a second passes. The robot says, “Sorry, I did not catch that.” It cut in on your pause. You start again, and it cuts in again.
So the team makes the robot more patient. Now it waits a full second of silence before it speaks. You finish, “a large coffee”, and a second of nothing follows. You wonder if it heard you. Too eager is rude. Too patient is dead. This chapter is about the narrow path between them.
Conversation analysts name the parts. A turn is one stretch of speech by one speaker. A transition is the hand-over from one speaker to the next. A gap is the silence in a transition. An overlap is when both talk at once. Sacks, Schegloff and Jefferson (1974) described a simple system: a speaker may go on until they reach a point where a hand-over is possible, and then the next speaker may begin.
Chapter 0 gave the target: the common gap is between 0 and 200 ms (Stivers et al., 2009). Levinson and Torreira (2015) point out what follows from it. Producing a word takes over 600 ms, far longer than the gap, so listeners cannot wait for the end. They begin planning while you speak, so they must predict your end.
A robot listens through a chain of stages. Here is the real data flow.
The simplest endpointer counts silent frames. When the count reaches a silence threshold, say 500 ms or 25 frames, it fires. The threshold is the only knob, and it is a bad trade. The robot cannot answer sooner than the threshold, so the threshold is added straight onto the response gap. But people pause inside sentences, to think, to breathe, to find a word. A threshold shorter than those pauses makes the robot cut in.
People do not use a silence timer. They use cues, and these cues show up before the silence. Skantze (2021) reviews this field for conversational systems and robots. The main cues are three.
Syntax: a finished sentence ends, and “I would like a” does not. Prosody, the melody of speech: pitch usually falls at the end of a statement and stays level or rises when the speaker will go on. And gaze: speakers often look away while they hold the turn and look back at the listener as they finish, which ties to Chapter 2.
The device shows one utterance, “I would like a… large coffee”, with a 450 ms pause in the middle. Slide the threshold, then switch on the cue.
The blue wave is you speaking, with a pause in the middle. The pink line is the pitch. The orange bar is when the robot starts to talk. Drag the threshold, then try the cue.
Toy utterance. Speech runs 0 to 1,600 ms, a 450 ms pause follows, speech runs on to 3,500 ms. With the cue on, a finished sentence with falling pitch triggers the reply after 150 ms; an unfinished one waits at least 1,000 ms. These two rules and the numbers are illustrative.
Without the cue you cannot win. A threshold at or below 450 ms cuts in at the pause. A threshold above 450 ms is safe, but then every reply is late by that much. With the cue, the robot answers 150 ms after the end and ignores the mid-sentence pause. It uses the one signal that the silence timer lacks: whether the sentence is finished.
A hand-written cue is a start. The review by Skantze describes models that learn from conversation data to predict, at every moment, whether the speaker will stop soon. The robot can then prepare its reply early and speak the instant the probability crosses a line. Our own voice turn-taking lesson builds such a predictor, and streaming speech shows the real-time audio plumbing behind it.
One more cue matters for a listener: the backchannel. A short “mm-hm” or a nod tells the speaker “go on, I am listening” without taking the turn. A robot that nods at the right moments keeps the speaker talking. A robot that says nothing makes them wonder.
Turn-taking runs both ways. While the robot talks, it must watch for the person starting to speak. If the person says a short “yeah”, that is a backchannel and the robot should keep going. If the person says a whole phrase, that is a barge-in and the robot should stop within a fraction of a second.
How does it tell them apart? A simple rule uses duration and energy. A burst under about 300 ms is probably a backchannel. A burst that continues, or one that is loud and close, is probably a barge-in. The numbers are design choices, not laws, and you tune them on recordings from your own room. The rule needs the echo cancellation from below, or the robot will decide that its own voice is a barge-in.
When the robot yields, the body should show it. The arm drops, the gaze returns to the person, and the speech fades over about 100 to 200 ms, not a hard cut. A hard cut sounds like a glitch. A fade sounds like a person stopping to listen.
Noise breaks endpointing in two ways. A TV, a second talker or a clatter keeps the VAD firing, so the silence counter never reaches the threshold, and the robot never answers. The symptom is a robot that waits forever in a loud room. Or the robot hears its own voice from its speaker and thinks the user is talking. The symptom is a robot that stops mid-sentence for no reason.
Measure both: log the time from the true end of speech to the reply start, and count replies cut off by false triggers. The fix is layered: raise the VAD threshold in noise, use the microphone array to keep only sound from the target direction, and cancel the robot’s own voice from the input before the VAD sees it. The motors are noisy too, so keep fast head moves out of the moment the user starts to speak.
pythondef user_done(vad_probs, cue_finished, thr_ms=500, frame_ms=20): silent = 0 for p in vad_probs: # one probability per 20 ms frame silent = silent + frame_ms if p < 0.5 else 0 need = 150 if cue_finished() else max(thr_ms, 1000) if silent >= need: # cue says done: 150 ms; unsure: wait longer return True return False
Chapter 4
Turn speech audio and text into joint angles, and see why a model needs both to move the way a speaker does
The robot says, “The fish was this big.” Its hands hang at its sides. You do not see the fish. Now picture the opposite: the robot swings the same arm in the same loop on every sentence, like a wind-up toy. You stop seeing the arm at all.
People gesture while they talk, and they do it without thinking. A robot that speaks needs the same habit, and it needs the right gesture at the right word. This chapter shows how a model can learn that from recordings of people.
A co-speech gesture is a hand or body movement that goes with speech. Researchers sort them into four kinds, and the learned-gesture papers use the same four.
A beat is a small flick that lands on a stressed word. It carries rhythm, not meaning. An iconic gesture draws the thing: hands apart for “big”. A metaphoric gesture draws an idea as if it were a thing: a cupped hand holding “a thought”. A deictic gesture points: at the door, at a person, at “you”.
The first kind follows the sound. The other three follow the meaning. Keep that split in mind, because it explains the design of the models.
The old way is a rulebook. An expert writes: when the text says “big”, play the clip “hands apart”. It works for the words on the list. It needs a person to write and tune every rule, and it fails on any phrase nobody foresaw. Yoon and colleagues (2018) call this out as expert labor and propose to learn it instead.
Their system trains on about 52 hours of TED talks. An encoder reads the speech text. A decoder produces a sequence of gestures. The learned gestures include iconic, metaphoric, deictic and beat types, and the team ran the result on a NAO humanoid robot. Participants rated the movements as human-like and as matching the speech content.
That model uses text only. Kucherenko and colleagues (2020) built Gesticulator, which takes both an acoustic and a semantic representation of speech and outputs gestures as joint angle rotations. They note that earlier end-to-end systems used just one of the two, so they produced either beats tied to the sound or meaningful gestures tied to the words, but not both. The paper won the best paper award at ICMI 2020. The output can drive a virtual character or a humanoid robot.
Here is the shape of such a model. The sizes are illustrative; each real model chooses its own.
Why output joint angles and not hand positions? Angles are the language of a skeleton, and a skeleton can be retargeted to a different body. Chapter 5 does exactly that. Training pairs the speech from a video with the pose of the speaker, found by a pose estimator. The loss is the difference between the predicted angles and the speaker’s angles.
Try it in the device. The phrase is “the fish was this big”. Three words are stressed. Pick which signals the model may use.
The playhead sweeps the phrase. Blue bars are the loudness of each word. The purple curve is how high the arm rises. The robot on the right follows that curve.
Toy model for one phrase of 3 s. Stressed words are at 0.7 s, 1.7 s and 2.4 s. Audio makes a short flick at each stress; text makes one wide, open-hands lift at “big”. A real model learns these from data; the curves here are drawn by hand to show the split.
Audio alone gives a flick on every stressed word, but no hand ever opens for “big”. Text alone gives the wide gesture at “big” and has no rhythm in the rest. Both together look like a speaker. That is the argument of the Gesticulator paper in one picture.
A model trained to match one recorded gesture has a quiet flaw. For the same sentence, a speaker could raise the right hand or open both hands. Both are good. If half the recordings do one and half the other, the loss is lowest when the model outputs the average of the two. The average might be a hand held halfway, which no person does. The model learns a safe, small, dull motion.
Worked example: the right arm goes to 60 degrees in half the examples and stays at 0 degrees in the other half. The squared error is smallest at 30 degrees. At 30 degrees the error is 30 in every example. At 60 degrees it is 0 in half and 60 in the other half. In squared terms 30 gives 900 and 60 gives (0 + 3,600) / 2 = 1,800. So training pushes the model to 30 degrees, which is a gesture nobody made. The symptom is a robot that shrugs weakly. The cure is to let the model draw from the spread of gestures instead of the mean, which is why newer systems use generative models.
A gesture model gives you a pose for every frame, but the voice comes from a speech synthesizer, and the synthesizer decides when each word is spoken. The two must share a clock. Most synthesizers can report a start time for each word. Feed those times to the gesture model as the alignment between text and audio frames. Then the flick lands on the right syllable.
The frame rates differ too. If the model outputs 20 poses per second and the control loop runs at 100 per second, you must interpolate between poses. Use the easing from Chapter 1 between neighbors, never a straight line, or the hand will move in steps that the viewer reads as shaking.
How do you know the gestures are good? The learned-gesture papers ask people. Yoon and colleagues had participants rate the robot’s gestures for human-likeness and for how well they matched the speech. Kucherenko and colleagues report subjective and objective evaluations. For your own system, run the same kind of test: show the same sentence with the learned gestures, with random gestures, and with none, and ask which looks most natural.
The most visible failure is timing. The hand lands after the word it should mark. The symptom looks like a bad dub. Measure it: compare the time of each arm peak with the onset of the stressed word. The fix: the speech audio is generated first, so generate the gestures from that exact audio, then delay the audio output slightly to match the motion latency of the arm.
Chapter 5
Move a human gesture onto an arm with shorter bones and tighter joint limits, and keep the hand where the gesture needs it
The gesture model from Chapter 4 outputs a human skeleton: shoulder and elbow angles for a person with a 30 cm upper arm. Your robot has an 18 cm upper arm and an elbow that bends only 90 degrees. You copy the angles straight across. The robot’s hand sweeps a small, wrong curve, and at the top of each swing the elbow grinds against its stop.
The motion was fine. It was made for another body. Moving a motion from one body to another is called retargeting, and this chapter shows how to do it.
Start with the arm itself. A joint angle says how far one bone is turned from the next. An arm with a shoulder joint and an elbow joint has two angles, and a hand position that depends on both. Computing the hand from the angles is forward kinematics (FK). Computing the angles that put the hand at a chosen point is inverse kinematics (IK). Each joint that can move on its own is a degree of freedom (DOF); this arm has two.
Let the upper bone have length L1 and the forearm L2. Measure the shoulder angle a1 from straight down, and the elbow angle a2 as the extra turn of the forearm. Then the hand sits at a distance d from the shoulder, and the law of cosines gives the elbow angle.
A worked example for the robot, with L1 = 18 cm and L2 = 16 cm. Say the hand must be 24.9 cm from the shoulder. Then d2 = 620, and cos a2 = (620 − 324 − 256) / 576 = 40 / 576 = 0.069. So a2 = arccos(0.069) = 86 degrees. The elbow must bend 86 degrees. That is inside a 90 degree limit, but only just. A slightly farther hand would not need as much bend, and a nearer hand would need more.
Gleicher (1998) named the problem and gave the classic answer. First rescale the motion to the new body. Then find the places where the motion must keep a feature, such as a foot planted on the floor or a hand touching something. Last, re-establish those features by numerical optimization, changing the motion as little as possible and keeping its frequency content, so that the character’s timing and style survive. The work was for animated characters, but the problem is the same for a robot, with one more constraint: the joints have real limits.
Here are three methods for the arm. The device runs the same human gesture through each.
Left: the human arm that makes the gesture. Right: the robot arm. The hollow ring is where the scaled human hand should be. Choose a method, then drag the elbow limit.
Toy arms. Human bones: 30 cm and 28 cm. Robot bones: 18 cm and 16 cm, so the reach ratio is 34 / 58 = 0.59. The gesture swings the human shoulder from 11 to 92 degrees and the elbow from 17 to 120 degrees. The robot shoulder range is 0 to 115 degrees. All lengths and limits are made up; the geometry is exact.
Copy gives the smallest-looking error at first glance, because both arms make the same pose. But its hand trail is wrong in size and shape, and it grinds at the limit. Match the hand follows the ring perfectly and then breaks the limit at the top of the swing: the red marks show where. Only the third method both follows and obeys. As you lower the limit, its error grows, and that is honest: the robot really cannot go there.
A hand position inside the reach has two IK answers: the elbow bent one way, or the elbow bent the other way, like two mirror images. The code picks the positive elbow angle. A robot arm usually allows only one of the two, so the choice is also a limit. If you pick the wrong branch, the arm tries to fold through itself.
Stay on one branch for a whole gesture. If the solver flips between the two as the target moves, the arm will whip across in a single tick. A simple guard is to start each solve from the previous angles and pick the answer nearest to them.
A real robot arm has more than two joints. A seven joint arm has extra freedom: the hand can stay still while the elbow swings. That freedom is useful. You can use it to keep the elbow away from the body, or to stay far from a joint limit. The solver then has many answers and must pick one, usually the one that moves the joints least.
The same idea applies to a whole upper body. The gesture model outputs rotations for every human joint, and the robot has fewer. A retargeting map says which human joints drive which robot joints, and which are dropped. A shoulder shrug, for example, may have nowhere to go on a robot without that joint, and that is fine. Drop the joint, and keep the hand path.
The symptom: at the top of a gesture the elbow motor buzzes, gets warm, and the motion flat-tops. The cause is a command beyond the hard stop; the motor pushes against it. Measure it by logging the commanded angle against the limit and the motor current. The fix is to clamp in the retargeting step, and to add a soft limit: slow the joint down before the stop so it never arrives at full speed.
A second trap is a fully straight arm. At full reach a2 is near 0 and small errors in the hand position cause large swings of the angles, so the IK answer jitters. Keep the target slightly inside the reach, for example at 98% of L1 + L2. Our inverse kinematics lesson builds the general case, and imitation learning shows how robots learn from human motion with the same body gap.
pythonimport math def retarget_arm(hand_h, L_h=(30, 28), L_r=(18, 16), a2_max=math.radians(90)): s = sum(L_r) / sum(L_h) # reach ratio 34 / 58 x, y = hand_h[0] * s, hand_h[1] * s # scaled hand target, cm d = min(math.hypot(x, y), 0.98 * sum(L_r)) # stay off the straight-arm singularity c2 = (d*d - L_r[0]**2 - L_r[1]**2) / (2 * L_r[0] * L_r[1]) a2 = math.acos(max(-1, min(1, c2))) # elbow bend phi = math.atan2(L_r[1] * math.sin(a2), L_r[0] + L_r[1] * math.cos(a2)) a1 = math.atan2(-x, y) - phi # shoulder angle from straight down return max(0, min(2.0, a1)), max(0, min(a2_max, a2)) # clamp to the joint limits
Chapter 6
Organize looking, nodding, speaking and idling into a tree that is checked every tick, so an interruption wins at once
The robot is halfway through a sentence, its arm in the air. The person says, “wait”. What should happen? The robot should stop talking, lower its arm, turn to look, and listen. All of that, in a fraction of a second, without any of the other behaviors fighting for the motors.
You now have many behaviors: idle breathing, gaze, nodding, speaking, gesturing. Chapters 1 to 5 built them one by one. Something must decide which of them runs at each moment. That decision-maker is the subject of this chapter.
The first attempt is a chain of if statements, or a finite state machine, a set of named states with arrows between them. It works for three behaviors. At ten, each new behavior needs arrows to and from every existing state. Add “wave when a new person arrives” and you must edit a dozen arrows, and the interruption rule hides in the middle of them.
A behavior tree (BT) is a different way to organize the same decisions. Colledanchise and Ögren describe BTs as a way to structure switching between tasks that is both modular and reactive. They began in computer games and spread across robotics and AI. Modular means you add a branch without touching the others. Reactive means the tree reacts to a change the moment it happens.
A BT is a tree of nodes. A clock sends a tick to the root, often 10 or more times per second. The tick travels down the tree, and every node that receives it answers with one of three words: Success (I finished), Failure (I could not), or Running (I am still working). The answer travels back up.
The leaves do the work. A condition checks a fact, such as “is the user speaking?”, and answers Success or Failure at once. An action does something, such as “look at the speaker”, and answers Success, Failure or Running. Two inner nodes give the tree its logic.
Put the children of the root in priority order, highest first. Our robot has three branches. Listen: if the user is speaking, look at them and nod. Reply: if a reply is ready, speak and gesture together. Idle: always available, keeps the body alive.
Here is the key point. The root is ticked again from the top on every tick. So if the user starts to speak while the robot talks, the Listen branch is checked first, answers Running, and the root stops there. The Reply branch is never ticked again, which stops the speech. That is a barge-in, and the tree handles it with no special code.
Boxes light up when the tick reaches them. Orange: running. Green: success. Gray with F: failure, which is normal. Dim: never reached. Switch the conditions, or press Play the interruption.
A tree of nine nodes, ticked by the code in this page. Look and Nod, Speak and Idle answer Success or Running as described in the text. The tree and the four-step story are made up to show the idea.
With both switches on, the Listen branch wins and the Reply branch is never reached. That is the priority order at work. With only Reply on, the tick falls through Listen (its first check fails), enters Reply, and the speak and gesture node answers Running. With nothing on, the tick reaches Idle.
The whole engine is small. Every node is a function that gets the shared data, called the blackboard, and returns one of three words.
pythonSUCCESS, FAILURE, RUNNING = 1, 0, 2 def sequence(*kids): def tick(bb): for k in kids: s = k(bb) if s != SUCCESS: return s # stop at the first child that is not done return SUCCESS return tick def fallback(*kids): def tick(bb): for k in kids: s = k(bb) if s != FAILURE: return s # stop at the first child that did not fail return FAILURE return tick root = fallback( sequence(user_speaking, look_at_speaker, nod), # Listen: highest priority sequence(reply_ready, parallel(speak, gesture)), # Reply idle) # Idle: always last # every 100 ms: root(blackboard) -> one status, and the active leaves hold the motors
Real trees add a third kind of node: the decorator. A decorator wraps one child and changes its answer or its schedule. One decorator holds a condition true for 500 ms. Another limits an action so it can run only once every ten seconds. A third turns Failure into Success, so a sequence can go on after an optional step. They let you adjust the logic without adding branches.
The blackboard is the tree’s memory and its only input. Sensors write facts to it: user_speaking, speaker_angle, reply_text. Conditions read facts and actions write requests. Keep it small and give every entry a timestamp, so a condition can ask how old a fact is. A stale fact is a bug that looks like a personality.
A tree is easy to debug because its state is one list: the status of each node on the last tick. Log that list at 10 Hz and you can replay any odd moment. Look for three signs. A branch that flips more than a few times per second needs a decorator. A branch that is never reached has a higher-priority sibling that always succeeds. And a node stuck on Running has no end condition.
Conditions come from noisy sensors. If the VAD flickers between speech and not-speech five times a second, the root flips between Listen and Reply five times a second. The robot starts a word, stops, starts again. The symptom is a stutter. Measure it: count branch changes per second. The fix is the same medicine as Chapter 2: add a decorator that holds a condition true for a short time, such as 500 ms, before letting it go.
Two more details matter on a real robot. When a branch is preempted, its running action must be halted, so the speech output is cut and the arm is handed over. And leaves should never write to the motors directly. They submit requests to a blending layer, which Chapter 7 builds.
Chapter 7
Mix idle sway, gaze and gestures into one stream of joint targets, so switching behaviors never makes the body snap
The behavior tree from Chapter 6 picks Reply. In one tick the robot’s arm must go from hanging at its side to a speaking pose, 52 degrees away. If the new behavior simply writes its target, the arm jumps. The servo slams after it, the shoulder knocks, and the viewer flinches.
There is a second problem, too. The idle layer wants the torso to sway. The gesture layer wants the torso to lean into a point. Both write to the same joint. Without a rule, the last writer wins and the robot twitches between them.
The cure is to separate asking from moving. Behaviors do not touch the motors. Each one is a layer: a source that proposes angles for some joints, along with a weight from 0 (ignored) to 1 (fully in charge). One component, the blender, reads all the layers and writes the single stream of joint targets that goes to the motors.
Two ways of combining layers cover most needs. In an override blend, a layer with weight w replaces part of what is below it. For one joint with lower value qA and upper value qB the result is
In an additive blend, the upper layer does not replace the lower one. It adds its offset on top: q = qA + w × Δq. The breathing stays, and the gesture rides on it.
The weight is where Chapter 1 comes back. To fade a layer in, ramp w from 0 to 1 over a blend time, using an easing curve. Take the idle sway at 8 degrees and a gesture pose at 60 degrees. With a 300 ms smoothstep fade, the joint moves 52 degrees with a peak speed of 1.5 × 52 / 0.3 = 260 degrees per second. With no fade, it moves 52 degrees in one 10 ms tick, which is 5,200 degrees per second. The fade is a speed limit you can choose.
The purple line is the arm angle the blender sends to the motor. The gesture layer is requested at 1.5 s and released at 3.5 s. Pick a blend, then drag the blend time.
Toy joint. The idle layer sways between 4 and 12 degrees every 3.5 s. The gesture pose is 60 degrees (override) or +52 degrees on top of the sway (additive). The fade is a smoothstep. Peak speed is measured on the blended output, sampled every 10 ms. All values are made up.
Set the blend time to 0 and the speed read-out jumps to thousands of degrees per second: that is the knock you could hear. Raise it, and the peak falls. Switch to additive and look at the top of the curve. The override line goes flat, because the sway is gone. The additive line keeps its slow wave. A robot that holds still while it talks looks frozen. A robot that keeps breathing looks alive.
Two more tools finish the job. A joint mask says which joints a layer may touch. Speech may drive the jaw and the right arm. Idle may drive the torso and the head. The gaze layer drives the head and the eyes. Layers that do not share joints cannot fight.
For joints that more than one layer wants, give each layer a priority. The blender applies layers from the lowest priority to the highest, each one blended on top of the result so far. The behavior tree sets the weights; the blender does the arithmetic. When the tree preempts Reply for Listen, the Reply layer’s weight ramps down over its blend time, and the arm goes back to rest by itself.
A note on angles that are rotations in 3D. Linear blending is right for a single hinge joint. For a ball joint, whose 3D turn is stored as four numbers called a quaternion, blend with spherical interpolation (slerp), which slides along the arc between two turns, or the result will not stay a valid rotation. Gleicher (1998) stressed another point that applies here: edits should keep the frequency content of the original motion, so that a blended gesture does not lose its flicks.
pythondef smooth(x): x = min(1, max(0, x)); return x * x * (3 - 2 * x) class Layer: def __init__(self, joints, priority, blend_ms, additive=False): self.joints, self.priority, self.blend_ms, self.additive = joints, priority, blend_ms, additive self.w, self.want = 0.0, 0.0 # current weight, requested weight (0 or 1 from the tree) def step(self, dt_ms): # called every tick (10 ms) k = dt_ms / max(1, self.blend_ms) self.w = min(self.want, self.w + k) if self.w < self.want else max(self.want, self.w - k) def blend(layers, proposals): # proposals[layer] = {joint: degrees} out = {} for L in sorted(layers, key=lambda L: L.priority): # low priority first w = smooth(L.w) for j in L.joints: # the mask: only its own joints q = proposals[L][j] out[j] = out.get(j, q) + w * q if L.additive else (1 - w) * out.get(j, q) + w * q return out # one writer: this goes to the motors
Take one joint, the torso lean, and three layers. Idle asks for a lean of 3 degrees, weight 1, priority 0. Gaze asks for 10 degrees to face the speaker, weight 0.5, priority 1. Gesture asks for 25 degrees to lean into a point, weight 1, priority 2. The blender applies them from the lowest priority up.
Start with idle: 3 degrees. Blend in gaze: (1 − 0.5) × 3 + 0.5 × 10 = 6.5 degrees. Blend in gesture with weight 1: (1 − 1) × 6.5 + 1 × 25 = 25 degrees. The gesture wins the joint fully. When its weight falls to 0.4 during the fade-out, the result is 0.6 × 6.5 + 0.4 × 25 = 13.9 degrees. The body slides smoothly back to the gaze pose, and the gaze layer is still pulling the whole time.
Two gestures in a row make a harder case. If you fade the first one out and then the second one in, the arm drops to rest between them. A better plan is a cross-fade: ramp one weight down while the other ramps up, over the same blend time. The two weights add to 1 at every moment, so the arm goes straight from one pose to the other. The weights are the same pair (1 − w) and w as in the formula above.
Choose the blend time to match the meaning. A quick correction, such as turning to a new speaker, can use 150 ms. A relaxed change of posture can use 600 ms. Because a blend time is a speed limit, the choice also depends on the motor: the same pose change with half the blend time needs twice the speed.
The symptom: a joint buzzes at the frequency of the control loop. Two behaviors write the same joint on alternate ticks, so the target flips between their values. Measure it: log the commanded angle and count how often its direction reverses per second. A calm joint reverses a few times a second. A fighting joint reverses fifty. The fix is structural: a single blender writes each joint, and every other component submits a layer. Nothing else ever touches a motor.
Chapter 8
Add up the delays in a speaking robot, then cover the slow ones with fast reactions so the person always sees something happen in time
You say, “Hello!” and stop. Inside the robot, five things must happen before it can answer: it must decide you are done, turn your sound into text, think of a reply, turn the reply into sound, and play it. Each takes time. Add them up and the answer arrives well after the 200 ms that people expect.
You cannot make a language model answer in 200 ms. But you can make sure that something happens in 200 ms. This chapter is about building that layer of fast reactions, and about counting the delays honestly.
Latency is the delay between a cause and its effect. A latency budget lists every stage of a pipeline with its delay, so that you can see where the time goes. Here are the stages of a typical speaking robot. The numbers are illustrative; measure your own.
A worked sum, with streaming off: E 150 + A 250 + L 500 + T 200 + M 60 = 1,160 ms. That is 5.8 times the typical gap of about 200 ms. Even with every stage fast, the language model alone eats more than the whole budget. So shortening stages is not enough. We need a second idea.
Living things react at several speeds at once. A flinch comes first. A nod comes next. A considered answer comes last. A robot can do the same, with a different loop for each.
A reflex needs no thinking: turn the head toward a sudden sound, or look at a face that appears. It runs in a fast loop on the robot itself, at 50 to 100 updates per second, and takes about 100 ms or less. An acknowledgment says “I heard you”: a nod, a short “mm”, a glance. It needs only the endpoint, so it can start about 200 ms after you stop. A deliberate response is the words and the gestures that fit them. It needs the whole pipeline and takes as long as the pipeline takes.
The idea is to schedule them in that order. The acknowledgment buys time for the words. And while the language model works, the robot can show a thinking behavior, such as the gaze aversion from Chapter 2, so that the wait reads as thought and not as failure.
The top bar adds up the stages after you stop speaking. The two rows below show when the body first reacts and when the voice starts. The dashed line is the typical gap of about 200 ms.
Illustrative budget: endpoint 150 ms; recognition 250 ms (50 ms when streaming); language model as set; synthesis 200 ms (150 ms when streaming); output 60 ms. The nod starts when the endpoint fires and takes 60 ms to move. The look away starts at the same time. Only the typical gap of about 200 ms comes from a study (Stivers et al., 2009).
Try it. With everything off, the voice starts about 1.2 seconds after you stop. Streaming trims the middle stages. The nod does not change when the words arrive, but it changes what you see: a reaction at about 210 ms, close to the gap. The words still come later, but now they come to someone who is clearly being heard.
The split follows the speed. The reflex and the nod live on the robot in a tight loop, with no network. The recognition and the model may run in the cloud, so a network round trip, often tens of milliseconds, sits inside their delays. A good design keeps the fast loops local, so that a slow network never freezes the body.
There is also a way to attack the stages themselves. Speech models that listen and speak at the same time, called full-duplex models, remove the hand-off between stages. Our lessons on Moshi and DuplexSLA show how they work. Even then, the body layers of this lesson still apply: a fast model still needs a robot that nods.
A budget on paper is a plan. To check it, stamp the clock at each stage boundary in the real system: when the endpoint fired, when the transcript arrived, when the first token arrived, when the first audio sample played. The differences between the stamps are the real delays.
Then look at more than the average. A language model that takes 500 ms on average may take 1,200 ms one time in twenty. Report the median and the 95th percentile for each stage. People remember the slow replies, not the average ones, so the tail is what makes a robot feel unreliable. If the tail is long, the fast reactions are even more important, because they are the only thing on the body during a slow reply.
Take the reflex of looking at a face that appears. If the camera runs at 30 frames per second, a new frame arrives every 33 ms. Add detection time, say 20 ms, and the control loop at 10 ms, and the head can start to move after about 60 ms. The turn itself, with a smoothstep and a speed limit, then takes several hundred milliseconds. So the reflex starts fast and finishes slowly, and that is fine: the start is what the viewer notices. These numbers are illustrative; measure your own camera and detector.
The symptom of an over-eager acknowledgment: the robot nods when you pause mid-sentence, and the nod makes you think you are done. Measure it with a log: how many nods fired before the true end of a turn? Fix it by tying the nod to the cue, not to a bare silence timer, as in Chapter 3.
The symptom of an over-used filler: the robot says “hmm, let me think” at every reply. It sounds fake by the third time. Measure how often it fires per ten replies and set a cap. A silent look away costs nothing and does not wear out as fast.
pythonimport asyncio async def on_user_done(robot, text_stream): # runs the moment the endpoint fires; each task has its own deadline ack = asyncio.create_task(robot.nod()) # acknowledgment, ~60 ms of motion think = asyncio.create_task(robot.look_away(800)) # thinking behavior while we wait first = await robot.llm.first_sentence(text_stream) # the slow part, 100 ms to 1.5 s think.cancel() # the tree preempts it (Chapter 6) await robot.speak_and_gesture(first) # Chapters 4, 5 and 7 take over
Chapter 9
Keep the numbers, the checklist, the core loop and every source in one place, and take the whole system back to the hero
A robot feels alive when its timing and its motion match what people expect. People leave a gap of about 200 ms between turns, so the robot must show a reaction inside that gap and decide quickly when you are done, using cues and not only silence. Its motion follows the animation principles: eased curves, anticipation, follow-through and constant small idle life. Its eyes go to the person who speaks and leave on purpose, briefly, to think. Its gestures come from a model that hears the stress and reads the meaning. A retargeting step fits those gestures to its own bones and limits. A behavior tree decides which behavior is in charge on every tick, and a blender is the only writer of joint targets, so nothing snaps or fights.
| What | Number | Why it matters |
|---|---|---|
| Gap between turns | most common gap 0 to 200 ms, in all of 10 languages | The target for a first reaction (Stivers et al., 2009) |
| Time to produce a word | over 600 ms | Listeners must predict the end of a turn (Levinson and Torreira, 2015) |
| Smoothstep peak speed | 1.5 times the average | Easing needs a faster motor than a straight line of the same length |
| 40° head turn in 400 ms | 100°/s average, 150°/s peak | Check the peak against the motor |
| Gaze aversion study | 30 participants, a NAO robot | Aversions read as intentional and thoughtful, and bad timing backfired (Andrist et al., 2014) |
| Audio framing | 16,000 samples per second, 20 ms frames: 320 samples, 50 frames per second | The grid on which the VAD speaks |
| Co-speech gesture training data | about 52 hours of TED talks | Text-only gesture learning (Yoon et al., 2018) |
| Gesture model input and output | audio + text in, joint angle rotations out | Beats from sound, meaning from words (Kucherenko et al., 2020) |
| Reach ratio, toy arms | 34 / 58 = 0.59 | Scale the hand path before solving IK |
| Fade for a 52° step, 300 ms | 260°/s peak, against 5,200°/s with no fade | A blend time is a speed limit |
| Illustrative latency budget | 150 + 250 + 500 + 200 + 60 = 1,160 ms | Why a fast local nod matters (illustrative numbers) |
This is a sketch. sense, tree, layers, blend and robot stand for the parts built in the chapters.
pythonimport time HZ = 100 # one control tick every 10 ms (Chapter 1) bb = {} # blackboard: shared facts (Chapter 6) def control_loop(sense, tree, layers, blend, robot): nxt = time.monotonic() while True: bb.update(sense()) # VAD, speaker angle, faces, reply text (Chapters 2, 3) tree(bb) # tick: leaves set layer.want to 0 or 1 (Chapter 6) for L in layers: L.step(1000 / HZ) # weights ramp over each blend time (Chapter 7) targets = blend(layers, bb["proposals"]) # the only writer of joint targets robot.send(clamp_and_slow(targets)) # limits and soft stops (Chapter 5) nxt += 1 / HZ time.sleep(max(0, nxt - time.monotonic())) # hold the rate; log any overrun (Chapter 8)
This lesson covers the layer between the models and the motors. Below it sit the speech stack and the control stack: speech recognition, speech synthesis, streaming audio and, for the motors, inverse kinematics. Above it sits the conversation itself, which the voice turn-taking lesson treats in depth. Learning a behavior from demonstrations, instead of writing it, is the subject of imitation learning.
Every claim above that carries a number or a name comes from one of these. Numbers marked illustrative in a device are our own, for teaching.
Now press Teach and explain one reaction from memory: what the robot hears, which cue ends the turn, which layer moves first, how the tree and the blender share the body, and what the person sees inside 200 ms. Then go back to the hero and wake the robot again, and name the chapter behind each layer.