Metadata-Version: 2.5
Name: llmroute-ai
Version: 0.1.0
Summary: Evidence-based LLM routing engine powered by LiteLLM with capability verification, cost/latency policy ranking, and explainable traces.
Project-URL: Homepage, https://github.com/jeromeprince777/llmroute
Project-URL: Repository, https://github.com/jeromeprince777/llmroute
Project-URL: Issues, https://github.com/jeromeprince777/llmroute/issues
Author: Jerome Prince
License: MIT
License-File: LICENSE
Keywords: ai-infrastructure,benchmarking,fastapi,litellm,llm,routing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.12
Requires-Dist: alembic<2.0.0,>=1.14.0
Requires-Dist: fastapi<1.0.0,>=0.115.0
Requires-Dist: httpx<1.0.0,>=0.27.0
Requires-Dist: jsonschema<5.0.0,>=4.23.0
Requires-Dist: litellm<2.0.0,>=1.60.0
Requires-Dist: opentelemetry-api<2.0.0,>=1.29.0
Requires-Dist: opentelemetry-sdk<2.0.0,>=1.29.0
Requires-Dist: pydantic-settings<3.0.0,>=2.7.0
Requires-Dist: pydantic<3.0.0,>=2.10.0
Requires-Dist: pyyaml<7.0.0,>=6.0.2
Requires-Dist: rich<16.0.0,>=13.9.0
Requires-Dist: sqlalchemy<3.0.0,>=2.0.36
Requires-Dist: typer<1.0.0,>=0.15.0
Requires-Dist: uvicorn<1.0.0,>=0.34.0
Description-Content-Type: text/markdown

# LLMRoute

**Evidence-based LLM routing engine powered by LiteLLM.**

LLMRoute selects models using application-specific benchmarks, empirically verified capabilities, estimated inference cost, latency, and reliability—explaining *why* a model was selected, *why* alternatives were rejected, and *which* benchmark evidence supports the decision.

## Problem Statement

Teams integrating multiple LLM providers run into recurring reliability and cost problems:
- Provider APIs and capability behavior vary inconsistently across vendors and model versions.
- Provider marketing claims (such as JSON Schema compliance or tool calling) do not always hold up on application payloads.
- Expensive frontier models are frequently used for structured tasks that cheaper or local models handle reliably.
- Upstream model updates can introduce silent capability or latency regressions.
- Generic proxy routers make selection difficult to inspect and can silently fall back to models that lack mandatory request capabilities.

## Project Differentiation

LLMRoute is **not** a generic LiteLLM Proxy clone or a black-box preference router like LMSYS RouteLLM.

| System | Primary Mechanism | LLMRoute Differentiation |
|---|---|---|
| **LiteLLM Proxy** | Multi-provider API translation, load balancing, static fallbacks | LLMRoute uses LiteLLM as its execution adapter while owning empirical capability verification, strict 2-stage policy filtering, and per-candidate explanation traces. |
| **LMSYS RouteLLM** | Learned classifiers on Chatbot Arena preference pairs | LLMRoute uses deterministic, inspectable policies and application-specific probes (JSON Schema, tool arguments, budgets) rather than black-box chat preference scores. |
| **Gateway / Semantic Routers** | Static traffic splits or embedding intent routing | LLMRoute verifies actual model capabilities before routing and preserves all mandatory constraints during fallback. |

See [ADR-001](docs/decisions/ADR-001-differentiation-and-architecture.md) for the full comparative analysis.

## Architecture

```mermaid
flowchart LR
    Req["Request + Policy"] --> S1["Stage 1: Capability, Context & Budget Filter"]
    S1 --> S2["Stage 2: Quality, Reliability & Freshness Filter"]
    S2 --> S3["Stage 3: Deterministic Ranking & Trace"]
    S3 --> S4["Stage 4: LiteLLM / Mock Execution"]
    S4 -- "Failure" --> S5["Stage 5: Capability-Aware Fallback"]
    S5 --> S4
```

## Installation & Quick Start

