1import json
2from transformers import AutoModelForCausalLM, AutoTokenizer
3
4SYSTEM = ("You translate ONE English instruction for a tracked robot "
5 "with a gripper arm into a single JSON object "
6 '{"commands":[...]} using actions: move, turn, stop, wait, '
7 "grasp, release. Output ONLY the JSON object, no prose, no "
8 'markdown. If the instruction is out of scope or nonsense, '
9 'output {"commands": []}.')
10
11tok = AutoTokenizer.from_pretrained("PATH_OR_REPO")
12model = AutoModelForCausalLM.from_pretrained("PATH_OR_REPO",
13 torch_dtype="auto",
14 device_map="auto")
15
16def translate(instruction: str) -> dict:
17 user = SYSTEM + "\n\n---\nINSTRUCTION: " + instruction.strip()
18 enc = tok.apply_chat_template(
19 [{"role": "user", "content": user}],
20 tokenize=True, add_generation_prompt=True,
21 return_dict=True, return_tensors="pt").to(model.device)
22 out = model.generate(**enc, max_new_tokens=160, do_sample=False)
23 txt = tok.decode(out[0][enc["input_ids"].shape[1]:],
24 skip_special_tokens=True)
25 i, j = txt.find("{"), txt.rfind("}")
26 try:
27 return json.loads(txt[i:j + 1])
28 except Exception:
29 return {"commands": []} # safe fallback
30
31print(translate("go forward 2 meters then turn left"))
32# {"commands": [{"action": "move", "direction": "forward",
33# "distance_m": 2.0}, {"action": "turn", "direction": "left",
34# "angle_deg": 90}]}
35print(translate("pick it up")) # {"commands": [{"action": "grasp"}]}
36print(translate("make me a coffee"))# {"commands": []}
Weights are a derivative of Google
Gemma-3 — use is governed by the
Gemma Terms of Use. Accompanying
code is under its own license (see the source repository).