Metadata-Version: 2.5
Name: urml-llm-bridge
Version: 0.5.4
Summary: Provider-agnostic glue between natural language and validated URML programs.
Project-URL: Homepage, https://github.com/urml-dev/URML
Project-URL: Repository, https://github.com/urml-dev/URML
Project-URL: Issues, https://github.com/urml-dev/URML/issues
Author: URML Maintainers
License: BUSL-1.1
License-File: LICENSE
Keywords: llm,robotics,specification,urml
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Requires-Dist: pydantic<3,>=2.6
Requires-Dist: pyyaml<7,>=6.0
Requires-Dist: urml-validator>=0.5.4
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.34; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: anthropic>=0.34; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: openai>=1.40; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: llama-cpp
Requires-Dist: httpx>=0.27; extra == 'llama-cpp'
Provides-Extra: ollama
Requires-Dist: httpx>=0.27; extra == 'ollama'
Provides-Extra: openai
Requires-Dist: openai>=1.40; extra == 'openai'
Provides-Extra: whisper-cpp
Requires-Dist: httpx>=0.27; extra == 'whisper-cpp'
Description-Content-Type: text/markdown

<p align="center">
  <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
</p>

<p align="center">
  A small, opinionated, human-readable language for describing robot intent.
</p>

<p align="center">
  <a href="https://urml.dev"><b>urml.dev</b></a>
</p>

---

# LLM Bridge