Requires Python 3.12+.

```bash
# Development setup with uv
uv sync --locked
uv run llmroute --version
uv run llmroute demo
```

Or install from PyPI / a built wheel in a clean environment:

```bash
pip install llmroute-ai
# Or from local wheel:
pip install dist/llmroute_ai-0.1.0-py3-none-any.whl
llmroute --version
llmroute demo
```

## Offline Demo

Run a complete deterministic routing, fallback, and baseline comparison demo without any API keys or external network calls:

```text
$ llmroute demo
┌───────────────────────── [SIMULATED OFFLINE DEMO] ──────────────────────────┐
│ All inference and benchmark metrics below use deterministic                 │
│ MockProviderAdapter fixtures.                                               │
│ Simulated results do NOT represent live commercial LLM performance.         │
└─────────────────────────────────────────────────────────────────────────────┘
Stage 1-3 Winner: mock-fast-json
Explanation: Selected 'mock-fast-json' (mock/gpt-4o-mini); under policy
'structured_extraction' (strategy=balanced, score=0.6000);
estimated_cost=$0.000192; quality=0.950 (suite=structured_extraction);
median_latency=95.0ms; reliability=0.995 (n=25); out of 2 eligible and 2
rejected candidate(s). Note: benchmark scores reflect recorded suite
evaluations, not guaranteed correctness on unseen prompts.
                              Rejected Candidates
┌───────────────────┬───────────────────┬─────────────────────────────────────┐
│ Deployment ID     │ Stage             │ Reason                              │
├───────────────────┼───────────────────┼─────────────────────────────────────┤
│ openai-unverified │ stage_1_candidate │ missing_capability: Missing         │
│                   │                   │ required verified capabilities:     │
│                   │                   │ structured_output, json_schema.     │
│ mock-no-schema    │ stage_1_candidate │ missing_capability: Missing         │
│                   │                   │ required verified capabilities:     │
│                   │                   │ json_schema.                        │
└───────────────────┴───────────────────┴─────────────────────────────────────┘
Stage 5 Fallback Recovery: attempted ['mock-fast-json', 'mock-premium-json'] ->
succeeded on mock-premium-json with output {"invoice_id": "INV-402",
"total_usd": 199.5}
```

## Supported Providers

- **Cloud & Hosted Providers (via LiteLLM)**: OpenAI, Anthropic, Google Gemini, Azure OpenAI, and other LiteLLM-supported backends configured by environment variable name (`api_key_env`).
- **Local Models (Ollama)**: Configured with `provider: ollama` and `api_base_env: OLLAMA_API_BASE`.
- **Offline Mock Adapter (`MockProviderAdapter`)**: Deterministic scenario adapter used by `llmroute demo`, CI, and offline contract tests.

## Model Registry Example

```yaml
models:
  - model_id: gpt-4o-mini
    provider: mock
    deployment_id: mock-fast-json
    api_key_env: null
    context_window: 128000
    max_output_tokens: 16384
    pricing:
      input_per_1m_tokens_usd: 0.15
      output_per_1m_tokens_usd: 0.60
    declared_capabilities:
      structured_output: true
      json_schema: true
    verified_capabilities:
      structured_output: true
      json_schema: true
    benchmark_scores:
      structured_extraction: 0.94
    latency_stats:
      median_ms: 420.0
      p95_ms: 780.0
    reliability_stats:
      success_rate: 0.995
      sample_size: 25
    last_verified_at: "2026-12-01T00:00:00Z"
    enabled: true
```

See [config.example.yaml](config.example.yaml) for a multi-provider configuration with cloud and local Ollama examples.

## Routing Policy Example

```yaml
policies:
  structured_extraction:
    required_capabilities:
      - structured_output
      - json_schema
    minimum_quality: 0.90
    estimated_request_budget_usd: 0.02
    benchmark_max_age_hours: 168
    minimum_benchmark_samples: 10
    strategy: balanced
    weights:
      quality: 0.40
      cost: 0.30
      latency: 0.20
      reliability: 0.10
    max_attempts: 3
    timeout_seconds: 30
    allow_unverified_models: false
```

