Connecting your robot
Your service is running and your key is in hand — this page turns that into working code. What your client sends, what comes back, how images and joint values have to be ordered, and a Python control loop that keeps the arm moving while the next request is still in flight.
Everything up to this page happened in a browser. This is the part you cannot click: your robot has to open a connection, send what its cameras and joints report, and act on the commands that come back — thirty times a second, for as long as the task lasts.
So this page is written for your editor rather than the console. By the end of it you will have opened a connection to your service, sent one real observation and read the reply, and run a 30 Hz control loop against it — and you will know the three mistakes that produce a service answering every call perfectly while driving the robot into the table.
Before you start
You need five things in hand.
| What | Where it comes from | Looks like |
|---|---|---|
| The address | The address row on your service's page at https://bicameral.studio/inference |
grpc.bicameral.studio:443 |
| Service ID | The Service ID row on the same page, also the last part of that page's web address | a82b7f877ee6 |
| API key | The Service created screen, shown once when you started the service | tk_ followed by 43 URL-safe characters |
robot_inference.proto |
Download it from the inference service page (or /robot_inference.proto on this site). The page and the first line of the file show Last-Updated; re-download if yours is older. |
A text file you pass to grpcurl or compile into client code |
| A service reading Running | The status badge on the same page | Not Provisioning, not a final status |
Use the address exactly as your own service page shows it. Addresses in the examples below are stand-ins. If that row shows anything other than a name and a number joined by a colon, see Inference services before building against the service.
The key is shown once and cannot be shown again
Copy it into your secret manager the moment it appears. If you lose it, the only way forward is to stop the service and create a new one, which gives you a new address, a new service ID and a new key — and another wait. See Inference services.
Wait for Running before you dial. A new service takes minutes, not seconds, to become ready, and it does not accept connections until it is genuinely ready — so a service reading Running really is answerable.
The four words this page uses
A policy is the model you trained: it takes what the robot sees and where its joints are, and returns numbers you send to motors.
An observation is one complete snapshot you hand the policy for a single decision — one image per camera, one flat vector of joint readings, one plain-English instruction. It is literally the request message. Nothing is remembered between calls, so every request carries the whole observation, instruction included, every time.
An action chunk is the reply: a small two-dimensional array where each row is the command for one future timestep. Row 0 is what to do now, row 1 is what to do a thirtieth of a second from now, and so on. It is batching to hide latency, in the same way you would ask a text model for fifty tokens in one call rather than making fifty calls.
gRPC is a remote-procedure-call framework over HTTP/2. Rather than posting a document to a URL, you call
named methods whose request and response types are protocol-buffer messages, defined in a .proto schema you
compile into client code for your language. Its equivalent of HTTP headers is called metadata — key/value
pairs, keys lowercase, attached to every call. Both of your credentials travel that way.
The three methods you can call
Everything lives in one gRPC service, robot_inference.RobotPolicyService.
| Fully-qualified method | Kind | Request | Response | Use it for |
|---|---|---|---|---|
robot_inference.RobotPolicyService/HealthCheck |
unary | HealthCheckRequest (empty) |
HealthCheckResponse |
A readiness gate before the control loop, and after any reconnect. |
robot_inference.RobotPolicyService/GetActionChunk |
unary | ObservationRequest |
ActionChunkResponse |
Ordinary chunk-at-a-time control. This is the method you will use. |
robot_inference.RobotPolicyService/StreamActionChunks |
bidirectional stream | stream of ObservationRequest |
stream of ActionChunkResponse |
High-rate control where per-call overhead matters. Read the caveats below first. |
HealthCheckResponse carries healthy (bool, field 1), status (string, field 2, a short human-readable
line) and model_name (string, field 3).
Schema discovery over the connection is not available, so tools that normally read a schema from a live
endpoint — grpcurl without -proto, most GUI gRPC clients — cannot. Always pass the proto file explicitly.
Authentication
Two metadata headers, on every single call, including HealthCheck. There is no login step and no session
to establish — these two headers are the whole of it.
| Metadata key | Value |
|---|---|
x-api-key |
The tk_… key from the Service created screen |
x-service-id |
The Service ID exactly as shown on the service page |
Copy the service ID literally: lowercase, no surrounding quotes, no trailing newline, no stray whitespace. A value that picked up any of those is rejected as malformed rather than treated as a wrong ID.
Unary or streaming
GetActionChunk is a unary call: one request, one response, like an HTTP POST. StreamActionChunks keeps one
connection open and carries the same two message types over it, one response per request you push.
Use GetActionChunk unless you have measured a reason not to. It is the well-trodden path, and per-call
overhead on a reused channel is small next to the compute time you are already paying for.
A streaming-only client can be stopped out from under itself
A service that has gone one full idle window with nothing calling it is stopped for you. Only
GetActionChunk counts as calling it: HealthCheck does not, and neither does traffic on
StreamActionChunks. A robot driving exclusively through the stream looks completely idle. If you stream,
set the idle timeout to zero when you create the service and manage its life yourself — see
Inference services.
One more thing to design for: a single call, including one open stream, will not last indefinitely. Treat stream termination as a normal event rather than an error — nothing is remembered between calls, so there is nothing to resume and nothing to lose. Recycle the stream and reconnect.
Your first call
Generate the client stubs and run a health check. This is the shortest path from a running service to proof that your credentials, your address and your channel type are all correct.
#!/usr/bin/env bash
set -euo pipefail
# 1. Tooling.
pip install grpcio grpcio-tools
# 2. Generate robot_inference_pb2.py and robot_inference_pb2_grpc.py in the
# current directory, from the proto file next to it.
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. robot_inference.proto
# 3. Fill these in from https://bicameral.studio
ENDPOINT="grpc.bicameral.studio:443" # the address row, service page
KEY="tk_replace_me" # shown once, right after you create the service
SERVICE_ID="a82b7f877ee6" # the Service ID row, service page
PROTO="./robot_inference.proto"
# 4. Readiness gate. -proto is mandatory: the schema is not discoverable over the wire.
# The endpoint is TLS on 443, which is grpcurl's default — no -plaintext.
grpcurl \
-H "x-api-key: ${KEY}" \
-H "x-service-id: ${SERVICE_ID}" \
-proto "${PROTO}" \
-max-time 60 \
"${ENDPOINT}" robot_inference.RobotPolicyService/HealthCheck
Expect "healthy": true before you drive anything. A TLS handshake error here usually means the client is
dialing plaintext: the endpoint only accepts TLS, so drop any -plaintext flag you carried over from an
older setup.
That is the whole connection proved. The rest of the page is about what you put in the request.
What you send: ObservationRequest
This is the GetActionChunk request, and the same message is what you push into StreamActionChunks.
| Field | Number | Type | Required | Meaning |
|---|---|---|---|---|
images |
1 | repeated CameraImage |
in practice yes | One compressed image per camera, in the order the policy was trained with. |
robot_state |
2 | RobotState |
yes | The joint readings. The one strictly required field. |
prompt |
3 | string | in practice yes | The plain-English instruction, for example pick up the red block. |
prefix_action |
4 | repeated ActionVector |
no | Real-time chunking. See below. |
delay |
5 | int32 | no | Pairs with prefix_action. Ignored when prefix_action is empty. |
timestamp_ns |
6 | int64 | no | Your own clock, in nanoseconds. Passed through untouched. |
request_id |
7 | string | no | Any string you choose. Echoed back unchanged. |
The three nested messages are small:
| Message | Field | Number | Type | Meaning |
|---|---|---|---|---|
CameraImage |
image_data |
1 | bytes | The raw bytes of a JPEG or PNG file. |
CameraImage |
encoding |
2 | string | Lowercase "jpeg" or "png". |
RobotState |
state |
1 | repeated float | The flat joint vector. |
ActionVector |
values |
1 | repeated float | One command vector. |
Set request_id on every call. It costs nothing, it is the only way to match replies to requests on a stream,
and it is the only handle support has for finding one specific call.
Images
Send JPEG at quality around 85. PNG is accepted and produces payloads several times larger, which is felt immediately over Wi-Fi.
- Colour order is RGB. Not BGR.
- Resolution does not matter. Each frame is resized for you to what the policy expects, aspect ratio preserved. Any reasonable capture resolution works.
- Do not normalise, scale, or mean-subtract pixel values. Send ordinary 8-bit pixels.
OpenCV hands you BGR, and nothing will tell you
cv2.imread and cv2.VideoCapture.read return frames with the blue and red channels swapped relative to
what the policy expects. A BGR frame is a perfectly valid JPEG, so it encodes cleanly, transmits cleanly,
decodes cleanly, and produces a confident action chunk that is wrong. Convert with
cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) before cv2.imencode — note the direction: you are converting
your RGB array into what imencode expects, so the JPEG comes out RGB.
Camera order is decided at training time
This is the single most common cause of a silent failure, so it gets its own section.
The protocol has no camera names. images[0] is the camera the policy calls camera0, images[1] is
camera1, and so on. That mapping was frozen when you trained, from the observation.images.* feature names
in your LeRobot dataset — the meta/info.json file that lists every recorded channel. Datasets
shows where that file sits in the folder you uploaded.
The default rule is that those names are sorted lexicographically and assigned in that order. Concretely,
given a dataset whose meta/info.json declares its features like this:
{
"features": {
"observation.images.wrist": {"dtype": "video", "shape": [480, 640, 3]},
"observation.images.top": {"dtype": "video", "shape": [480, 640, 3]},
"observation.images.side": {"dtype": "video", "shape": [480, 640, 3]},
"observation.state": {"dtype": "float32", "shape": [14]},
"action": {"dtype": "float32", "shape": [14]}
}
}
the mapping is not the order they appear in the file. Sorted, side < top < wrist, so:
| Request index | Feature it corresponds to |
|---|---|
images[0] |
observation.images.side |
images[1] |
observation.images.top |
images[2] |
observation.images.wrist |
The wrist camera is listed first in the file and is sent last on the wire.
Confirm your camera order — do not derive it
The alphabetical rule is the default, not a guarantee: a feature mapping you supplied explicitly when you configured the run wins outright. Nothing reports back which mapping a policy resolved to, so the only reliable answer is an empirical one.
Nothing on the wire can detect a swap. Two cameras sent in the wrong order produce a service that answers every call in the normal time with a normal-looking chunk, and a robot that reaches confidently for the wrong place.
To confirm the order empirically, replay a recording you already have the answer for:
- Pick one frame index from one episode of the dataset the policy was trained on.
- Extract that frame from each camera video, and the matching row of
observation.state. - Send them as one observation, with the same instruction that episode was labelled with.
- Compare the first row of the returned chunk against the
actionrow recorded at that same index. Actions come back already un-normalised and in your dataset's own units, so the two are directly comparable. - If they are close, your camera order and state layout are right. If they are not, swap two cameras and repeat.
Read this as a relative test rather than an absolute one: the correct ordering comes out visibly closer to the recorded action than any wrong ordering does.
The joint state vector
robot_state.state is a flat list of floats describing where every actuated part of the robot is right now:
one number per joint angle, plus a number for each gripper (the hand at the end of the arm, usually
expressed as an opening amount), plus any other actuated axis.
The element order and the units are whatever your training dataset's observation.state column used. The
protocol does not define them, does not carry them, and cannot check them. If element 7 was a wrist angle in
radians during training, it must be a wrist angle in radians now.
- It is required. An empty or missing state is rejected with
INVALID_ARGUMENTand the messageRobot state is required. - Send your real length. If your robot's state is narrower than the policy expects, it is padded for you. Never pad or truncate it yourself.
- A reordered or rescaled state produces no error. Like camera order, this fails silently.
The prompt
Send the instruction on every request. Nothing is remembered between calls, so a request without a prompt is a request where the policy does not know what you want on that tick. An empty string is legal on the wire; running a vision-and-language policy without an instruction is not a supported mode.
The instruction is tokenised to a budget fixed at training time — far more than a label like
pick up the red block needs.
prefix_action and delay
These two fields are real-time chunking: you tell the policy which commands you are already committed to
executing, so the new chunk is planned to splice onto motion already in flight instead of starting from
scratch. prefix_action is that list of committed commands, oldest first; delay says how many of them will
have executed by the time the reply arrives.
Real-time chunking needs a training-time setting you probably did not enable
It does something only if the policy was trained with a non-zero Max delay, and that box defaults to
0. With the default, sending prefix_action and delay is at best a no-op, and the number you set in
Max delay is what these two fields are measured against. See Max delay in
Training. Omit both fields for the standard loop.
Sending one observation from the shell
Useful for the camera-order check above, before any client code exists:
#!/usr/bin/env bash
set -euo pipefail
ENDPOINT="grpc.bicameral.studio:443"
KEY="tk_replace_me"
SERVICE_ID="a82b7f877ee6"
PROTO="./robot_inference.proto"
# One base64 blob per camera, in the trained camera order.
# image_data is a protobuf bytes field, so grpcurl's JSON needs base64 on ONE line.
# -w0 suppresses wrapping on Linux; on macOS, `base64 -i camera0.jpg` is already unwrapped.
IMG0=$(base64 -w0 camera0.jpg)
IMG1=$(base64 -w0 camera1.jpg)
# Replace the 14 numbers with your own observation.state row, in its own order and units.
cat > request.json <<EOF
{
"request_id": "req_001",
"prompt": "pick up the red block",
"images": [
{"image_data": "${IMG0}", "encoding": "jpeg"},
{"image_data": "${IMG1}", "encoding": "jpeg"}
],
"robot_state": {
"state": [0.01, -0.12, 0.33, 0.00, 0.05, -0.41, 0.27,
0.00, 0.11, -0.08, 0.19, 0.02, -0.30, 0.14]
}
}
EOF
grpcurl \
-H "x-api-key: ${KEY}" \
-H "x-service-id: ${SERVICE_ID}" \
-proto "${PROTO}" \
-max-msg-sz 104857600 \
-max-time 60 \
-d @ \
"${ENDPOINT}" robot_inference.RobotPolicyService/GetActionChunk \
< request.json
What comes back: ActionChunkResponse
| Field | Number | Type | Meaning |
|---|---|---|---|
action_chunk |
1 | repeated ActionVector |
The plan. One row per future timestep, oldest first. |
timestamp_ns |
2 | int64 | When the reply was produced, in nanoseconds. Not your clock. |
request_id |
3 | string | Your request_id, echoed unchanged. |
inference_time_ms |
4 | float | Compute time only. It excludes your network round trip. |
Row t of action_chunk is the command for timestep t after the observation you sent. The values are
already un-normalised and in your robot's own units — do not rescale them.
How many rows, and how wide
The number of rows is the Action chunk length fixed when the policy was trained; the default is 50. All training data is brought to a control rate of 30 Hz — one command every 33.3 ms — so a 50-row chunk is about 1.67 seconds of motion, and that number is your entire budget for hiding one round trip.
The width of each row is a different matter.
Read the action width off the first real response
Do not hardcode it. A returned row can be wider than the number of actuators you drive. Log
len(response.action_chunk[0].values) on your first successful call, compare it to your actuator count,
and slice explicitly in your driver.
Channel settings
| Setting | Value | Why |
|---|---|---|
| Per-call deadline | 30 seconds | The first call after a service becomes ready is far slower than the ones that follow it. A one-second deadline turns a healthy service into an unbroken stream of DEADLINE_EXCEEDED. |
| Max send / receive message length | 104857600 (100 MB) |
gRPC's own default receive limit is 4 MB, which two full-resolution frames can exceed. Overshooting it fails with RESOURCE_EXHAUSTED. |
| Keepalive | 30 s ping interval, 10 s ping timeout, pings permitted without active calls | Open one channel and reuse it for the whole session. A channel that goes quiet between chunks can be dropped by intermediate networking, and the reconnect lands at exactly the moment the robot is waiting. |
| Concurrency | One request in flight per robot | Pipelining speculative requests gets you chunks planned from stale states. |
On transport security: the endpoint is gRPC over TLS on port 443 and accepts nothing else, so dial a TLS
channel — grpc.secure_channel in Python, plain grpcurl with no extra flag. Your API key and every
observation you send are encrypted in transit as a result; a plaintext channel simply fails to connect.
A complete Python client
Save this as client.py, next to the generated stubs. It runs as written — the camera and robot functions
produce synthetic data so you can prove the connection before wiring in hardware — and the control loop in the
next section imports from it.
#!/usr/bin/env python3
"""bicameral policy client: connect, health-check, request one action chunk.
Prerequisites
-------------
pip install grpcio grpcio-tools numpy opencv-python
# Generate the stubs next to this file:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. robot_inference.proto
Environment
-----------
BICAMERAL_ENDPOINT host:port from the address row on the service page
INFERENCE_API_KEY the tk_ prefixed key shown once when the service was created
SERVICE_ID the Service ID from the service page
Run
---
python client.py
"""
import os
import time
import cv2
import grpc
import numpy as np
import robot_inference_pb2 as pb
import robot_inference_pb2_grpc as pb_grpc
ENDPOINT = os.environ.get("BICAMERAL_ENDPOINT", "grpc.bicameral.studio:443")
API_KEY = os.environ["INFERENCE_API_KEY"]
SERVICE_ID = os.environ["SERVICE_ID"]
PROMPT = "pick up the red block"
NUM_CAMERAS = 2 # must match what the policy was trained with
STATE_DIM = 14 # your observation.state width
CONTROL_HZ = 30.0 # fixed at training time; do not deviate
DT = 1.0 / CONTROL_HZ
REQUEST_TIMEOUT_S = 30.0 # generous: the first call after startup is slow
# Both credentials ride on every call, including HealthCheck. Keys are lowercase.
METADATA = (
("x-api-key", API_KEY),
("x-service-id", SERVICE_ID),
)
CHANNEL_OPTIONS = [
# gRPC's 4 MB default is too small for multi-camera payloads.
("grpc.max_send_message_length", 100 * 1024 * 1024),
("grpc.max_receive_message_length", 100 * 1024 * 1024),
# Keep the connection alive between chunks so no call pays a reconnect.
("grpc.keepalive_time_ms", 30_000),
("grpc.keepalive_timeout_ms", 10_000),
("grpc.keepalive_permit_without_calls", 1),
("grpc.http2.max_pings_without_data", 0),
]
def open_channel():
"""One channel per process. Channels and stubs are thread-safe; reuse them."""
return grpc.secure_channel(
ENDPOINT, grpc.ssl_channel_credentials(), options=CHANNEL_OPTIONS
)
def encode_jpeg(rgb: np.ndarray, quality: int = 85) -> bytes:
"""Encode an HxWx3 uint8 RGB array as JPEG bytes.
cv2.imencode expects BGR, so an RGB array must be converted going in for the
resulting JPEG to be RGB. Sending BGR is accepted silently and drives badly.
"""
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
ok, buf = cv2.imencode(".jpg", bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
if not ok:
raise RuntimeError("JPEG encode failed")
return buf.tobytes()
def read_cameras() -> list:
"""Return one HxWx3 uint8 RGB frame per camera, IN THE TRAINED CAMERA ORDER.
Replace the synthetic frames with real grabs. If you grab through OpenCV,
convert BGR -> RGB here, not later.
"""
frames = []
for i in range(NUM_CAMERAS):
frame = np.zeros((480, 640, 3), dtype=np.uint8)
frame[:, :, i % 3] = 128
frames.append(frame)
return frames
def read_joint_state() -> list:
"""Return the joint vector in the trained element order and units."""
return [0.0] * STATE_DIM
def apply_action(action) -> None:
"""Command the robot with one action vector. Replace with your driver call.
action.values may be wider than your actuator count; slice explicitly.
"""
_ = list(action.values)[:STATE_DIM]
def build_observation(frames, joint_state, prompt: str, request_id: str):
"""Assemble one ObservationRequest. Nothing is remembered: send everything."""
request = pb.ObservationRequest()
request.prompt = prompt
request.request_id = request_id
request.timestamp_ns = time.time_ns()
for frame in frames:
image = request.images.add()
image.image_data = encode_jpeg(frame)
image.encoding = "jpeg"
request.robot_state.state.extend(float(v) for v in joint_state)
return request
def wait_until_ready(stub, attempts: int = 60, backoff_s: float = 10.0) -> None:
"""Poll HealthCheck until the policy answers. Startup takes minutes."""
for attempt in range(attempts):
try:
reply = stub.HealthCheck(
pb.HealthCheckRequest(), metadata=METADATA, timeout=REQUEST_TIMEOUT_S
)
if reply.healthy:
print(f"ready: {reply.status}")
return
except grpc.RpcError as exc:
print(f"health check attempt {attempt + 1}: {exc.code().name}")
time.sleep(backoff_s)
raise RuntimeError("service never became healthy")
def request_chunk(stub, frames, joint_state, request_id: str):
"""One observation in, one action chunk out, with retries on transient codes."""
transient = (grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED)
for attempt in range(3):
try:
return stub.GetActionChunk(
build_observation(frames, joint_state, PROMPT, request_id),
metadata=METADATA,
timeout=REQUEST_TIMEOUT_S,
)
except grpc.RpcError as exc:
if exc.code() not in transient or attempt == 2:
raise
time.sleep(0.5 * (attempt + 1))
raise RuntimeError("unreachable")
def main() -> None:
with open_channel() as channel:
stub = pb_grpc.RobotPolicyServiceStub(channel)
wait_until_ready(stub)
reply = request_chunk(stub, read_cameras(), read_joint_state(), "probe-0")
rows = len(reply.action_chunk)
width = len(reply.action_chunk[0].values) if rows else 0
print(f"chunk: {rows} rows x {width} values")
print(f"compute: {reply.inference_time_ms:.1f} ms")
print(f"echoed request_id: {reply.request_id}")
print(f"seconds of motion: {rows / CONTROL_HZ:.2f}")
# Row t is the command for timestep t after the observation, oldest first.
for t, action in enumerate(reply.action_chunk[:3]):
print(f" t={t}: {[round(v, 4) for v in action.values]}")
if __name__ == "__main__":
main()
Run it once against a running service before you write anything else. The printed row count and width are the two numbers your driver has to agree with.
Running a control loop
The reason an action chunk exists is that you cannot afford a round trip per tick. At 30 Hz you have 33 ms per command; a call costs compute time plus your network. So you execute the chunk you already hold while the next request is in flight, and you never let the queue reach zero.
Save this as control_loop.py next to client.py.
#!/usr/bin/env python3
"""bicameral control loop: execute the current chunk while the next is in flight.
Run
---
python control_loop.py
"""
import time
from concurrent.futures import ThreadPoolExecutor
import robot_inference_pb2_grpc as pb_grpc
from client import (
CONTROL_HZ,
DT,
apply_action,
open_channel,
read_cameras,
read_joint_state,
request_chunk,
wait_until_ready,
)
# Ticks of executable motion still in hand when the next request goes out.
# 15 ticks at 30 Hz = 500 ms of cover. Size this from measured latency.
REFILL_MARGIN = 15
MAX_TICKS = 300 # 10 seconds of motion
def control_loop(stub, max_ticks: int = MAX_TICKS) -> None:
pending = [] # rows not yet executed, oldest first
in_flight = None # the Future for the request currently outstanding
requested_at_tick = 0 # the tick whose observation that request carries
last_action = None # what to hold if a chunk arrives late
starved = 0
tick = 0
next_deadline = time.perf_counter()
# One worker: exactly one request outstanding per robot, never two.
with ThreadPoolExecutor(max_workers=1) as pool:
while tick < max_ticks:
# 1. Ask for the next chunk while there is still motion in hand.
if in_flight is None and len(pending) <= REFILL_MARGIN:
requested_at_tick = tick
in_flight = pool.submit(
request_chunk,
stub,
read_cameras(),
read_joint_state(),
f"tick-{tick}",
)
# 2. Collect it the instant it lands, without blocking this tick.
if in_flight is not None and in_flight.done():
reply = in_flight.result()
in_flight = None
# Row t of the reply is timestep t AFTER the observation that
# produced it. Ticks have passed since then, so those leading
# rows describe motion already executed: drop them.
elapsed = tick - requested_at_tick
rows = list(reply.action_chunk)
if elapsed < len(rows):
pending = rows[elapsed:]
print(
f"tick {tick}: {len(rows)} rows, "
f"{reply.inference_time_ms:.0f} ms compute, "
f"{elapsed} ticks stale, {len(pending)} usable"
)
# 3. One command per tick, always.
if pending:
last_action = pending.pop(0)
else:
starved += 1 # raise REFILL_MARGIN if you ever see this
if last_action is not None:
apply_action(last_action)
# 4. Absolute-deadline pacing: errors do not accumulate.
tick += 1
next_deadline += DT
sleep_s = next_deadline - time.perf_counter()
if sleep_s > 0:
time.sleep(sleep_s)
else:
next_deadline = time.perf_counter()
print(f"done: {tick} ticks at {CONTROL_HZ:.0f} Hz, {starved} starved ticks")
def main() -> None:
with open_channel() as channel:
stub = pb_grpc.RobotPolicyServiceStub(channel)
wait_until_ready(stub)
try:
control_loop(stub)
finally:
# Always leave the robot somewhere safe.
print("stopped; hold the arm in a safe pose here")
if __name__ == "__main__":
main()
The latency reasoning
Three numbers decide whether this loop is smooth.
Your budget is the chunk length. 50 rows at 30 Hz is 1.67 seconds. That is the total amount of motion one call buys you, and everything else is spent out of it.
Your cover is the refill margin. REFILL_MARGIN is how much executable motion you still hold when the
request goes out. It must exceed your worst-case round trip — inference_time_ms plus your network —
expressed in ticks. At 30 Hz, 15 ticks is 500 ms. Log inference_time_ms on real calls, take your worst
observed value, add your network, convert to ticks, and then double it. If starved is ever non-zero, the arm
stopped mid-trajectory and the margin is too small.
Your cost is staleness. The chunk that arrives was planned from an observation captured elapsed ticks
ago, so its first elapsed rows describe motion that has already happened. The loop above drops them. That
means a larger margin gives you more safety and more staleness at once: the actions you finally execute were
planned from an older view of the world. Set the margin as small as your measured latency safely allows, not as
large as possible.
Dropping the leading rows follows directly from the contract: row t is timestep t after the observation,
and the control rate is a fixed 30 Hz, so elapsed ticks of the plan are already behind you by the time it
lands. Real-time chunking is the mechanism that removes this seam entirely, and it needs a training-time
setting — see prefix_action and delay above.
Blocking the loop on the call instead — asking only once the queue is empty — freezes the arm for the whole duration of every call, roughly three times a second. It is visible, and it is hard on hardware.
Troubleshooting
Every call succeeds and the robot still moves wrongly
A shape or layout mismatch looks like success. Every call returns OK, inference_time_ms sits in its
normal range, the chunk has the expected number of rows, and the robot moves smoothly toward the wrong place —
or oscillates, or reaches past the object. There is no error code for this, because nothing on the path knows
what your numbers mean.
Work through these in order, changing one thing at a time:
| Check | How to test it |
|---|---|
| Camera order | Swap images[0] and images[1] and see whether behaviour improves. Then confirm properly with the replay procedure under Camera order. |
| Colour order | Save one frame exactly as it goes on the wire and open it. If people look blue, you are sending BGR. |
| Joint order and units | Replay a recorded observation and compare the first returned row against the recorded action row. Radians against degrees is the classic. |
| Action element order | Print the returned row next to your actuator list. An arm that moves the right amount on the wrong joint is an output-side permutation. |
| Action width | len(reply.action_chunk[0].values) against your actuator count. If it is wider, you are being handed padding — slice, do not reinterpret. |
| Control rate | Confirm you are executing one row per 1/30 s. Playing rows faster or slower distorts the motion in a way that reads as a badly trained policy. |
An INTERNAL error with a message beginning Inference error: is different: that is a corrupt image, an
encoding string that disagrees with the actual bytes, or a state vector of an unexpected length. Confirm each
image decodes standalone, then send support the request_id and the response timestamp_ns.
The call is rejected
| What you get back | What it means | What to do |
|---|---|---|
UNAUTHENTICATED |
The key is missing, misspelled, or belongs to another service. | Attach x-api-key to every call, including HealthCheck. A lost key cannot be recovered — see Inference services. |
INVALID_ARGUMENT, message naming the service-id header |
The header is absent. | Add x-service-id. Both headers are required on every call. |
INVALID_ARGUMENT, message about the service ID format |
Trailing newline, quotes, whitespace, or upper case crept in. | Send the Service ID exactly as the service page shows it. |
INVALID_ARGUMENT, Robot state is required |
robot_state.state was empty or absent. |
Populate it. It is the one strictly required field. |
| A TLS handshake error, or the connection closes as it opens | You are dialing plaintext against a TLS-only endpoint. | Use grpc.secure_channel with grpc.ssl_channel_credentials(), and drop -plaintext from grpcurl. |
Unknown service or Unknown method from grpcurl |
The schema was never loaded. | Pass -proto ./robot_inference.proto. The method is robot_inference.RobotPolicyService/GetActionChunk. |
DEADLINE_EXCEEDED on the very first call |
Your deadline is shorter than a cold first call. | Use 30 seconds. |
RESOURCE_EXHAUSTED |
The payload is above the message-size limit. | Use "jpeg" rather than "png", and set both message-length options to 104857600. |
Calls that used to work now fail immediately
UNAVAILABLE on every method, with no partial degradation and no warning beforehand, means the service is no
longer running. Open its page in the console and read the status badge.
A service that has reached a final status cannot be restarted. Serving the same policy again means creating a new service, which gives you a new address, a new Service ID and a new key shown once — so anything that hardcoded the old set has to be updated. Inference services covers the statuses, what causes each one, and how to keep a service alive through a long session.