**Status:** alpha, on PyPI as `urml-llm-bridge`. Versions are `0.x`, so a release may break compatibility; the [changelog](https://github.com/urml-dev/URML/blob/main/CHANGELOG.md) says what each one changed. Shipped: the provider-agnostic `Bridge` + bounded validator-feedback revision loop, five providers (Anthropic, OpenAI, Ollama, llama.cpp, all lazy-imported, plus the hermetic `EchoProvider`), schema-derived GBNF grammar for llama.cpp (RFC-0021), a speech front-end (RFC-0670), and profile-scoped few-shot libraries (home / industrial / drone / educational / fleet). The `urml translate`, `urml run`, `urml emit-prompt` and `urml bench` commands use it; the `urml` CLI itself comes with `urml-validator`, which this package depends on. The normative contract is [`spec/layer-4-nl-grammar/`](https://github.com/urml-dev/URML/tree/main/spec/layer-4-nl-grammar); a hermetic end-to-end walkthrough is [`docs/demos/bridge-roundtrip.md`](https://github.com/urml-dev/URML/blob/main/docs/demos/bridge-roundtrip.md).

## What this is

The **provider-agnostic glue** between natural-language input and a validated URML program. The LLM bridge:

1. Takes a natural-language request from a user (or another system).
2. Prompts a configured LLM with the [Layer-4 prompt contract](https://github.com/urml-dev/URML/tree/main/spec/layer-4-nl-grammar), the connected robot's [Layer-1 capability manifest](https://github.com/urml-dev/URML/tree/main/spec/layer-1-hal), and the active safety envelope.
3. Receives the LLM's emission (a URML program).
4. Calls the [validator](https://github.com/urml-dev/URML/tree/main/reference/validator) to statically verify the emission.
5. On rejection, surfaces the structured error back to the LLM and requests a revision. Repeats up to a configured bound.
6. On acceptance, returns the validated program. The caller hands it to a runtime; the bridge executes nothing.
7. When the request needs a capability the manifest does not declare, the model emits a `report(status: failure)` naming what is missing rather than fabricating capability. (The normative contract has no clarifying-question turn: see [`spec/layer-4-nl-grammar/v0.2.0.md`](https://github.com/urml-dev/URML/blob/main/spec/layer-4-nl-grammar/v0.2.0.md) §5. An experimental clarify mode, off by default, lets the model ask a clarifying question (one, unless you raise the budget) before it commits: `Bridge(clarify=True)`, or `--clarify` on `urml translate` and `urml run`.)

## Benchmarking a model

`urml bench` measures how well any configured model speaks URML: it runs a
corpus of natural-language requests through the same translate loop and
reports how many landed as accepted programs, honest refusals, or invalid
emissions, plus a match rate against per-utterance expectations. Corpora,
methodology, and the honesty rules for quoting numbers live in
[`bench/`](https://github.com/urml-dev/URML/tree/main/bench) at the repository root. It is a benchmark, not a
conformance test.

## Provider neutrality is non-negotiable

URML's value as a standard depends on Layer 4 being **provider-neutral**. The LLM bridge must support, as first-class citizens:

- **Anthropic** (Claude family).
- **OpenAI** (GPT family).
- **Open-weights models** (Llama, Mistral, Qwen, and their successors), via local serving (vLLM, llama.cpp, Ollama) or hosted inference providers.
- **On-device models** for offline-capable deployments.

Adding a new provider must be a small adapter in `providers/`, not a structural change to the bridge. If a provider's particular feature would let URML produce better URML, the bridge surfaces the feature behind a profile-neutral abstraction, never by privileging that provider.

Vendor lock-in here is explicitly prohibited by [`CLAUDE.md`](https://github.com/urml-dev/URML/blob/main/CLAUDE.md) §What Claude Should Never Do.

## What the bridge does NOT do

- It does **not** include or embed any specific LLM provider's API client as a hard dependency. Provider clients are optional and pluggable.
- It does **not** require cloud connectivity. A deployment using a local open-weights model runs offline end to end.
- It does **not** persist user inputs, model outputs, or any other data without explicit, opt-in, documented purpose. Trust is the most valuable asset of this project; the bridge will not be the place it leaks.
- It does **not** execute URML. That is the runtime's job.
- It does **not** make safety decisions. The validator is the safety boundary; the bridge only relays.

## Architecture

```
                ┌────────────────────────┐
   user / NL    │   LLM Bridge           │   validated URML
   ─────────────▶  • build prompt        ├──────────────────▶  runtime
                │  • call provider       │
                │  • validate emission   │
                │  • revise loop         │
                └──┬──────────────────▲──┘
                   │                  │
                   ▼                  │
              providers/           validator
              (anthropic.py,       (in-process
               openai.py,           call)
               ollama.py,
               llama_cpp.py,
               echo.py)
```

The bridge is small. The intelligence lives in the LLM (which is configured, not built here) and in the validator, which the bridge imports and calls in-process on every emission. The bridge orchestrates.

## Language

- **Python**. `mypy --strict`. Public API fully type-annotated.

## API

```python
from urml_llm_bridge import Bridge, BridgeRevisionExhausted

bridge = Bridge(
    provider=provider,             # an LLMProvider instance; see "Using a real provider"
    manifest=manifest,             # the robot's capability manifest, parsed YAML
    envelope=envelope,             # the safety envelope, parsed YAML (optional)
    profiles=("home",),
    max_revisions=3,
)

try:
    result = bridge.translate("Bring me the red mug from the kitchen.")
except BridgeRevisionExhausted as exc:
    # The validator rejected every attempt. The last verdict is attached.
    for err in exc.last_result.errors:
        print(err.render())
else:
    runtime.execute(result.program, manifest, envelope)
```

`translate()` returns only an accepted program. Every other outcome raises a `BridgeError`: `BridgeRevisionExhausted` when the revision bound is reached, `BridgePolicyViolation` when only compliance-policy errors remain (a revision cannot change hardware), `BridgeDeploymentViolation` for a rulebook error only the deployment can fix, `BridgeClarificationNeeded` in clarify mode with no answer channel, and `ProviderError` when the model call fails or returns no JSON.

## Conformance contract

The bridge has no pass/fail conformance bar and declares no success rate. [`conformance/llm-bridge/`](https://github.com/urml-dev/URML/tree/main/conformance/llm-bridge) is a scoring sub-suite (RFC-0021): it runs a profile's utterance set through the bridge with one model and one backend, and records how many emissions were structurally valid and how many the validator accepted. The one committed result row comes from the hermetic echo backend, so it exercises the harness and measures no model.

## License

The LLM bridge (the *bridge logic and the prompt contract*, not any specific provider's API) is licensed under the Business Source License 1.1: free for non-production use, commercial license for production (see [`LICENSING.md`](https://github.com/urml-dev/URML/blob/main/LICENSING.md)). It stays provider-agnostic.

## Quickstart (hermetic, no provider needed)

From PyPI (this also installs `urml-validator`):

```bash
python -m venv .venv && . .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install urml-llm-bridge
```

From a checkout of the repository, to run the tests:

```bash
cd reference/llm-bridge
python -m venv .venv && . .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e ../validator           # bridge depends on validator
pip install -e ".[dev]"
pytest
```

Use it in code with the bundled `EchoProvider` (for tests / hermetic CI):

```python
import json
from urml_llm_bridge import Bridge, EchoProvider

red_mug_program = {  # the URML the LLM is expected to emit
    "profile": "home",
    "behavior": {"type": "sequence", "steps": [...]},
}

provider = EchoProvider(scripted=[json.dumps(red_mug_program)])
bridge = Bridge(provider=provider, manifest=manifest, envelope=envelope, profiles=("home",))
result = bridge.translate("Bring me the red mug from the kitchen.")

runtime.execute(result.program, manifest, envelope)   # translate() returned, so the program was accepted
```

The revision loop runs automatically when the validator rejects the LLM's emission: the bridge feeds the structured errors back to the LLM and asks for a corrected version, up to `max_revisions` times (default 3).

### Using a real provider

Install the extra for the provider you want. The bridge package itself has no SDK dependencies:

```bash
pip install urml-llm-bridge[anthropic]    # adds the `anthropic` SDK
pip install urml-llm-bridge[openai]       # adds the `openai` SDK
pip install urml-llm-bridge[ollama]       # adds httpx; talks to a local `ollama serve`
pip install urml-llm-bridge[llama_cpp]    # adds httpx; talks to a local `llama-server`
```

Then:

```python
from urml_llm_bridge import Bridge
from urml_llm_bridge.providers.anthropic import AnthropicProvider

provider = AnthropicProvider(model="claude-sonnet-4-6")  # reads ANTHROPIC_API_KEY env var
bridge = Bridge(provider=provider, manifest=manifest, envelope=envelope, profiles=("home",))
result = bridge.translate("Bring me the red mug from the kitchen.")
```

Or OpenAI:

```python
from urml_llm_bridge.providers.openai import OpenAIProvider

provider = OpenAIProvider(model="gpt-4o")  # reads OPENAI_API_KEY env var
```

Or a local model, fully offline (RFC-0021):

```python
from urml_llm_bridge.providers.ollama import OllamaProvider
from urml_llm_bridge.providers.llama_cpp import LlamaCppProvider

provider = OllamaProvider(model="llama3.2:1b")   # talks to ollama serve at 127.0.0.1:11434
provider = LlamaCppProvider()                    # talks to llama-server at 127.0.0.1:8080
```

Every adapter surfaces its native structured-output mechanism: Anthropic via tool use (with the URML schema as the `emit_urml` tool's `input_schema`), OpenAI via `response_format={"type": "json_object"}` with the schema conveyed in the system prompt, Ollama via the schema as the `format` constraint, and llama.cpp via a GBNF grammar derived from the schema (structurally invalid output is unrepresentable at the decoder). In all cases, conformance to the schema is validated downstream by `urml_validator.validate()` as part of the bridge's revision loop.

From the CLI, the same providers are one flag away: `urml translate ... --provider ollama --model llama3.2:1b`, `--provider llama_cpp`, or `--provider openai --base-url http://host:port/v1` for any OpenAI-compatible server (LM Studio, vLLM). `--timeout SECONDS` sets how long to wait for a slow local model (default 120 for `ollama` and `llama_cpp`).

### Speech input (RFC-0670)

The bridge also ships a speech front-end: a `SpeechProvider` protocol (`transcribe(audio, filename, language) -> str`) with adapters for whisper.cpp's `whisper-server` (`[whisper_cpp]` extra, on-device, the default), OpenAI-shaped transcription endpoints (`[openai]` extra, `base_url` for self-hosted servers), and a hermetic `EchoSpeechProvider`. The transcript feeds the same `Bridge.translate()` path a typed request does, so the validator boundary is untouched. From the CLI: `urml translate --audio request.wav ...` (and the same on `urml run`).

## What's not here

- **Multilingual few-shot variants** (Hebrew, Spanish, Japanese, Mandarin).
- **Conversation memory** for follow-up requests within a session.
- **OpenAI strict JSON-schema mode** needs schema preprocessing to satisfy the strict-mode constraints (every property required, no `oneOf`, etc.). The current adapter uses `json_object` mode plus the schema in the system prompt for portability.

## Related documents

- [`/spec/layer-4-nl-grammar/`](https://github.com/urml-dev/URML/tree/main/spec/layer-4-nl-grammar): the prompt contract this bridge implements.
- [`/reference/validator/`](https://github.com/urml-dev/URML/tree/main/reference/validator): the safety boundary this bridge feeds.
- [`/examples/`](https://github.com/urml-dev/URML/tree/main/examples): the paired natural-language / URML scenarios used as fixtures.
- [`CLAUDE.md`](https://github.com/urml-dev/URML/blob/main/CLAUDE.md) §What Claude Should Never Do: the provider-neutrality requirement, in writing.