## Benchmark Methodology & Simulated Baseline Results

LLMRoute evaluates models with deterministic validators (JSON parsing, `jsonschema` validation, tool-call argument schemas, instruction constraints, normalized math, and labeled classification) without executing model-generated code. Results are labeled `simulated`, `estimated`, or `live`.

Observed **simulated** comparison from `llmroute demo` (`structured-output v1.0.0`, `MockProviderAdapter` fixtures):

| Strategy | Success Rate | JSON Validity | Est. Cost (USD) | Median Latency (ms) | Violations |
|---|---:|---:|---:|---:|---:|
| `cheapest_eligible` | 100.0% | 100.0% | $0.000135 | 95.0 | 0 |
| `highest_scoring_eligible` | 100.0% | 100.0% | $0.002250 | 340.0 | 0 |
| `fastest_eligible` | 100.0% | 100.0% | $0.000135 | 95.0 | 0 |
| `llmroute_balanced` | 100.0% | 100.0% | $0.000135 | 95.0 | 0 |

*(Note: Measured on synthetic mock fixtures to verify deterministic policy behavior; live model performance depends on target provider deployments and benchmark suites.)*

## API Examples

Start the local server (binds to `127.0.0.1:8000` by default):

```bash
uv run llmroute serve
```

Preview a route and inspect its trace:

```bash
curl -s -X POST http://127.0.0.1:8000/v1/route \
  -H "Content-Type: application/json" \
  -d '{"policy": "structured_extraction"}'

curl -s -X POST http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "policy:structured_extraction",
    "messages": [{"role": "user", "content": "Extract invoice INV-402"}],
    "response_format": {"type": "json_object"}
  }'
```

See [docs/api.md](docs/api.md) for all endpoints and supported vs. rejected OpenAI parameters.

## Security Model

- **Credential Isolation**: API keys are referenced strictly by environment variable name (`api_key_env`) and rejected if literal secret prefixes are supplied.
- **Redaction & Privacy**: Authorization headers and secret patterns are redacted in errors/logs; raw prompts and responses are omitted from logs and SQLite traces by default.
- **SSRF & Input Guards**: Client-supplied `api_base`/`base_url` parameters and link-local/metadata hosts (`169.254.*`, `metadata.google.internal`) are blocked; payloads exceeding `LLMROUTE_MAX_REQUEST_BYTES` return HTTP `413`.
- **Paid Run Guard**: Live/billable benchmarks require explicit authorization flags (`--authorize-live`, `--authorize-paid`).
- **Safe Server Defaults**: Server binds to `127.0.0.1` by default and supports optional `LLMROUTE_API_KEY` bearer authentication.

See [docs/security.md](docs/security.md) and [SECURITY.md](SECURITY.md).

## Known Limitations

- Streaming SSE responses (`stream=true`) and `n > 1` are unsupported in `v0.1.0` and rejected with HTTP `422`.
- Provider billing and ambiguous network failures prevent an absolute spending guarantee; request budgets act as deterministic pre-attempt caps.
- Docker container builds are validated in GitHub Actions (`ubuntu-latest`); local Docker runtime testing requires Docker installed on the host.

## Roadmap

- **v0.1.0 (Completed P0 + Core P1)**: Model registry, LiteLLM & mock adapters, deterministic capability benchmarks, SQLite + Alembic storage, 5-stage filtering/ranking/fallback, FastAPI gateway & OpenAI subset, Typer CLI & offline demo, regression detection & baselines, OpenTelemetry & redacted logging, Docker packaging.
- **P2 (Future)**: Web dashboard, Redis distributed routing state, Prometheus/Grafana templates, adaptive production feedback routing, SSE streaming, MCP server, custom benchmark plugins, multi-tenant gateway.

## Contributing & License

Contributions are welcome—see [CONTRIBUTING.md](CONTRIBUTING.md). Licensed under the [MIT License](LICENSE).
