urml-model 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ dist/
9
+ develop-eggs/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Virtual envs
25
+ .venv/
26
+ venv/
27
+ env/
28
+ ENV/
29
+ .python-version
30
+
31
+ # Test / coverage / mypy / pyright
32
+ .coverage
33
+ .coverage.*
34
+ .cache
35
+ .pytest_cache/
36
+ .mypy_cache/
37
+ .dmypy.json
38
+ .pyre/
39
+ .pyright/
40
+ htmlcov/
41
+ nosetests.xml
42
+ coverage.xml
43
+ *.cover
44
+ .hypothesis/
45
+ .tox/
46
+
47
+ # --- Node / web tooling (kept out of core repo; here for safety) ---
48
+ node_modules/
49
+ .pnp.*
50
+ .yarn/cache/
51
+ .yarn/unplugged/
52
+ .yarn/build-state.yml
53
+ .yarn/install-state.gz
54
+ npm-debug.log*
55
+ yarn-debug.log*
56
+ yarn-error.log*
57
+
58
+ # --- C++ / Rust build artifacts (in case reference runtimes land here in early Phase 1) ---
59
+ target/
60
+ *.o
61
+ *.obj
62
+ *.a
63
+ *.lib
64
+ *.dll
65
+ *.dylib
66
+ *.exe
67
+ *.pdb
68
+ cmake-build-*/
69
+ CMakeCache.txt
70
+ CMakeFiles/
71
+ CMakeScripts/
72
+ Testing/
73
+ cmake_install.cmake
74
+ install_manifest.txt
75
+ compile_commands.json
76
+
77
+ # --- ROS 2 build dirs ---
78
+ build/
79
+ install/
80
+ log/
81
+
82
+ # --- Editor and OS junk ---
83
+ .vscode/
84
+ .idea/
85
+ *.swp
86
+ *.swo
87
+ *~
88
+ .DS_Store
89
+ Thumbs.db
90
+ desktop.ini
91
+
92
+ # --- Local-only artifacts ---
93
+ .env
94
+ .env.*
95
+ *.log
96
+ *.tmp
97
+ .local/
98
+ .scratch/
99
+
100
+ # --- Outreach campaign artifacts (operational, not part of the open standard) ---
101
+ # Target lists, message drafts, tracking data, and the launch-approval record
102
+ # stay local. They are private to the maintainer; committing them would
103
+ # telegraph the campaign before launch and could embarrass listed projects.
104
+ outreach/
105
+
106
+ # Outreach dashboard SQLite mirror (RFC-0275). Derived from
107
+ # examples/lighthouses/outreach*.yaml via tools/scripts/refresh_outreach_db.py.
108
+ # Regenerated on demand by `make outreach-refresh`.
109
+ tools/outreach.db
110
+ tools/.outreach.db
111
+
112
+ # Local Claude Code settings (per-machine; permission rules, etc.). Not committed.
113
+ .claude/settings.json
114
+ .claude/settings.local.json
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: urml-model
3
+ Version: 0.5.0
4
+ Summary: Dataset synthesis pipeline and training recipe for a URML-native small model (RFC-0666).
5
+ Project-URL: Homepage, https://github.com/urml-dev/URML
6
+ Project-URL: Repository, https://github.com/urml-dev/URML
7
+ Project-URL: Issues, https://github.com/urml-dev/URML/issues
8
+ Author: URML Maintainers
9
+ License: BUSL-1.1
10
+ Keywords: dataset,fine-tuning,llm,robotics,urml
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: Other/Proprietary License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: pydantic<3,>=2.6
21
+ Requires-Dist: pyyaml<7,>=6.0
22
+ Requires-Dist: urml-conformance>=0.5.0
23
+ Requires-Dist: urml-llm-bridge>=0.5.0
24
+ Requires-Dist: urml-validator>=0.5.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: ruff>=0.5; extra == 'dev'
30
+ Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ <p align="center">
34
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
35
+ </p>
36
+
37
+ <p align="center">
38
+ A small, opinionated, human-readable language for describing robot intent.
39
+ </p>
40
+
41
+ <p align="center">
42
+ <a href="https://urml.dev"><b>urml.dev</b></a>
43
+ </p>
44
+
45
+ ---
46
+
47
+ # urml-model
48
+
49
+ Dataset synthesis pipeline and training recipe for a URML-native small model ([RFC-0666](../../docs/rfcs/0666-urml-native-model-pipeline.md)).
50
+
51
+ The idea: URML already owns a perfect, free, machine-checkable reward signal. A candidate program is correct exactly when `urml_validator.validate` accepts it, and when it is wrong the validator says why in ~150 namespaced error codes. This package turns that oracle plus the repository's gold assets (conformance fixtures, the few-shot library, rejected bridge emissions) into a training dataset for a small open-weights model that emits first-pass-valid URML offline.
52
+
53
+ What this package does **not** do: train a model, download weights, or call a specific LLM vendor. Training is operator-action, documented in [docs/training-recipe.md](docs/training-recipe.md). No model artifact ever lives in this repository.
54
+
55
+ ## Quick start
56
+
57
+ ```bash
58
+ # Hermetic: mine the repo's gold assets into a dataset (no network, no LLM)
59
+ urml-model synthesize --out data/urml-sft.jsonl
60
+
61
+ # Write a chat-format SFT file (system prompt = the bridge's real prompt)
62
+ urml-model export --in data/urml-sft.jsonl --out data/sft-chatml.jsonl --fmt chatml
63
+
64
+ # After training: score the model with the conformance scorer (RFC-0021 metrics)
65
+ urml-model eval --utterances-root conformance/llm-bridge/fixtures \
66
+ --profile home --backend ollama --model my-urml-3b \
67
+ --out conformance/llm-bridge/results/$(date +%F)/home-my-urml-3b.yaml
68
+ ```
69
+
70
+ ## Dataset shape
71
+
72
+ One JSONL record per example: `nl`, `program`, `manifest_ref`, `profile`, `language`, `provenance`, `validator_verdict`, optional `envelope_ref` and `repair`. Records rejected by the validator are only allowed as `rejection_repair` examples (failed emission + error codes + the accepted program as the repair target). The full schema is normative in RFC-0666.
73
+
74
+ ## Diversity at scale
75
+
76
+ The CLI's synthesize path uses the deterministic template back-translator so CI stays hermetic. Real phrasing diversity comes from `LLMBackTranslator`, a library call that takes any `LLMProvider` (Anthropic, OpenAI, Ollama, llama.cpp — the bridge's own adapters). Every candidate it produces still goes through the oracle before it enters the dataset.
@@ -0,0 +1,44 @@
1
+ <p align="center">
2
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
3
+ </p>
4
+
5
+ <p align="center">
6
+ A small, opinionated, human-readable language for describing robot intent.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://urml.dev"><b>urml.dev</b></a>
11
+ </p>
12
+
13
+ ---
14
+
15
+ # urml-model
16
+
17
+ Dataset synthesis pipeline and training recipe for a URML-native small model ([RFC-0666](../../docs/rfcs/0666-urml-native-model-pipeline.md)).
18
+
19
+ The idea: URML already owns a perfect, free, machine-checkable reward signal. A candidate program is correct exactly when `urml_validator.validate` accepts it, and when it is wrong the validator says why in ~150 namespaced error codes. This package turns that oracle plus the repository's gold assets (conformance fixtures, the few-shot library, rejected bridge emissions) into a training dataset for a small open-weights model that emits first-pass-valid URML offline.
20
+
21
+ What this package does **not** do: train a model, download weights, or call a specific LLM vendor. Training is operator-action, documented in [docs/training-recipe.md](docs/training-recipe.md). No model artifact ever lives in this repository.
22
+
23
+ ## Quick start
24
+
25
+ ```bash
26
+ # Hermetic: mine the repo's gold assets into a dataset (no network, no LLM)
27
+ urml-model synthesize --out data/urml-sft.jsonl
28
+
29
+ # Write a chat-format SFT file (system prompt = the bridge's real prompt)
30
+ urml-model export --in data/urml-sft.jsonl --out data/sft-chatml.jsonl --fmt chatml
31
+
32
+ # After training: score the model with the conformance scorer (RFC-0021 metrics)
33
+ urml-model eval --utterances-root conformance/llm-bridge/fixtures \
34
+ --profile home --backend ollama --model my-urml-3b \
35
+ --out conformance/llm-bridge/results/$(date +%F)/home-my-urml-3b.yaml
36
+ ```
37
+
38
+ ## Dataset shape
39
+
40
+ One JSONL record per example: `nl`, `program`, `manifest_ref`, `profile`, `language`, `provenance`, `validator_verdict`, optional `envelope_ref` and `repair`. Records rejected by the validator are only allowed as `rejection_repair` examples (failed emission + error codes + the accepted program as the repair target). The full schema is normative in RFC-0666.
41
+
42
+ ## Diversity at scale
43
+
44
+ The CLI's synthesize path uses the deterministic template back-translator so CI stays hermetic. Real phrasing diversity comes from `LLMBackTranslator`, a library call that takes any `LLMProvider` (Anthropic, OpenAI, Ollama, llama.cpp — the bridge's own adapters). Every candidate it produces still goes through the oracle before it enters the dataset.
@@ -0,0 +1,87 @@
1
+ # Training recipe: a URML-native small model
2
+
3
+ > Operator-run. Nothing here executes in CI, and no artifact it produces is committed to this repository (RFC-0666).
4
+
5
+ This walkthrough takes the dataset this package synthesizes and produces a LoRA fine-tune of a small open-weights model that emits first-pass-valid URML. The base model is a replaceable parameter, not an endorsement; any instruction-tuned model in the 1B to 9B class with a permissive license works. Pick per your deployment target (a Raspberry Pi 5 wants 1.5B to 3B quantized; a Jetson or desktop tolerates 7B to 9B).
6
+
7
+ ## 0. What you need
8
+
9
+ - A GPU with 16 GB or more VRAM (a single rented A10/A100/4090-class card is enough for LoRA at 3B).
10
+ - The dataset: run the synthesis on the repo checkout, then (optionally, recommended) enrich it with LLM back-translation.
11
+ - An inference server for evaluation: `ollama serve` or `llama-server`.
12
+
13
+ ## 1. Build the dataset
14
+
15
+ Hermetic floor (template utterances, every record oracle-verified):
16
+
17
+ ```bash
18
+ urml-model synthesize --out data/urml.jsonl
19
+ ```
20
+
21
+ Diversity pass (operator-action; pick any provider the bridge supports):
22
+
23
+ ```python
24
+ from urml_llm_bridge.providers.anthropic import AnthropicProvider # or openai / ollama
25
+ from urml_model import LLMBackTranslator, mine_fixture_programs, synthesize, Dataset
26
+
27
+ gold = mine_fixture_programs()
28
+ translator = LLMBackTranslator(AnthropicProvider(model="claude-haiku-4-5-20251001"))
29
+ diverse, report = synthesize(gold, translator, per_program=5)
30
+ print(report.summary())
31
+
32
+ base = Dataset.read_jsonl("data/urml.jsonl")
33
+ base.extend(diverse.records)
34
+ base.write_jsonl("data/urml.jsonl")
35
+ ```
36
+
37
+ Provider terms note: utterances written by a hosted model inherit that provider's output terms. Read them before redistributing the enriched dataset; the hermetic floor carries no such question.
38
+
39
+ If you have bridge sessions from real use (for example a `--save-rejected` debugging trail rebuilt as `TranslateResult` objects), mine them too:
40
+
41
+ ```python
42
+ from urml_model import mine_rejections, session_from_result
43
+ records = mine_rejections([session_from_result(nl, result) for nl, result in sessions],
44
+ manifest=manifest, manifest_ref="turtlebot4_home", profile="home")
45
+ ```
46
+
47
+ ## 2. Export
48
+
49
+ ```bash
50
+ urml-model export --in data/urml.jsonl --out data/sft.jsonl --fmt chatml
51
+ urml-model export --in data/urml.jsonl --out data/dpo.jsonl --fmt dpo # only if repair records exist
52
+ ```
53
+
54
+ The chatml system prompt is the bridge's real prompt (manifest summary, envelope, few-shots, JSON schema). Train on it unmodified so inference-time and training-time prompts match.
55
+
56
+ ## 3. Fine-tune (LoRA SFT)
57
+
58
+ Any LoRA-capable trainer works; the shape below is the reference point, not a framework mandate.
59
+
60
+ | knob | value | note |
61
+ | --- | --- | --- |
62
+ | method | LoRA (r=16, alpha=32, dropout 0.05) | full fine-tune is unnecessary at this dataset size |
63
+ | target modules | attention + MLP projections | the usual all-linear set |
64
+ | epochs | 2 to 3 | watch validation loss; this dataset is small and memorizes fast |
65
+ | learning rate | 1e-4 cosine, warmup 3% | |
66
+ | sequence length | long enough for the full system prompt (measure it: `urml emit-prompt` + tokenize; expect several thousand tokens) | truncating the schema out of the prompt defeats the training |
67
+ | batch | effective 16 via gradient accumulation | |
68
+ | completion-only loss | yes | mask the prompt; learn the emission, not the manifest |
69
+
70
+ If you exported DPO pairs, run a short DPO pass after SFT (beta 0.1, 1 epoch). Whether SFT-with-error-context or DPO helps more is an open question RFC-0666 expects this first run to answer; record what you find.
71
+
72
+ ## 4. Evaluate honestly
73
+
74
+ Serve the tune, then score it with the same harness that scores any other model:
75
+
76
+ ```bash
77
+ ollama create urml-3b -f Modelfile # or llama-server with the GGUF export
78
+ urml-model eval --utterances-root conformance/llm-bridge/fixtures \
79
+ --profile home --backend ollama --model urml-3b \
80
+ --out conformance/llm-bridge/results/<date>/home-urml-3b.yaml
81
+ ```
82
+
83
+ Score the untuned base model the same way first. The claim worth making is the delta: base vs tuned on `structural_pass_rate`, `semantic_pass_rate`, `revision_attempts_mean`. Numbers enter `docs/launch/claims-audit.md` only through the `make audit` transcription discipline, and only after they were actually measured.
84
+
85
+ ## 5. Deployment pairing
86
+
87
+ Pair the tuned model with GBNF grammar-constrained decoding (`urml_llm_bridge.grammar`, the `llama_cpp` provider) in production: the grammar guarantees structural validity at decode time, the tune carries the semantic load, and the validator remains the gate either way. The bridge's validate-and-revise loop stays on; a good tune makes it cheap, not optional.
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "urml-model"
7
+ version = "0.5.0"
8
+ description = "Dataset synthesis pipeline and training recipe for a URML-native small model (RFC-0666)."
9
+ readme = "README.md"
10
+ license = { text = "BUSL-1.1" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "URML Maintainers" }]
13
+ keywords = ["robotics", "urml", "llm", "dataset", "fine-tuning"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: Other/Proprietary License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ ]
24
+ dependencies = [
25
+ "pydantic>=2.6,<3",
26
+ "PyYAML>=6.0,<7",
27
+ "urml-validator>=0.5.0",
28
+ "urml-llm-bridge>=0.5.0",
29
+ "urml-conformance>=0.5.0",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ dev = [
34
+ "pytest>=8",
35
+ "pytest-cov>=5",
36
+ "ruff>=0.5",
37
+ "mypy>=1.10",
38
+ "types-PyYAML>=6.0",
39
+ ]
40
+
41
+ [project.scripts]
42
+ urml-model = "urml_model.cli:main"
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/urml-dev/URML"
46
+ Repository = "https://github.com/urml-dev/URML"
47
+ Issues = "https://github.com/urml-dev/URML/issues"
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/urml_model"]
51
+
52
+ [tool.ruff]
53
+ line-length = 120
54
+ target-version = "py311"
55
+ src = ["src", "tests"]
56
+
57
+ [tool.ruff.lint]
58
+ select = ["E", "F", "W", "I", "B", "UP", "N", "ANN", "RUF"]
59
+ ignore = ["ANN401"]
60
+
61
+ [tool.ruff.lint.per-file-ignores]
62
+ "tests/*" = ["ANN"]
63
+
64
+ [tool.mypy]
65
+ strict = true
66
+ python_version = "3.11"
67
+ plugins = ["pydantic.mypy"]
68
+ mypy_path = "src"
69
+ packages = ["urml_model"]
70
+
71
+ [tool.pytest.ini_options]
72
+ testpaths = ["tests"]
@@ -0,0 +1,51 @@
1
+ """urml-model — dataset synthesis pipeline for a URML-native small model (RFC-0666).
2
+
3
+ The validator is the labeling oracle: every (natural language, program,
4
+ manifest) triple in a dataset produced here passed `urml_validator.validate`
5
+ at synthesis time, and every rejected bridge emission becomes a repair
6
+ example carrying the validator's machine-readable error codes.
7
+
8
+ This package never trains a model, never downloads weights, and never
9
+ calls a specific LLM vendor. It mines the repository's gold assets,
10
+ back-translates programs into utterances (deterministic templates in CI,
11
+ any `LLMProvider` at scale), filters through the oracle, and exports the
12
+ formats fine-tuning frameworks consume. The training itself is
13
+ operator-action, documented in ``docs/training-recipe.md``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from urml_model.backtranslate import BackTranslator, LLMBackTranslator, TemplateBackTranslator
19
+ from urml_model.dataset import Dataset, DatasetRecord, Provenance, ValidatorVerdict
20
+ from urml_model.export import export_dpo, export_sft
21
+ from urml_model.mining import (
22
+ GoldExample,
23
+ mine_few_shot_pairs,
24
+ mine_fixture_programs,
25
+ resolve_envelope_ref,
26
+ resolve_manifest_ref,
27
+ )
28
+ from urml_model.rejections import RejectionSession, mine_rejections, session_from_result
29
+ from urml_model.synthesize import SynthesisReport, synthesize
30
+
31
+ __all__ = [
32
+ "BackTranslator",
33
+ "Dataset",
34
+ "DatasetRecord",
35
+ "GoldExample",
36
+ "LLMBackTranslator",
37
+ "Provenance",
38
+ "RejectionSession",
39
+ "SynthesisReport",
40
+ "TemplateBackTranslator",
41
+ "ValidatorVerdict",
42
+ "export_dpo",
43
+ "export_sft",
44
+ "mine_few_shot_pairs",
45
+ "mine_fixture_programs",
46
+ "mine_rejections",
47
+ "resolve_envelope_ref",
48
+ "resolve_manifest_ref",
49
+ "session_from_result",
50
+ "synthesize",
51
+ ]
@@ -0,0 +1,216 @@
1
+ """Back-translation: produce a natural-language utterance from a gold program (RFC-0666).
2
+
3
+ Fixture programs have no paired utterance. `BackTranslator` is the seam:
4
+
5
+ - `TemplateBackTranslator` renders deterministic English from the program's
6
+ steps. Hermetic, runs in CI, stylistically narrow by design. It exists so
7
+ the pipeline is testable end to end without a network and so the dataset
8
+ floor never depends on an external model.
9
+ - `LLMBackTranslator` asks any `LLMProvider` for paraphrases of the intent
10
+ a program encodes. This is where dataset diversity comes from; running it
11
+ at scale is operator-action. The provider protocol keeps it vendor-neutral.
12
+
13
+ Every candidate utterance goes through the validator oracle downstream
14
+ regardless of which translator produced it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from typing import Any, Protocol, runtime_checkable
21
+
22
+ from urml_llm_bridge.providers.base import LLMProvider
23
+
24
+
25
+ @runtime_checkable
26
+ class BackTranslator(Protocol):
27
+ """Anything that can phrase a URML program as the instruction that produces it."""
28
+
29
+ def to_utterances(
30
+ self,
31
+ program: dict[str, Any],
32
+ manifest: dict[str, Any],
33
+ *,
34
+ language: str = "en",
35
+ n: int = 1,
36
+ ) -> list[str]:
37
+ """Return up to `n` natural-language utterances for `program`."""
38
+ ...
39
+
40
+
41
+ def _fmt_value(value: Any) -> str:
42
+ if isinstance(value, str):
43
+ return value.replace("_", " ")
44
+ return str(value)
45
+
46
+
47
+ def _render_step(step: dict[str, Any]) -> str | None:
48
+ """One clause of imperative English for one primitive step.
49
+
50
+ Unknown primitives return None and are skipped by the caller; the
51
+ template path renders what it knows and never invents phrasing for a
52
+ primitive it has no template for.
53
+ """
54
+ if len(step) != 1:
55
+ return None
56
+ name, args = next(iter(step.items()))
57
+ if not isinstance(args, dict):
58
+ return None
59
+ match name:
60
+ case "move_to":
61
+ return f"go to {_fmt_value(args.get('location', 'the target'))}"
62
+ case "detect":
63
+ obj = _fmt_value(args.get("object", "the object"))
64
+ attrs = args.get("attributes")
65
+ if isinstance(attrs, dict) and "color" in attrs:
66
+ return f"find a {_fmt_value(attrs['color'])} {obj}"
67
+ return f"find a {obj}"
68
+ case "grasp":
69
+ return "pick it up"
70
+ case "release":
71
+ if args.get("mode") == "hand_to_user":
72
+ return "hand it to me"
73
+ return f"put it down at {_fmt_value(args['at'])}" if "at" in args else "put it down"
74
+ case "take_off":
75
+ alt = args.get("altitude")
76
+ return f"take off to {alt} meters" if alt is not None else "take off"
77
+ case "land":
78
+ return "land"
79
+ case "return_to_home":
80
+ return "return home"
81
+ case "hover":
82
+ over = args.get("over")
83
+ return f"hover over {_fmt_value(over)}" if over else "hover in place"
84
+ case "capture":
85
+ return f"take a {_fmt_value(args.get('media', 'photo'))}"
86
+ case "scan":
87
+ return "scan the area"
88
+ case "measure":
89
+ return f"measure the {_fmt_value(args.get('what', 'reading'))}"
90
+ case "report":
91
+ return "tell me the result" if args.get("to") == "user" else "report the result"
92
+ case "wait_for":
93
+ condition = args.get("condition")
94
+ if isinstance(condition, dict) and "event" in condition:
95
+ return f"wait for {_fmt_value(condition['event'])}"
96
+ return "wait for the condition"
97
+ case "wait_passively":
98
+ duration = args.get("duration")
99
+ return f"wait {_fmt_value(duration)}" if duration else "wait"
100
+ case "dock":
101
+ return f"dock at {_fmt_value(args.get('at', 'the dock'))}"
102
+ case "call_program":
103
+ return f"run the {_fmt_value(args.get('name', 'named'))} program"
104
+ case "speak":
105
+ return f"say {args.get('text', 'something')!r}"
106
+ case "listen":
107
+ return "listen for my reply"
108
+ case "drive":
109
+ if "radius" in args and "arc" in args:
110
+ return f"orbit {args['arc']} degrees with a {args['radius']} meter radius"
111
+ if "arc" in args:
112
+ return f"curve {args['arc']} degrees over {args.get('distance', 0)} meters"
113
+ return f"drive {args.get('distance', 0)} meters"
114
+ case "turn":
115
+ angle = args.get("angle", 0)
116
+ side = "left" if isinstance(angle, (int, float)) and angle >= 0 else "right"
117
+ return f"turn {side} {abs(angle) if isinstance(angle, (int, float)) else angle} degrees"
118
+ case "pick_from":
119
+ return f"pick a {_fmt_value(args.get('object', 'part'))} from {_fmt_value(args.get('source', 'the bin'))}"
120
+ case "place_at":
121
+ return f"place it at {_fmt_value(args.get('destination', 'the target'))}"
122
+ case "swap_tool":
123
+ return f"swap to the {_fmt_value(args.get('tool', 'next'))} tool"
124
+ case "set_output":
125
+ return f"set output {_fmt_value(args.get('line', ''))}".strip()
126
+ case "follow_trajectory" | "plan_trajectory":
127
+ return "follow the planned route"
128
+ case _:
129
+ return None
130
+
131
+
132
+ def _collect_clauses(node: Any) -> list[str]:
133
+ """Walk a behavior tree and collect renderable clauses in order."""
134
+ clauses: list[str] = []
135
+ if isinstance(node, dict):
136
+ steps = node.get("steps")
137
+ branches = node.get("branches")
138
+ body = node.get("body")
139
+ if isinstance(steps, list):
140
+ for step in steps:
141
+ clauses.extend(_collect_clauses(step))
142
+ elif isinstance(branches, list):
143
+ for branch in branches:
144
+ clauses.extend(_collect_clauses(branch))
145
+ elif isinstance(body, dict):
146
+ clauses.extend(_collect_clauses(body))
147
+ else:
148
+ rendered = _render_step(node)
149
+ if rendered is not None:
150
+ clauses.append(rendered)
151
+ return clauses
152
+
153
+
154
+ class TemplateBackTranslator:
155
+ """Deterministic English rendering of a program's step sequence.
156
+
157
+ English only; other languages take the LLM path (RFC-0666 Unresolved
158
+ questions). Returns at most one utterance regardless of `n`, because a
159
+ template has exactly one way to say a thing.
160
+ """
161
+
162
+ def to_utterances(
163
+ self,
164
+ program: dict[str, Any],
165
+ manifest: dict[str, Any],
166
+ *,
167
+ language: str = "en",
168
+ n: int = 1,
169
+ ) -> list[str]:
170
+ if language != "en":
171
+ return []
172
+ clauses = _collect_clauses(program.get("behavior", {}))
173
+ if not clauses:
174
+ return []
175
+ if len(clauses) == 1:
176
+ sentence = clauses[0]
177
+ else:
178
+ sentence = ", ".join(clauses[:-1]) + f", then {clauses[-1]}"
179
+ return [sentence[0].upper() + sentence[1:] + "."]
180
+
181
+
182
+ _BACKTRANSLATE_SYSTEM = """\
183
+ You reverse-translate robot programs into the instruction a person would have
184
+ given to produce them. You will receive a URML program (JSON). Reply with a
185
+ JSON array of {n} distinct natural-language instructions in {language}, each a
186
+ single sentence a non-programmer might say, each fully implied by the program:
187
+ no added goals, no dropped steps. Reply with the JSON array only."""
188
+
189
+
190
+ class LLMBackTranslator:
191
+ """Paraphrase-diverse back-translation through any `LLMProvider`."""
192
+
193
+ def __init__(self, provider: LLMProvider) -> None:
194
+ self._provider = provider
195
+
196
+ def to_utterances(
197
+ self,
198
+ program: dict[str, Any],
199
+ manifest: dict[str, Any],
200
+ *,
201
+ language: str = "en",
202
+ n: int = 1,
203
+ ) -> list[str]:
204
+ system = _BACKTRANSLATE_SYSTEM.format(n=n, language=language)
205
+ raw = self._provider.complete(
206
+ system=system,
207
+ user=json.dumps(program, sort_keys=True),
208
+ schema={"type": "array", "items": {"type": "string"}},
209
+ )
210
+ try:
211
+ parsed = json.loads(raw)
212
+ except json.JSONDecodeError:
213
+ return []
214
+ if not isinstance(parsed, list):
215
+ return []
216
+ return [item.strip() for item in parsed if isinstance(item, str) and item.strip()][:n]