feat: provider-agnostic LLM gateway + curated profiles (Sprint 3, ADR-002)

- ADR-002 formalizuje BYOK + 5 curated profiles + Claude Code side-channel
- packages/llm-gateway: LLMGatewayConfig (pydantic-settings env-driven),
  profile-based routing (cloud-cheap/cloud-premium/local-data-sovereign/
  hybrid/custom), Ollama models (Bielik 11B, Llama 3.3 70B), mock provider
  deterministic stub, hybrid promotion logic, routing_decision w Langfuse
  trace metadata; GatewayRejected nadal provider-agnostic
- packages/evals: mock mode (CI bez ANTHROPIC_API_KEY), --profile flag
  w conftest, lazy import compass_agents
- .claude/skills/compass-legal-review: internal-use side-channel workflow
  (Claude Code reuses packages/* jako library, 12-pkt self-check)
- scripts/setup_local_llm.{sh,ps1}: Ollama+Bielik bootstrap (winget/curl)
- CLAUDE.md + .env.example: BYOK + 5 profiles + model routing matrix
  per profile + cross-references do ADR-002 + compass-legal-review skill

Tests: 17/17 llm-gateway config, 9/9 evals --profile=mock,
8/9 default (1 correct skip without ANTHROPIC_API_KEY).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
tobayah
2026-05-17 16:54:47 +02:00
co-authored by Claude Opus 4.7
parent 9c50931209
commit 944eed2106
16 changed files with 1525 additions and 80 deletions
@@ -0,0 +1,382 @@
---
name: compass-legal-review
description: Use when robisz internal-use contract review w Claude Code reusing Compass packages jako importowaną Python library (NIE production runtime) — workflow Tobiasza dla 1-5 kontraktów/tydzień własnej review bez deploymentu apps/api ani zewnętrznego API LLM. Side-channel z ADR-002 (Opcja A subset). Claude (model) jest LLM — Ty mentalnie aplikujesz SYSTEM_PROMPT z compass_prompts + few-shots jako structured guardrail, konstruujesz LiabilityClause(**output) z Pydantic validators (auto-disclaimer + unlimited→Needs Attention downgrade), runujesz post_extraction_check z compass_jurisdictions.pl.liability (KC art. 473 § 2 + 484 § 2), zapisujesz JSON + Markdown report + audit log. Identical schemas, different runtime — provider-agnostic gateway w apps/api dla produkcji, ta sama library w Claude Code dla solo founder phase. 6 fundamentów (decyzja side-channel vs apps/api, library imports + venv, mentalny LLM dispatch + Pydantic guardrail, jurisdiction post-check, output format JSON+MD+audit, hard guardrails AI legal disclaimer). Mandatory self-check 12 punktów. Synergizuje z [[compass-architecture]] (package boundaries — Ty reusujesz packages, nie modyfikujesz), [[compass-clause-taxonomy]] (14-clause taxonomy + Pydantic+zod sync — used as-is, NIE dodajesz typów tutaj), [[compass-ai-native-mandates]] (M2 schema-first + M8 observable applies nawet w internal — ślad JSON+MD jako observability surrogate), legal-tech (red flag library + GDPR/AI Act + jurisdiction rules), pisanie-pl (każdy PL fragment markdown report przez 10-pkt self-check). SKIP dla non-PL kontraktów dopóki Sprint 4 nie dorzuci EN/DE jurisdiction modules (use legal-tech baseline tymczasowo), kontraktów >50 stron (chunking required — czekaj na retrieval pipeline Sprint 4+), real-time customer-facing flows (use apps/api production runtime), modyfikacji schemas/prompts/jurisdictions (to NIE jest skill do edytowania packages — use compass-clause-taxonomy + compass-architecture).
---
Base directory for this skill: `compass-contract-hub/.claude/skills/compass-legal-review/`
# Compass — legal review (Claude Code internal-use)
Skill dla **internal-use side-channel** zdefiniowanego w ADR-002. Tobiasz reuse'uje `packages/schemas` + `packages/prompts` + `packages/jurisdictions` jako importowaną Python library w Claude Code, bez deploymentu `apps/api` i bez wywołania zewnętrznego LLM API. **Claude (model) jest LLM** — w tym workflow Ty (jako model) mentalnie aplikujesz SYSTEM_PROMPT, konstruujesz Pydantic objects, Pydantic validators wymuszają correctness, jurisdiction post-checks aplikują KC rules.
**To NIE jest production runtime.** Production = `apps/api` z provider-agnostic gateway (ADR-002 Decision section). Ten skill = dev/internal tool dla solo founder phase (1-5 kontraktów/tydzień).
## Kontekst — kiedy używasz tego workflow
- **Solo founder phase, brak klientów prod** — nie ma sensu deployować pełnego stacku tylko po to żeby self-review jeden umowę
- **Compass packages = SSOT** — Pydantic schemas + prompts + jurisdiction rules są pojedynczym źródłem prawdy, niezależnym od runtime
- **Brak API kosztów** — Tobiasz już ma Claude Code subscription; reuse zamiast osobnego ANTHROPIC_API_KEY billing
- **Identyczne guardrails** — Pydantic validators (auto-disclaimer, unlimited→Needs Attention downgrade) działają niezależnie czy LLM jest Claude API, Bielik local, czy Claude Code session
## Kiedy stosować
- **TAK:** "review contract X dla liability", "extract clauses z `inbox/<file>.pdf`", "check this PL umowa for missing carve-outs", solo founder personal review, dry-run nowego promptu przed eval, ad-hoc audit kontraktu klienta haski.io przed signing
- **NIE:** non-PL kontrakty (Sprint 4 doda EN/DE jurisdiction modules), kontrakty >50 stron (Claude context limit ~200k → potrzebujesz chunking → Sprint 4+ retrieval pipeline), real-time customer-facing flows (use `apps/api`), modyfikacje `packages/schemas` / `packages/prompts` / `packages/jurisdictions` (use [[compass-clause-taxonomy]] + [[compass-architecture]])
## 6 fundamentów
### 1. Decyzja: side-channel vs apps/api
Zanim odpalisz skill — zweryfikuj że side-channel jest właściwy:
| Sytuacja | Use |
|---|---|
| Tobiasz solo, 1-5 kontraktów/tydzień, własna review | **side-channel (ten skill)** |
| Klient w produkcji uploaduje umowę | `apps/api` POST `/contracts/{id}/extract` |
| Eval prompt change przed merge | `packages/evals/runner.py` (M4) |
| Adding new clause type | NIE tutaj — [[compass-clause-taxonomy]] workflow |
| Adding new jurisdiction | NIE tutaj — [[compass-architecture]] + [[compass-clause-taxonomy]] |
| Real-time SSE streaming do UI | `apps/api` (M3 + M7) |
Jeśli odpowiedź jest "klient w prod" / "real-time" / "modify packages" → STOP, użyj odpowiedniej ścieżki.
### 2. Library imports — Compass jako site-packages
Setup (one-time):
```powershell
# Z root repo
uv sync --all-packages
# Activate venv (Windows PowerShell)
. .venv\Scripts\Activate.ps1
```
Workflow imports (w Claude Code Python REPL lub script):
```python
# Schemas (Pydantic models)
from compass_schemas.clauses import LiabilityClause
from compass_schemas.clauses.base import ClauseBase # auto-disclaimer logic
# Prompts (versioned)
from compass_prompts import load_prompt
spec = load_prompt("liability_v1")
SYSTEM_PROMPT = spec["system_prompt"]
FEW_SHOTS = spec["few_shot_examples"]
VERSION = spec["version"] # "liability_v1"
# Jurisdiction overlay (PL only Sprint 2/3)
from compass_jurisdictions.pl.liability import (
post_extraction_check,
MANDATORY_OBSERVATIONS,
PROMPT_HINTS,
)
```
**Boundary respect:** NIE importujesz `apps/api/*` ani `apps/workers/*` z tego workflow. Side-channel reuse'uje TYLKO `packages/*`. Jeśli potrzebujesz logiki która siedzi w apps — to znak że side-channel jest niewłaściwy ścieżki (vide fundament 1).
### 3. Mentalny LLM dispatch + Pydantic guardrail
W produkcji `apps/api` → `LLMRouter.complete()` → LiteLLM → provider. W side-channel **Ty (Claude w Claude Code) jesteś tym providerem**. Workflow:
1. **Read kontrakt** — Read tool, plik z `inbox/<filename>.{pdf,docx,txt}`. Dla PDF: jeśli Claude Code wspiera, OK; inaczej user konwertuje do .txt offline (Sprint 4+ doda `packages/ingestion` proper parser).
2. **Apply SYSTEM_PROMPT mentalnie** — wczytaj `spec["system_prompt"]` + `spec["few_shot_examples"]` jako kontekst. Te są tym samym promptem który dostałby Sonnet w produkcji, identyczna jakość extraction.
3. **Wygeneruj structured output** — JSON matchujący `LiabilityClause` schema. Pola wymagane: `found`, `text`, `source_location`, `confidence`, `cap` (LiabilityCap lub None), `carve_outs` (list), `preliminary_status`, `key_observations`, `extraction_prompt_version`.
4. **Construct Pydantic object** — `LiabilityClause(**output_dict)`. Validators automatycznie:
- Append "REQUIRES LEGAL COUNSEL SIGN-OFF" do `key_observations` (auto-disclaimer)
- Downgrade `Approved` → `Needs Attention` jeśli `cap is None` (unlimited liability detector)
- Reject `requires_counsel_review=False` (Literal[True] hardcoded — niezmienne)
- Validate `confidence` w `[0, 1]`
- Reject malformed `cap` shape
Jeśli construction zawodzi z ValidationError → output był malformed, **wróć do kroku 3** i popraw. NIE forsuj objscure pól (np. `requires_counsel_review=False`) — to celowo niedostępne.
### 4. Jurisdiction post-check (PL)
Po Pydantic construction:
```python
checked_clause = post_extraction_check(clause)
```
Ta funkcja (`packages/jurisdictions/pl/liability.py`):
- **Appenduje MANDATORY_OBSERVATIONS** dla PL: KC art. 473 § 2 (nie można wyłączyć liability za winę umyślną), KC art. 484 § 2 (sąd może obniżyć karę umowną "rażąco wygórowaną")
- **Downgrade do Needs Attention** jeśli `carve_outs` nie zawiera `gross_negligence` lub `willful_misconduct` (PL prawo wymaga carve-outów na te przypadki dla cap'a)
- **No-op jeśli `found=False`** — nie ma sensu dorzucać PL rules do klauzuli której nie ma w kontrakcie
Wynik: `checked_clause` ma pełen audit trail (oryginalne observations + PL rules + auto-disclaimer + downgrade trigger jeśli dotyczy).
### 5. Output format — JSON + Markdown + audit log
Trzy artefakty w `outputs/` (gitignored — to private review, nie produkt):
**1. JSON dump** (`outputs/<contract_slug>_liability.json`):
```python
import json
from pathlib import Path
out_dir = Path("outputs")
out_dir.mkdir(exist_ok=True)
(out_dir / f"{contract_slug}_liability.json").write_text(
checked_clause.model_dump_json(indent=2),
encoding="utf-8",
)
```
**2. Markdown report** (`outputs/<contract_slug>_liability.md`) — human-readable dla Tobiasza, używasz [[pisanie-pl]] dla każdego PL fragmentu:
```markdown
# Liability review — {contract_name}
**Status preliminary:** {preliminary_status}
**Confidence:** {confidence:.2f}
**Source:** {source_location}
**Prompt version:** {extraction_prompt_version}
## Tekst klauzuli
> {text}
## Cap
- **Amount:** {cap.amount} {cap.currency}
- **Scope:** {cap.scope}
- **Multiplier of fees:** {cap.multiplier_of_fees}
## Carve-outs
- {", ".join(carve_outs) or "(brak)"}
## Key observations
{bullet list of key_observations}
## Disclaimer
**REQUIRES LEGAL COUNSEL SIGN-OFF.** AI-assisted preliminary review per ADR-001 M2.
Final decision wymaga radcy prawnego / adwokata. Nie traktować jako poradę prawną.
```
**3. Audit log entry** (`outputs/audit_log.jsonl`) — append-only JSONL:
```python
import json
from datetime import datetime, timezone
from pathlib import Path
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"operation": "compass_legal_review.internal",
"tenant_id": "_internal", # placeholder dla side-channel
"user_id": "tobiasz",
"contract_slug": contract_slug,
"clause_type": "liability",
"preliminary_status": checked_clause.preliminary_status,
"confidence": checked_clause.confidence,
"prompt_version": VERSION,
"runtime": "claude_code_side_channel", # NIE production
}
audit_path = Path("outputs/audit_log.jsonl")
audit_path.parent.mkdir(exist_ok=True)
with audit_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
```
To jest **observability surrogate** dla M8 (Langfuse w produkcji). Side-channel nie ma Langfuse hookup, ale ślad JSON+MD+jsonl daje retrospective debug capability.
### 6. Hard guardrails — AI legal disclaimer (nie negocjowalne)
Per [[legal-tech]] skill (user-level, 14-pkt self-check + hard disclaimer):
1. **NIGDY** nie afirmuj że klauzula jest "enforceable" / "valid" / "legalna" / "OK" bez radcy prawnego
2. **ZAWSZE** w Markdown report sekcja "Disclaimer" z "REQUIRES LEGAL COUNSEL SIGN-OFF"
3. **NIGDY** nie dostarczaj wyjścia do klienta haski.io / kogokolwiek innego bez human counsel review w jurysdykcji
4. **Citation discipline** — nie cytuj artykułów / orzeczeń SN bez weryfikacji że istnieją (Claude halucinuje statutes; jeśli nie jesteś pewny → "patrz właściwy artykuł KC dot. ...")
5. **PL vs EN terminologia** — nie myl "indemnification" (US) z "odszkodowanie" (PL) ani "limitation of liability" z "kara umowna"
6. **AI Act compliance** — jeśli output używany jako decision support w "high-risk" obszarze (legal/healthcare/credit) — human-in-the-loop jest wymóg regulatory, nie opcja
## Self-check — OBOWIĄZKOWO
**12 punktów** przed wysłaniem output do Tobiasza. Wykonaj punkt po punkcie:
### Decyzja + import surface (1-3)
1. **Side-channel właściwy** — czy to NIE jest klient prod / real-time / modify packages? Jeśli któreś z tych → STOP, użyj `apps/api` / [[compass-clause-taxonomy]] / [[compass-architecture]].
2. **Imports z packages/* tylko** — czy importuję `compass_schemas` + `compass_prompts` + `compass_jurisdictions`? Czy NIE importuję `apps.api.*` / `apps.workers.*`?
3. **Venv aktywny** — czy `uv sync --all-packages` wykonany, czy import nie failuje?
### Mentalny dispatch + Pydantic (4-6)
4. **SYSTEM_PROMPT loaded z prompts/** — czy używam `load_prompt("liability_v1")`, NIE własnego inline'owego promptu (M4 invariant + version traceability)?
5. **Pydantic validation pass** — czy `LiabilityClause(**output)` constructor passed bez ValidationError? Jeśli nie — naprawiłem JSON shape, nie obeszłem schema.
6. **Auto-disclaimer applied** — czy `key_observations` zawiera "REQUIRES LEGAL COUNSEL SIGN-OFF" (Pydantic validator dorzuca auto jeśli `found=True` + observations present)?
### Jurisdiction + output (7-9)
7. **PL post-check applied** — czy wywołałem `post_extraction_check(clause)`? Czy `key_observations` zawiera "KC art. 473 § 2" oraz "KC art. 484 § 2" dla found clauses?
8. **Downgrade trigger zweryfikowany** — jeśli `cap is None` lub brak `gross_negligence`+`willful_misconduct` carve-outs, czy `preliminary_status` jest `Needs Attention` (lub gorzej), NIE `Approved`?
9. **JSON + MD + audit log** — wszystkie 3 artefakty zapisane w `outputs/`? `audit_log.jsonl` appended (NIE overwritten)?
### Hard guardrails (10-12)
10. **AI legal disclaimer w Markdown** — sekcja "Disclaimer" obecna, z explicit "REQUIRES LEGAL COUNSEL SIGN-OFF" + "nie traktować jako poradę prawną"?
11. **Citations verified** — jeśli cytuję art. KC / orzeczenie SN — czy zweryfikowałem że istnieje? Jeśli nie pewny — "patrz właściwy artykuł KC dot. ..." zamiast konkretnego cytatu.
12. **PL terminology consistency** — nie pomyliłem indemnification/odszkodowanie, limitation of liability/kara umowna, etc.? PL terminologia matchuje legal-tech baseline?
**Dla każdego output do Tobiasza** — VISIBLE confirmation w Markdown report (na końcu, przed Disclaimer):
```
Self-check compass-legal-review:
- Side-channel decision ✓
- Imports clean ✓
- Pydantic validation ✓
- Auto-disclaimer ✓
- PL post-check ✓
- Output JSON+MD+audit ✓
- AI legal disclaimer ✓
- Citations verified ✓
```
## Mini-przykład — full workflow
```python
"""End-to-end internal review — Tobiasz personal contract.
Run from Claude Code session z aktywnym venv.
"""
import json
from datetime import datetime, timezone
from pathlib import Path
from compass_jurisdictions.pl.liability import post_extraction_check
from compass_prompts import load_prompt
from compass_schemas.clauses import LiabilityClause
# 1. Read contract (Claude Code Read tool — outside this snippet)
contract_text = Path("inbox/vendor_x_msa.txt").read_text(encoding="utf-8")
contract_slug = "vendor_x_msa"
# 2. Load prompt + few-shots
spec = load_prompt("liability_v1")
# SYSTEM_PROMPT + FEW_SHOT_EXAMPLES guide my (Claude's) mental extraction:
# - I read contract_text against spec["system_prompt"]
# - Match patterns from spec["few_shot_examples"]
# - Produce structured JSON output below
# 3. Structured output (Claude generates this from mental extraction)
output_dict = {
"found": True,
"text": "Section 8.1 Limitation of Liability. EXCEPT FOR ...",
"source_location": "Section 8.1",
"confidence": 0.92,
"cap": {
"amount": "100000",
"currency": "EUR",
"scope": "aggregate",
"multiplier_of_fees": None,
},
"carve_outs": ["gross_negligence", "willful_misconduct", "ip_indemnity"],
"preliminary_status": "Approved",
"key_observations": [
"Mutual cap at EUR 100k aggregate.",
"Standard carve-outs present (gross negligence, willful misconduct, IP).",
"Cap to annual fees ratio not specified — verify against payment terms.",
],
"extraction_prompt_version": spec["version"],
}
# 4. Pydantic construction — validators run automatically
clause = LiabilityClause(**output_dict)
# At this point: auto-disclaimer appended to key_observations.
# If cap was None: preliminary_status would be downgraded to "Needs Attention".
# 5. PL post-extraction check
checked = post_extraction_check(clause)
# Now: MANDATORY_OBSERVATIONS (KC art. 473 § 2 + 484 § 2) appended.
# 6. Output artifacts
out_dir = Path("outputs")
out_dir.mkdir(exist_ok=True)
(out_dir / f"{contract_slug}_liability.json").write_text(
checked.model_dump_json(indent=2), encoding="utf-8"
)
md = f"""# Liability review — {contract_slug}
**Status:** {checked.preliminary_status}
**Confidence:** {checked.confidence:.2f}
**Source:** {checked.source_location}
**Prompt:** {checked.extraction_prompt_version}
## Tekst
> {checked.text}
## Cap
- Amount: {checked.cap.amount} {checked.cap.currency}
- Scope: {checked.cap.scope}
## Carve-outs
- {", ".join(checked.carve_outs)}
## Observations
{chr(10).join(f"- {o}" for o in checked.key_observations)}
## Self-check compass-legal-review
- Side-channel decision: ✓
- Imports clean: ✓
- Pydantic validation: ✓
- Auto-disclaimer: ✓
- PL post-check: ✓
- Output JSON+MD+audit: ✓
- AI legal disclaimer: ✓
- Citations verified: ✓
## Disclaimer
**REQUIRES LEGAL COUNSEL SIGN-OFF.** AI-assisted preliminary review per ADR-001 M2
+ ADR-002 internal-use side-channel. Final decision wymaga radcy prawnego / adwokata
w jurysdykcji PL. Nie traktować jako poradę prawną.
"""
(out_dir / f"{contract_slug}_liability.md").write_text(md, encoding="utf-8")
# Audit log append
audit_entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"operation": "compass_legal_review.internal",
"tenant_id": "_internal",
"user_id": "tobiasz",
"contract_slug": contract_slug,
"clause_type": "liability",
"preliminary_status": checked.preliminary_status,
"confidence": checked.confidence,
"prompt_version": spec["version"],
"runtime": "claude_code_side_channel",
}
audit_path = out_dir / "audit_log.jsonl"
with audit_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(audit_entry, ensure_ascii=False) + "\n")
print(f"Done. See {out_dir}/{contract_slug}_liability.{{json,md}}")
```
## Cross-references
- [[compass-architecture]] — package boundaries (apps→packages direction; side-channel reuse'uje packages)
- [[compass-clause-taxonomy]] — 14-clause taxonomy + Pydantic+zod sync (used as-is, NIE dodajesz typów tutaj)
- [[compass-ai-native-mandates]] — M2 (schema-first) + M8 (observable surrogate via audit log) applies even w side-channel
- legal-tech (user-level) — full red flag library + GDPR/AI Act + PL/EU/UK/US baseline + 14-pkt self-check
- pisanie-pl (user-level) — każdy PL fragment markdown report przez 10-pkt self-check
- ADR-001 (`docs/architecture/ADR-001-ai-native.md`) — 8 mandates baseline
- ADR-002 (`docs/architecture/ADR-002-llm-provider-byok.md`) — internal-use side-channel rationale (Decision section + Internal-use side-channel)
## Zasada główna
**Identical schemas, different runtime.** Production = `apps/api` z provider-agnostic gateway (ADR-002). Internal-use = Claude Code reuse `packages/*` jako library. Brak duplicate kodu, brak shadow taxonomy, brak alternative prompts — packages są SSOT. Side-channel działa dopóki: (a) Tobiasz jest solo founder bez klientów prod, (b) ≤5 kontraktów/tydzień, (c) tylko PL liability dopóki Sprint 4 nie expand'uje jurisdictions. Wszystko ponad to → `apps/api` production path. **AI legal disclaimer + human counsel sign-off nigdy nie znika** — nawet w "private" review.
+21 -1
View File
@@ -1,12 +1,32 @@
# Compass — env template. Copy to .env.local and populate.
# NEVER commit .env.local — see CLAUDE.md security invariant #9.
# ---------- LLM providers ----------
# ---------- LLM provider selection (BYOK + local LLM hybrid, ADR-002) ----------
# Pick ONE curated profile (preferred) OR set provider/endpoint/model directly.
# Default deployment: local-data-sovereign (on-prem moat #4 jako default).
#
# Profiles:
# cloud-cheap — anthropic, Sonnet 4.6 (typical) + Haiku 4.5 (bulk)
# cloud-premium — anthropic, Opus 4.7 (all tasks)
# local-data-sovereign — ollama, Bielik 11B v2.3 (PL) + Llama 3.3 70B (fallback)
# hybrid — ollama primary; promote to cloud on critical/long-ctx
# custom — BYOK, set LLM_DEFAULT_MODEL + LLM_ENDPOINT yourself
LLM_PROFILE=local-data-sovereign
LLM_PROVIDER=ollama # anthropic | ollama | azure | openai | mock
LLM_ENDPOINT=http://localhost:11434 # Ollama base URL; blank for cloud autodetect
LLM_API_KEY=ollama # Ollama uses dummy 'ollama' string; cloud: real key
# LLM_DEFAULT_MODEL= # BYOK override (exact LiteLLM model string)
# ---------- Cloud provider keys (only if LLM_PROVIDER in {anthropic, openai, azure}) ----------
ANTHROPIC_API_KEY=sk-ant-...
VOYAGE_API_KEY=pa-...
GEMINI_API_KEY=AIza...
# Optional: OPENAI_API_KEY=sk-... (only if multi-provider fallback chain enabled)
# ---------- Local LLM (only if LLM_PROVIDER=ollama) ----------
OLLAMA_API_BASE=http://localhost:11434 # set automatically by gateway from LLM_ENDPOINT
# Run scripts/setup_local_llm.sh to install Ollama + pull Bielik weights
# ---------- Supabase (auth + DB + storage) ----------
SUPABASE_URL=https://<project-ref>.supabase.co
SUPABASE_ANON_KEY=eyJ...
+20 -8
View File
@@ -27,7 +27,13 @@ Project memory for Claude Code working in this repository. **Read first w każde
- **FastAPI** (Python) — primary backend
- **PydanticAI** — agent framework primary
- **LangGraph** — selective (multi-step flows tylko)
- **LiteLLM** — multi-provider gateway, cost tracking, model routing
- **LLM gateway:** provider-agnostic per ADR-002 — `packages/llm-gateway` wraps
LiteLLM with curated profiles (`cloud-cheap` / `cloud-premium` /
`local-data-sovereign` / `hybrid` / `custom`) + BYOK via `LLM_DEFAULT_MODEL`.
Default deployment: `local-data-sovereign` (Ollama+Bielik, moat #4 jako default).
Model preference order: **Bielik 11B v2.3** (default local PL) → **Claude Sonnet 4.6**
(curated cloud baseline) → **Claude Opus 4.7** (compliance-critical) →
**Gemini 2.5 Pro** (long-context fallback >120k tokens).
- **Celery + Redis** — task queue dla operacji >5s
**Data:**
@@ -60,6 +66,7 @@ Gdy Claude pracuje nad zadaniem dotykającym legal-tech / Compass kodu, **invoke
- **`compass-architecture`** — system overview, monorepo, data model, RLS, deployment topology (12-pkt self-check)
- **`compass-clause-taxonomy`** — Pydantic schemas, zod mirror, prompt templates, jurisdiction variants, add-clause workflow (13-pkt self-check)
- **`compass-ai-native-mandates`** — enforcement ADR-001 8 mandatów (8-pkt self-check; mandatory dla każdej PR z LLM operation)
- **`compass-legal-review`** — internal-use side-channel (ADR-002), Claude Code reuse `packages/*` jako library dla solo founder phase contract review (12-pkt self-check; NIE production runtime)
### Level 3 — Framework (user-level, global)
@@ -85,7 +92,7 @@ Gdy Claude pracuje nad zadaniem dotykającym legal-tech / Compass kodu, **invoke
2. **M2 Schema-first** — Pydantic input/output, retry 3×, NIGDY regex parsing
3. **M3 Streaming** — SSE dla każdej operacji >2s, EventSource w UI
4. **M4 Eval-driven** — prompt change wymaga passing eval w CI, golden dataset min 20 PL + 20 EN
5. **M5 Cost-aware routing** — LLMRouter wybiera model (Sonnet default, Opus critical, Haiku bulk, Gemini long-ctx), `tenant_id` + `operation` w metadata
5. **M5 Cost-aware routing** — `LLMRouter` jest provider-agnostic (ADR-002): wybór modelu na podstawie profile + task complexity + urgency, dispatch przez LiteLLM do {anthropic, ollama, azure, openai, mock}. Local profile preferuje Bielik 11B (typical PL) / Llama 3.3 70B (review+long-ctx). Cloud profile preferuje Sonnet 4.6 (typical) / Opus 4.7 (critical) / Haiku 4.5 (bulk) / Gemini 2.5 Pro (long-ctx). Hybrid profile = local primary z cloud promote na criticality=high lub context>120k. `tenant_id` + `operation` w metadata enforced przez `GatewayRejected` provider-agnostic.
6. **M6 Cache-aware** — Anthropic prompt cache + embedding cache (Redis) + result memoization (doc_hash + prompt_v + model)
7. **M7 Async-first** — operacje >5s przez Celery, return task_id + stream_url
8. **M8 Observable** — Langfuse trace per agent run, `tenant_id` w metadata
@@ -119,12 +126,15 @@ Gdy Claude pracuje nad zadaniem dotykającym legal-tech / Compass kodu, **invoke
## Cost discipline
- **Per-tenant cost tracking** w Langfuse od dnia 1 — każdy LLM call z `tenant_id` + `operation` metadata
- **Model routing rules** (per ADR-001 M5):
- Clause extraction → Sonnet 4.6
- Compliance review (critical) → Opus 4.7
- Bulk classification (>100 docs) → Haiku 4.5
- Embedding → voyage-multilingual-2
- Long context (>200k) → Gemini 2.5 Pro
- **Model routing rules** (per ADR-001 M5 + ADR-002 provider-agnostic):
| Operation | `cloud-cheap` profile | `local-data-sovereign` profile | `hybrid` profile |
|---|---|---|---|
| Clause extraction (typical) | Sonnet 4.6 | Bielik 11B v2.3 | Bielik local → Sonnet on confidence<0.6 |
| Compliance review (critical) | Opus 4.7 | Llama 3.3 70B | promote do Opus zawsze |
| Bulk classification (>100) | Haiku 4.5 | Bielik 11B (lower quant.) | local zawsze |
| Embedding | voyage-multilingual-2 | voyage (Sprint 4: local embed) | local-first |
| Long context (>120k local / >180k cloud) | Gemini 2.5 Pro | Llama 3.3 70B + chunking | promote do Gemini |
- **Cost annotation w task definition** — każda nowa operacja w `apps/workers/tasks/` ma docstring z estimated cost per typical document
- **Cache hit ratio monitoring** — Langfuse scorer dla cache hits, alert jeśli <30% dla extraction
- **Monthly per-tenant cost report** — automated z Langfuse → email do operator (subagent `compass-cost-analyzer` Sprint 5+)
@@ -244,10 +254,12 @@ User świadomie absorbuje IP risk per analysis 2026-05-17. **Kontekst:**
## Cross-references
- `docs/architecture/ADR-001-ai-native.md` — pełna ADR z 8 mandates + alternatives considered + status
- `docs/architecture/ADR-002-llm-provider-byok.md` — provider-agnostic gateway (BYOK + curated profiles + Claude Code side-channel)
- `AGENTS.md` — 8 subagents topology (clause-extractor, clause-reviewer, jurisdiction-checker, prompt-tester, doc-parser, rls-auditor, test-writer, pr-reviewer)
- `.claude/skills/compass-architecture/SKILL.md`
- `.claude/skills/compass-clause-taxonomy/SKILL.md`
- `.claude/skills/compass-ai-native-mandates/SKILL.md`
- `.claude/skills/compass-legal-review/SKILL.md` — internal-use side-channel workflow (Claude Code reuses packages/* jako library)
- `.claude/settings.json` — permissions + hooks placeholder + MCPs scope
- `~/.claude/CLAUDE.md` — user-level global instructions (kto pyta, stack defaults, anti-patterns)
@@ -0,0 +1,186 @@
# ADR-002: LLM provider hybrid — BYOK + curated profiles + Claude Code internal use
- **Status:** Accepted
- **Date:** 2026-05-17 (evening)
- **Decision-makers:** Tobiasz Badura (solo founder, private build phase)
- **Supersedes:** none — refines ADR-001 M5 (cost-aware routing) without contradicting it
- **Superseded by:** none
## Context
Sprint 2 zamknął się working extraction pipeline opartym o LiteLLM + Anthropic Claude (Sonnet/Opus) jako default. ADR-001 M5 zdefiniowało routing rules per task complexity (Sonnet typical / Opus critical / Haiku bulk / Gemini long-context). Implementacja w `packages/llm-gateway/` hardcoded'owała `Model` enum na cloud-only providers przez prefiksy LiteLLM (`anthropic/...`, `gemini/...`).
W wieczorną iterację 2026-05-17 Tobiasz przeforsowal pushback:
> "LLM API nie jest mi potrzebne — wszystko lokalne on-premise. Compass = on-prem moat (moat #4 z CLAUDE.md), klienci dla których RODO jest deal-breaker chcą zerową zewnętrzną comm. Plus internal use w Claude Code bez kupowania dodatkowego API."
Argumenty przemawiają za rewizją:
1. **Strategic moat #4** z CLAUDE.md to **on-prem self-host**, explicite jako differentiator vs MikeOSS ("Prohibited Areas: local-hosting refactors"). Cloud-only LLM łamie ten moat.
2. **RODO / data sovereignty** — niektórzy klienci EU (kancelarie, biura rachunkowe z danymi wrażliwymi, sektor publiczny) NIE akceptują transferu treści kontraktów do external LLM API, nawet z DPA + SCCs.
3. **Cost predictability dla open-core** — klient self-hosting Compass wolnym local LLM = $0/mc inference cost. Cloud baseline = $20-200/mc per tenant. Rozdwojenie ścieżek.
4. **Internal-use Claude Code** — Tobiasz już płaci subskrypcję Claude Code; reuse `packages/*` jako library bez deploymentu `apps/api` jest pragmatyczny dla solo founder z 1-2 kontraktami/tydzień własnej review.
Three options considered.
### Alt A: Claude Code as production runtime
Reuse Claude Code jako runtime dla wszystkich extractions (nie tylko internal). Compass byłby cienkim wrapperem Skills + subagents nad Claude Code SDK.
**Verdict: odrzucone — category error.**
Claude Code = developer tool (interactive shell, file I/O, agentic loop dla single-user dev workflow). Production legal-tech runtime wymaga multi-tenant RLS, JWT auth, audit log per mutation, horizontal scaling, SSE streaming, Celery retries. Claude Code nie projektowany dla tego — to jak budowanie SaaS na bazie ChatGPT Web UI.
### Alt B: cloud-only LiteLLM (status quo Sprint 2)
Zostaw `LLMRouter` hardcoded na cloud providers (Anthropic + Gemini + OpenAI fallback). Brak local LLM path.
**Verdict: odrzucone — łamie moat #4.**
Compass tracilibyśmy główny differentiator vs MikeOSS. EU klienci z RODO-strict profile nie kupiliby produktu. Marketing claim "on-prem self-host" bez prawdziwej local LLM ścieżki = bait-and-switch.
### Alt C1: BYOK only (Bring Your Own Key / Endpoint), bez curated profiles
Zostaw klientowi pełną swobodę konfiguracji — set `LLM_PROVIDER` + `LLM_ENDPOINT` jak chcesz. Brak opinionated defaults.
**Verdict: odrzucone — onboarding friction.**
Klient z RODO concern, dla którego self-host jest must-have, prawdopodobnie NIE ma ekspertyzy żeby samodzielnie zsetupować Ollama + dobrać model + zoptymalizować quantization. "BYOK only" = "DIY" = większość klientów porzuca w Day 1. Curated profiles (`local-data-sovereign` → Ollama+Bielik z setupem skryptem) są mostkiem między pełną kontrolą a out-of-box experience.
### Alt C2: hybrid B + C + A (wybrane)
- **B:** zachowujemy cloud routing dla klientów którzy go chcą (curated `cloud-cheap` / `cloud-premium` profiles)
- **C:** dodajemy BYOK + local LLM jako first-class deployment profile (`local-data-sovereign`)
- **A:** Claude Code jako **internal-use side-channel** (NIE production runtime) — Tobiasz reuse'uje `packages/schemas` + `packages/prompts` + `packages/jurisdictions` jako importowaną library w Claude Code Skill, bez deploymentu `apps/api`
## Decision
**Compass-runtime jest model-agnostic od Sprint 3 forward.** Provider selection przez environment, NIE przez kod.
### Configuration surface
```bash
# Wybierasz JEDEN profile lub set custom values:
LLM_PROFILE=local-data-sovereign # cloud-cheap | cloud-premium | local-data-sovereign | hybrid | custom
LLM_PROVIDER=ollama # anthropic | ollama | azure | openai | mock
LLM_ENDPOINT=http://localhost:11434
LLM_API_KEY=ollama # ollama używa dummy key
LLM_DEFAULT_MODEL=bielik:11b-v2.3 # override jeśli profile resolution nie pasuje
```
### Curated profiles
| Profile | Provider | Default models | Use case |
|---|---|---|---|
| `cloud-cheap` | anthropic | Sonnet 4.6 (typical) + Haiku 4.5 (bulk) | budget-conscious cloud, EU compliance z DPA + SCCs |
| `cloud-premium` | anthropic | Opus 4.7 (all tasks) | high-stakes review (M&A, regulatory exposure) |
| `local-data-sovereign` | ollama | Bielik 11B v2.3 (PL) + Llama 3.3 70B (fallback EN/long-ctx) | EU RODO-strict, sektor publiczny, kancelarie z danymi wrażliwymi |
| `hybrid` | ollama → anthropic | local primary, cloud na criticality=high lub context>120k | scale-up: tanie typowe extractions lokalnie, drogie krytyczne w chmurze |
| `custom` | env-driven | env-driven | enterprise BYOK — własny Azure OpenAI deployment, AWS Bedrock, on-prem vLLM |
### Default deployment profile
`local-data-sovereign`. Decyzja: nowy klient instalujący Compass (docker compose up) dostaje z definicji local Ollama+Bielik, bez wymogu zewnętrznych kluczy. Cloud profile = opt-in.
**Reasoning:** moat #4 (on-prem self-host) ma być **default**, nie opcją w sekcji "advanced settings". Pierwsza linijka kodu produkcyjnego Compass = data sovereignty.
### Schema-first invariant zachowany
`packages/schemas/`, `packages/prompts/`, `packages/jurisdictions/` są **provider-agnostic**. Identyczne prompts działają cross-provider — różnica jest tylko w accuracy/cost/latency. Pydantic validators (auto-disclaimer, unlimited→Needs Attention downgrade, PL post-extraction check) działają niezależnie od LLM origin. ADR-001 M2 (Schema-first LLM I/O) nadal w pełni egzekwowane.
### ADR-001 M5 update
Routing rules pozostają, ale dispatch jest **provider-agnostic**:
| Operation | Cloud profile model | Local profile model | Hybrid profile behaviour |
|---|---|---|---|
| Clause extraction (typical) | Sonnet 4.6 | Bielik 11B v2.3 | Bielik local; promote do Sonnet jeśli confidence<0.6 |
| Compliance review (critical) | Opus 4.7 | Llama 3.3 70B | promote do Opus zawsze |
| Bulk classification | Haiku 4.5 | Bielik 11B (lower quantization) | local zawsze (cost-sensitive) |
| Embedding | voyage-multilingual-2 | nomic-embed-text + bielik-embed | local-first, cloud fallback dla unsupported languages |
| Long context (>120k tokens) | Gemini 2.5 Pro | Llama 3.3 70B + chunking | promote do Gemini zawsze |
### Internal-use side-channel (Opcja A subset)
`.claude/skills/compass-legal-review/` definiuje workflow w którym Claude Code reuse'uje `packages/schemas` + `packages/prompts` + `packages/jurisdictions` jako importowaną Python library. **Claude (model) jest LLM** — Tobiasz nie wywołuje gateway, tylko mentalnie aplikuje SYSTEM_PROMPT, konstruuje `LiabilityClause(**output)`, Pydantic validators wymuszają correctness, `pl_liability.post_extraction_check()` aplikuje KC art. 473/484 rules.
**Identical schemas, different runtime.** Production runtime = `apps/api` z gateway provider-agnostic. Internal runtime = Claude Code reuse. Brak duplicate kodu — packages są SSOT.
To NIE jest production runtime, NIE replace'uje `apps/api`. To jest workflow dla solo founder który ma ~1-5 kontraktów/tydzień własnej review — nie chce deployować całego stacku tylko po to żeby pomocniczo posprawdzać jeden umowę.
## Consequences
### Gain
- **Full data sovereignty option** — klient EU z RODO-strict profile ma realną drogę: ani jeden bit treści kontraktu nie wychodzi z jego infrastruktury. Default profile to wspiera, nie ukrywa.
- **AI Act compliance łatwiejszy** — local LLM = brak transferu do third-party AI provider = mniej requirements dla high-risk classification (Art. 16 AI Act).
- **Zero vendor lock-in** — klient z istniejącym Azure OpenAI Enterprise deployment lub AWS Bedrock subscription może wsadzić go przez `custom` profile bez zmiany kodu Compass.
- **MikeOSS pattern compatibility** — klienci z MikeOSS background rozumieją BYOK / self-host paradigm (MikeOSS Will Chen explicite "Prohibited Areas: local-hosting refactors" → Compass wypełnia tę lukę).
- **Cost predictability** — open-core klient self-hosting = $0/mc inference. Cloud klient = predictable per-call cost via routing rules. Brak ślepego rachunku per tenant.
- **Internal use Tobiasza** — solo founder phase: bez API kosztów dla własnej review, bez deploymentu stacku, full schemas + jurisdiction rules wymuszane przez Pydantic.
### Cost
- **7GB Bielik weights bundle** lub klient musi sam pobrać (`ollama pull SpeakLeash/bielik-11b-v2.3-instruct`). Docker compose może bundlować lub instalować on first run — decyzja open (patrz "Open questions").
- **Baseline accuracy trade-off** — Bielik 11B baseline accuracy 65-78% vs Sonnet 4.6 ~90% na liability PL (estimate z public benchmarks, wymaga eval validation w Sprint 4+). To **feature**, nie bug — local LLM = WIĘCEJ human oversight wymagane = zgodne z ADR-001 (`requires_counsel_review: Literal[True]` hardcoded w schema) + AI Act human-in-the-loop dla high-risk.
- **Dłuższy onboarding dla local profile** — instalacja Ollama + pull weights + verify endpoint = 10-30 min vs cloud profile = "wpisz API key, gotowe". Mitigation: `scripts/setup_local_llm.sh` bootstrap.
- **Per-provider quirks** — LiteLLM abstrahuje, ale Ollama vs Anthropic mają różne tool calling capabilities, streaming semantics, prompt cache behaviour. Eval framework MUSI verify cross-provider parity (Sprint 4+).
### Risk
- **Klient wybiera słaby local LLM model** (np. Bielik 7B starszy, lub Llama 3.2 zamiast 3.3) → "Compass nie działa" opinia. **Mitigation:** opinionated curated profiles + setup script + docs explicite "supported models" lista. Outside listy = `custom` profile + user accepts responsibility.
- **Hybrid profile complexity** — fallback logic (local→cloud przy criticality high lub context>120k) musi być transparent w Langfuse traces (trace pokazuje obie próby + decision rationale). Bez tego debugging "dlaczego Compass wybrał Sonnet zamiast Bielik" jest niemożliwy. **Mitigation:** M8 (Observable) extended z `routing_decision` field w trace metadata.
- **Eval cross-provider regression** — prompt zoptymalizowany dla Sonnet może działać gorzej na Bielik (np. JSON output format reliability różni się). **Mitigation:** eval framework musi runować per-provider (`pytest -m eval --profile=local-data-sovereign` vs `--profile=cloud-cheap`), thresholds osobne per profile (M4 update Sprint 4).
- **Internal-use side-channel scope creep** — Tobiasz może zacząć używać Claude Code zamiast budować `apps/api`, przesuwając timeline MVP. **Mitigation:** explicite kategoryzacja — side-channel = dev tool, NIE replace dla product. Memory `project-compass` flag jeśli >20% tygodniowego czasu idzie w side-channel zamiast w product.
## Implementation outline
### Sprint 3 (current)
1. **`packages/llm-gateway/` refactor → provider-agnostic** (current sprint)
- `LLMGatewayConfig` (pydantic-settings) — env-driven provider + endpoint + api_key + default_model + profile
- `Model` enum extended: `OLLAMA_BIELIK_11B`, `OLLAMA_LLAMA_33_70B`, `OLLAMA_MISTRAL_24B`
- `LLMRouter.complete()` honors `config.default_model` (BYOK override), `profile=hybrid` fallback chain, `provider=mock` deterministic stub
- `GatewayRejected` nadal egzekwowane (tenant_id + operation w metadata) — provider-agnostic
- Test `test_llm_gateway_config.py` (env override, profile selection, mock provider)
2. **`.claude/skills/compass-legal-review/SKILL.md`** — internal-use workflow Tobiasza
3. **`packages/evals/runner.py` mock mode** — CI eval bez ANTHROPIC_API_KEY
4. **`.env.example` + `CLAUDE.md`** update — BYOK + curated profiles documented
5. **`scripts/setup_local_llm.sh`** (optional) — Ollama+Bielik bootstrap
### Sprint 4 (next)
- **Eval cross-provider parity** — eval suite runs per-profile, separate thresholds
- **Routing decision observability** — `routing_decision` field w Langfuse trace metadata dla hybrid profile
- **Docker compose `local-data-sovereign` bundle** — czy bundlujemy Ollama service w compose lub zostawiamy prerequisite install (decyzja open, patrz poniżej)
- **`packages/jurisdictions/de|fr|en/`** — multi-jurisdiction expansion, każda działa cross-provider
### Sprint 5+
- **MCP server** (`apps/mcp-server`) — distribution channel dla Compass jako MCP, czerpiący z tych samych `packages/*` (provider-agnostic by inheritance)
- **Self-hosted Langfuse** — przesunięcie Langfuse z optional do default dla `local-data-sovereign` profile (data sovereignty pełna, łącznie z observability)
## Open questions
Pozostawione do decyzji w Sprint 3 review lub Sprint 4 kickoff:
1. **Ollama bundling w Docker compose vs install prerequisite** — bundling = zero-config deploy, ale +7GB image. Prerequisite = lekkie, ale 10-30 min onboarding gap. Decyzja zależy od typical klient persona — open.
2. **`compass-legal-review` skill scope** — tylko liability PL na start (matchuje Sprint 2 implementation) czy od razu wszystkie clause types z registry? Decyzja: start z liability PL, expand w Sprint 4 paralelnie do nowych clause types.
3. **Profile naming bikeshed** — `local-data-sovereign` vs `ollama-bielik` vs `on-prem`. Wpłynie na docs/marketing later. Decyzja: `local-data-sovereign` (intent-first, nie tech-first; user nie cares o Ollama, cares o "moje dane się nie ruszają").
4. **Hybrid profile criticality threshold** — kiedy promote local→cloud (confidence<0.6? confidence<0.5? operator-defined?). Wymaga eval data Sprint 4+. Default tymczasowy: confidence<0.6 OR criticality=high OR context>120k OR explicit `urgency=critical`.
## Status
**Accepted 2026-05-17 wieczorem.** Obowiązuje od Sprint 3 implementation. Review po 3 msc (2026-08-17) lub przy pierwszym znaczącym deviation (np. klient enterprise wymagający custom routing logic poza profile system).
ADR-001 8 mandatów **nadal w pełni applies**. Ta ADR refines M5 — nie supersedes.
## Linki
- [[ADR-001-ai-native]] — 8 mandatów (M5 cost-aware routing refined here)
- [[compass-architecture]] — package boundaries (`packages/llm-gateway` jako leaf, single-responsibility)
- [[compass-ai-native-mandates]] — M5 + M8 enforcement (provider-agnostic compatible)
- [[compass-legal-review]] — internal-use Claude Code side-channel (Sprint 3 deliverable)
- `bielik-router` (user-level) — Bielik 11B selection criteria, quantization, hardware fit
- `cloud-deploy` (user-level) — Hetzner deployment patterns dla cloud profile
- Handoff: `docs/handoffs/2026-05-17-sprint3-handoff.md`
+79 -13
View File
@@ -3,6 +3,12 @@
Per ADR-001 M4: every prompt change requires passing eval suite in CI. The
runner computes precision / recall / cost per field and per overall extraction.
Per ADR-002: ``LLM_PROVIDER=mock`` short-circuits live ``extract_clause()``,
constructing a mock LiabilityClause directly from ``row["expected"]``. This
keeps CI eval framework wiring testable without ANTHROPIC_API_KEY (cloud) or
GPU (local Ollama). Mock mode trivially passes precision=recall=1.0 by
construction — it verifies the runner/comparison pipeline, NOT LLM quality.
Golden dataset format (JSONL, one example per line):
{
"id": "pl-001",
@@ -15,7 +21,7 @@ Golden dataset format (JSONL, one example per line):
Metrics:
- precision = TP / (TP + FP) : where TP/FP measured per (example, field) pair
- recall = TP / (TP + FN) : FN = field present in expected, missing or wrong in extracted
- cost_per_doc : USD, summed from Langfuse generation usage
- cost_per_doc : USD, summed from Langfuse generation usage (0.0 in mock mode)
Field comparison semantics:
- Scalar fields (bool, int, str, Decimal): exact match
@@ -29,16 +35,22 @@ from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from compass_agents import extract_clause
log = logging.getLogger(__name__)
MOCK_PROVIDER_VALUE = "mock"
def _is_mock_mode() -> bool:
"""True if LLM_PROVIDER=mock — skip live LLM, mock from expected payload."""
return os.getenv("LLM_PROVIDER", "").strip().lower() == MOCK_PROVIDER_VALUE
# Fields ignored during precision/recall scoring (graded by LLM-as-judge in Sprint 3+)
SUBJECTIVE_FIELDS: frozenset[str] = frozenset({
"text",
@@ -181,35 +193,89 @@ def load_dataset(dataset_name: str, base_dir: Path | None = None) -> list[dict[s
return rows
def _make_mock_clause_dict(row: dict[str, Any]) -> dict[str, Any]:
"""Construct deterministic mock extraction from row['expected'].
Strategy: shallow copy ``expected`` verbatim — guarantees actual==expected
per field, so the comparison pipeline (TP/FP/FN, precision/recall) trivially
scores 1.0/1.0. Then backfill required schema fields (subjective + required
invariants) if missing from expected.
This verifies runner/comparison wiring without claiming anything about LLM
quality — see ``run_eval`` docstring.
"""
expected = dict(row.get("expected", {}))
mock: dict[str, Any] = dict(expected)
mock.setdefault("found", True)
mock.setdefault(
"text",
f"[mock] {row.get('input_text', '')[:200]}" if mock["found"] else None,
)
mock.setdefault(
"source_location",
"[mock] Section unknown" if mock["found"] else None,
)
mock.setdefault("confidence", 0.99)
mock.setdefault("preliminary_status", "Needs Attention")
mock.setdefault(
"key_observations",
["[mock] deterministic eval — replace LLM_PROVIDER=mock to run live LLM."],
)
mock.setdefault("suggested_questions_for_counsel", [])
mock.setdefault("extraction_prompt_version", "liability_v1")
mock["requires_counsel_review"] = True
return mock
async def run_eval(
*,
prompt_version: str,
dataset: str,
clause_type: str = "liability",
tenant_id: str = "_eval",
mock_mode: bool | None = None,
) -> EvalResult:
"""Run the full eval suite for a (prompt_version, dataset) pair.
Note: this hits the LLM gateway. Cost ≈ $0.01-0.02 per example
Live mode (default): hits the LLM gateway. Cost ≈ $0.01-0.02 per example
(Sonnet 4.6 typical for liability extraction).
Mock mode (``mock_mode=True`` or env ``LLM_PROVIDER=mock``): skips live
extraction, builds actual=expected by construction. Used in CI to verify
runner wiring without API keys. Precision/recall trivially 1.0 in this
mode — NOT a quality signal, only a smoke test.
"""
if mock_mode is None:
mock_mode = _is_mock_mode()
examples = load_dataset(dataset)
result = EvalResult(prompt_version=prompt_version, dataset_name=dataset)
# Lazy import — mock mode does NOT require compass_agents (which pulls in
# PydanticAI + Anthropic SDK). CI w/o LLM creds can still smoke-test eval.
extract_clause = None
if not mock_mode:
from compass_agents import extract_clause as _extract_clause # type: ignore
extract_clause = _extract_clause
for row in examples:
ex_result = ExampleResult(example_id=row["id"])
try:
clause = await extract_clause(
contract_text=row["input_text"],
clause_type=clause_type,
jurisdiction_code=row.get("jurisdiction", "pl"),
tenant_id=tenant_id,
)
actual: dict[str, Any]
if isinstance(clause, BaseModel):
actual = clause.model_dump(mode="json")
if mock_mode:
actual = _make_mock_clause_dict(row)
else:
actual = dict(clause)
assert extract_clause is not None # narrow for type checker
clause = await extract_clause(
contract_text=row["input_text"],
clause_type=clause_type,
jurisdiction_code=row.get("jurisdiction", "pl"),
tenant_id=tenant_id,
)
if isinstance(clause, BaseModel):
actual = clause.model_dump(mode="json")
else:
actual = dict(clause)
tp, fp, fn, field_results = _compare_fields(row["expected"], actual)
ex_result.correct_fields = tp
ex_result.false_positives = fp
+71
View File
@@ -0,0 +1,71 @@
"""Pytest config dla compass-evals — adds --profile CLI flag.
Per ADR-002: ``--profile`` propagates LLM_PROFILE + LLM_PROVIDER env so eval
tests run against the selected curated profile (cloud-cheap, cloud-premium,
local-data-sovereign, hybrid, custom, mock).
Examples::
pytest packages/evals/tests/ -m eval --profile=mock
pytest packages/evals/tests/ -m eval --profile=cloud-cheap
pytest packages/evals/tests/ -m eval --profile=local-data-sovereign
"""
from __future__ import annotations
import os
from typing import Iterator
import pytest
_KNOWN_PROFILES = {
"cloud-cheap": "anthropic",
"cloud-premium": "anthropic",
"local-data-sovereign": "ollama",
"hybrid": "ollama",
"custom": None, # caller MUST set LLM_PROVIDER + LLM_DEFAULT_MODEL externally
"mock": "mock", # convenience: --profile=mock sets LLM_PROVIDER=mock
}
def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption(
"--profile",
action="store",
default=None,
choices=list(_KNOWN_PROFILES.keys()),
help="LLM profile per ADR-002 — sets LLM_PROFILE + LLM_PROVIDER env "
"for the test session. Default: leave env as-is.",
)
@pytest.fixture(autouse=True, scope="session")
def _apply_profile_env(request: pytest.FixtureRequest) -> Iterator[None]:
profile = request.config.getoption("--profile")
if not profile:
yield
return
prev_profile = os.environ.get("LLM_PROFILE")
prev_provider = os.environ.get("LLM_PROVIDER")
# --profile=mock is a convenience override of provider; profile stays sane
if profile == "mock":
os.environ["LLM_PROVIDER"] = "mock"
# Keep LLM_PROFILE as configured (or default) — mock provider sidesteps it
else:
os.environ["LLM_PROFILE"] = profile
provider = _KNOWN_PROFILES[profile]
if provider:
os.environ["LLM_PROVIDER"] = provider
try:
yield
finally:
if prev_profile is None:
os.environ.pop("LLM_PROFILE", None)
else:
os.environ["LLM_PROFILE"] = prev_profile
if prev_provider is None:
os.environ.pop("LLM_PROVIDER", None)
else:
os.environ["LLM_PROVIDER"] = prev_provider
@@ -1,13 +1,23 @@
"""Eval test for liability extraction (ADR-001 M4 gate).
Requires:
Live mode requires:
- ANTHROPIC_API_KEY in env (LLM gateway hits live model)
- LANGFUSE_* in env (for cost tracking) — optional, set LANGFUSE_ENABLED=false to skip
- Internet access
Mock mode (``--profile=mock`` or ``LLM_PROVIDER=mock``) requires neither —
runs deterministic stub from row["expected"], smoke-tests runner wiring only.
Skipped by default (`@pytest.mark.eval`). Run explicitly::
uv run pytest packages/evals/tests/test_liability_extraction.py -m eval
# Mock (CI, no creds needed)
uv run pytest packages/evals/tests/test_liability_extraction.py -m eval --profile=mock
# Live cloud
uv run pytest packages/evals/tests/test_liability_extraction.py -m eval --profile=cloud-cheap
# Live local Ollama
uv run pytest packages/evals/tests/test_liability_extraction.py -m eval --profile=local-data-sovereign
"""
from __future__ import annotations
@@ -16,6 +26,7 @@ import os
import pytest
from compass_evals import run_eval
from compass_evals.runner import _is_mock_mode
pytestmark = pytest.mark.eval
@@ -33,8 +44,11 @@ def llm_keys_present() -> bool:
@pytest.mark.asyncio
async def test_liability_extraction_pl_golden(llm_keys_present: bool) -> None:
if not llm_keys_present:
pytest.skip("ANTHROPIC_API_KEY not set — eval requires live LLM access")
if not _is_mock_mode() and not llm_keys_present:
pytest.skip(
"ANTHROPIC_API_KEY not set and LLM_PROVIDER != mock — "
"eval requires live LLM creds OR mock mode (pass --profile=mock)."
)
result = await run_eval(prompt_version="liability_v1", dataset="liability_pl")
@@ -50,7 +64,30 @@ async def test_liability_extraction_pl_golden(llm_keys_present: bool) -> None:
assert result.recall >= RECALL_THRESHOLD, (
f"Recall regression: {result.recall:.4f} < {RECALL_THRESHOLD}"
)
if result.cost_per_doc > 0: # 0.0 in offline mode (Langfuse not wired in v1 runner)
if result.cost_per_doc > 0: # 0.0 in offline/mock mode (Langfuse not wired in v1 runner)
assert result.cost_per_doc <= COST_PER_DOC_USD_THRESHOLD, (
f"Cost regression: ${result.cost_per_doc:.4f} > ${COST_PER_DOC_USD_THRESHOLD}"
)
@pytest.mark.asyncio
async def test_liability_extraction_mock_mode_smoke() -> None:
"""Mock mode smoke test — independent of --profile flag.
Forces mock_mode=True regardless of env so this test runs in any CI
config. Validates runner pipeline wiring (load_dataset, compare_fields,
EvalResult aggregation) without needing LLM creds OR --profile=mock CLI.
"""
result = await run_eval(
prompt_version="liability_v1",
dataset="liability_pl",
mock_mode=True,
)
# Mock returns expected as actual → precision/recall trivially 1.0.
# Smoke test value: pipeline works, dataset loads, fields compare.
assert len(result.examples) >= 1, "dataset liability_pl appears empty"
assert result.error_rate == 0.0, f"mock mode produced errors: {result.error_rate}"
assert result.precision == 1.0, f"mock precision != 1.0: {result.precision}"
assert result.recall == 1.0, f"mock recall != 1.0: {result.recall}"
assert result.cost_per_doc == 0.0, "mock mode should report zero cost"
+3 -2
View File
@@ -1,12 +1,13 @@
[project]
name = "compass-llm-gateway"
version = "0.1.0"
description = "Multi-provider LLM router with cost tracking, model selection, Langfuse instrumentation, and caching"
version = "0.2.0"
description = "Provider-agnostic LLM gateway (BYOK + curated profiles + Langfuse instrumentation) per ADR-001 + ADR-002"
requires-python = ">=3.12"
dependencies = [
"litellm>=1.50",
"langfuse>=2.50",
"pydantic>=2.9",
"pydantic-settings>=2.5",
"redis>=5.0",
"tenacity>=9.0",
"structlog>=24.4",
@@ -3,9 +3,32 @@
Enforces ADR-001 mandates M5 (cost-aware multi-model routing), M6 (cache-aware),
and M8 (observable LLM ops) at the gateway level so individual agents do not
duplicate this logic.
"""
from compass_llm_gateway.models import Model, TaskType, Urgency
from compass_llm_gateway.router import LLMRouter
__all__ = ["LLMRouter", "Model", "TaskType", "Urgency"]
__version__ = "0.1.0"
Per ADR-002 (provider-agnostic): provider selection (anthropic / ollama /
azure / openai / mock) is env-driven via ``LLMGatewayConfig``. Curated profiles
(``cloud-cheap``, ``cloud-premium``, ``local-data-sovereign``, ``hybrid``,
``custom``) wybierają opinionated defaults. BYOK via ``LLM_DEFAULT_MODEL`` env.
"""
from compass_llm_gateway.config import (
LLMGatewayConfig,
Profile,
Provider,
is_cloud_profile,
is_local_profile,
)
from compass_llm_gateway.models import Model, TaskType, Urgency
from compass_llm_gateway.router import GatewayRejected, LLMRouter
__all__ = [
"GatewayRejected",
"LLMGatewayConfig",
"LLMRouter",
"Model",
"Profile",
"Provider",
"TaskType",
"Urgency",
"is_cloud_profile",
"is_local_profile",
]
__version__ = "0.2.0"
@@ -0,0 +1,79 @@
"""Gateway configuration — provider, endpoint, profile selection.
Per ADR-002: Compass-runtime jest provider-agnostic. Wybór providera (anthropic
/ ollama / azure / openai / mock) odbywa się przez env vars, NIE przez kod.
Curated profiles (`cloud-cheap`, `cloud-premium`, `local-data-sovereign`,
`hybrid`, `custom`) dają opinionated defaults dla typowych deployment scenarios.
Default profile dla nowej instalacji to ``local-data-sovereign`` (on-prem moat
#4 jako default, nie opcja w advanced settings).
"""
from __future__ import annotations
from typing import Literal
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
Provider = Literal["anthropic", "ollama", "azure", "openai", "mock"]
Profile = Literal[
"cloud-cheap",
"cloud-premium",
"local-data-sovereign",
"hybrid",
"custom",
]
class LLMGatewayConfig(BaseSettings):
"""Env-driven gateway configuration.
Reads ``LLM_*`` prefixed env vars. ``.env.local`` is honored when present.
All fields optional — defaults wybierają ``local-data-sovereign`` profile
z Ollama+Bielik 11B (per ADR-002 default deployment).
"""
model_config = SettingsConfigDict(
env_prefix="LLM_",
env_file=".env.local",
env_file_encoding="utf-8",
extra="ignore",
)
profile: Profile = Field(
default="local-data-sovereign",
description="Curated deployment profile or 'custom' for full BYOK control.",
)
provider: Provider = Field(
default="ollama",
description="LLM provider — drives LiteLLM model name prefix.",
)
endpoint: str | None = Field(
default="http://localhost:11434",
description="Provider endpoint URL. Required for ollama/azure/custom; "
"cloud providers autodetect from API key.",
)
api_key: str | None = Field(
default="ollama",
description="Provider API key. For Ollama use dummy 'ollama' string.",
)
default_model: str | None = Field(
default=None,
description="BYOK override — exact LiteLLM model string. If unset, "
"profile resolution selects sensible default per TaskType.",
)
enable_langfuse: bool = Field(
default=True,
description="Whether to wrap calls in Langfuse traces (M8). Set false "
"in unit tests + ephemeral CI jobs without Langfuse access.",
)
def is_cloud_profile(profile: Profile) -> bool:
"""True jeśli profile wymaga cloud API key (cloud-cheap, cloud-premium)."""
return profile in ("cloud-cheap", "cloud-premium")
def is_local_profile(profile: Profile) -> bool:
"""True jeśli profile preferuje local LLM (local-data-sovereign, hybrid primary)."""
return profile in ("local-data-sovereign", "hybrid")
@@ -1,11 +1,23 @@
"""Model + task type enums for LLM routing.
Routing table (per ADR-001 M5):
- Clause extraction (typical) -> Sonnet 4.6
Routing table per ADR-001 M5 + ADR-002 (provider-agnostic):
Cloud profiles (cloud-cheap, cloud-premium):
- Clause extraction (typical) -> Sonnet 4.6 / Opus 4.7
- Compliance review (critical) -> Opus 4.7
- Bulk classification (>100 docs) -> Haiku 4.5
- Embedding -> voyage-multilingual-2
- Long context (>200k tokens) -> Gemini 2.5 Pro
Local profile (local-data-sovereign):
- Clause extraction (typical) -> Bielik 11B v2.3 (PL)
- Compliance review (critical) -> Llama 3.3 70B
- Bulk classification -> Bielik 11B v2.3 (cheaper quantization)
- Embedding -> local embed (Sprint 4+)
- Long context (>120k tokens) -> Llama 3.3 70B + chunking (Sprint 4+)
Hybrid profile: local primary, cloud promote na criticality=high OR
context>120k OR confidence<0.6 OR explicit urgency=critical.
"""
from __future__ import annotations
@@ -13,12 +25,25 @@ from enum import Enum
class Model(str, Enum):
# Cloud — Anthropic
SONNET_46 = "anthropic/claude-sonnet-4-6"
OPUS_47 = "anthropic/claude-opus-4-7"
HAIKU_45 = "anthropic/claude-haiku-4-5-20251001"
# Cloud — Google
GEMINI_25_PRO = "gemini/gemini-2.5-pro"
# Cloud — Voyage (embeddings)
VOYAGE_MULTILINGUAL_2 = "voyage/voyage-multilingual-2"
# Local — Ollama (LiteLLM routes via OLLAMA_API_BASE env, model prefix "ollama/...")
OLLAMA_BIELIK_11B = "ollama/SpeakLeash/bielik-11b-v2.3-instruct"
OLLAMA_LLAMA_33_70B = "ollama/llama3.3:70b-instruct-q4_K_M"
OLLAMA_MISTRAL_24B = "ollama/mistral-small:24b-instruct-2501-q4_K_M"
# Mock — deterministic stub dla CI bez API key i bez GPU
MOCK = "mock/deterministic-stub"
class TaskType(str, Enum):
CLAUSE_EXTRACTION = "clause_extraction"
@@ -1,42 +1,110 @@
"""LLM router — model selection, cost tracking, Langfuse instrumentation.
"""LLM router — provider-agnostic model selection, cost tracking, Langfuse instrumentation.
Sprint 1: routing logic + Langfuse trace wrapper. Sprint 2 adds real cache
integration (Redis embedding + result memoization) and fallback chain
(Sonnet -> Opus -> Gemini Pro -> dead letter queue).
Per ADR-002: provider selection (anthropic / ollama / azure / openai / mock)
driven by ``LLMGatewayConfig`` (env-based). Curated profiles wybierają sensible
defaults dla typical operations; BYOK ``default_model`` override sidesteps
profile resolution całkowicie.
Per ADR-001 M5+M8: every call requires tenant_id + operation in metadata.
Calls without these are rejected at gateway level — no exceptions.
Calls without these are rejected at gateway level — no exceptions, provider-agnostic.
"""
from __future__ import annotations
import hashlib
import json
import os
import time
from typing import Any
import litellm
import structlog
from langfuse import Langfuse
from compass_llm_gateway.config import LLMGatewayConfig, Profile
from compass_llm_gateway.models import Model, TaskType, Urgency
log = structlog.get_logger()
CLAUDE_LONG_CONTEXT_THRESHOLD = 180_000
CLOUD_LONG_CONTEXT_THRESHOLD = 180_000
LOCAL_LONG_CONTEXT_THRESHOLD = 120_000
BULK_BATCH_THRESHOLD = 100
HYBRID_PROMOTE_CONFIDENCE_FLOOR = 0.6
class GatewayRejected(Exception):
"""Raised when an LLM call is missing required metadata (tenant_id, operation)."""
class LLMRouter:
"""Single LLM gateway. Wraps LiteLLM + Langfuse + Compass routing rules."""
# Profile → default model mapping per TaskType.
# Resolution order: explicit model_override > config.default_model > _PROFILE_DEFAULTS[profile][task].
_PROFILE_DEFAULTS: dict[Profile, dict[TaskType, Model]] = {
"cloud-cheap": {
TaskType.CLAUSE_EXTRACTION: Model.SONNET_46,
TaskType.CLAUSE_REVIEW: Model.OPUS_47,
TaskType.JURISDICTION_CHECK: Model.SONNET_46,
TaskType.BULK_CLASSIFICATION: Model.HAIKU_45,
TaskType.EMBEDDING: Model.VOYAGE_MULTILINGUAL_2,
TaskType.LONG_CONTEXT: Model.GEMINI_25_PRO,
},
"cloud-premium": {
TaskType.CLAUSE_EXTRACTION: Model.OPUS_47,
TaskType.CLAUSE_REVIEW: Model.OPUS_47,
TaskType.JURISDICTION_CHECK: Model.OPUS_47,
TaskType.BULK_CLASSIFICATION: Model.SONNET_46,
TaskType.EMBEDDING: Model.VOYAGE_MULTILINGUAL_2,
TaskType.LONG_CONTEXT: Model.GEMINI_25_PRO,
},
"local-data-sovereign": {
TaskType.CLAUSE_EXTRACTION: Model.OLLAMA_BIELIK_11B,
TaskType.CLAUSE_REVIEW: Model.OLLAMA_LLAMA_33_70B,
TaskType.JURISDICTION_CHECK: Model.OLLAMA_BIELIK_11B,
TaskType.BULK_CLASSIFICATION: Model.OLLAMA_BIELIK_11B,
# Sprint 4+ replaces voyage with local embed (nomic-embed-text or bielik-embed)
TaskType.EMBEDDING: Model.VOYAGE_MULTILINGUAL_2,
TaskType.LONG_CONTEXT: Model.OLLAMA_LLAMA_33_70B,
},
"hybrid": {
# Local primary; cloud promotion handled in select_model().
TaskType.CLAUSE_EXTRACTION: Model.OLLAMA_BIELIK_11B,
TaskType.CLAUSE_REVIEW: Model.OPUS_47, # critical → always cloud
TaskType.JURISDICTION_CHECK: Model.OLLAMA_BIELIK_11B,
TaskType.BULK_CLASSIFICATION: Model.OLLAMA_BIELIK_11B,
TaskType.EMBEDDING: Model.VOYAGE_MULTILINGUAL_2,
TaskType.LONG_CONTEXT: Model.GEMINI_25_PRO,
},
"custom": {
# No opinionated defaults — caller MUST provide config.default_model
# or pass model_override per call. select_model() raises if neither set.
},
}
def __init__(self, langfuse: Langfuse | None = None) -> None:
self.langfuse = langfuse or Langfuse(
public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
host=os.getenv("LANGFUSE_HOST"),
)
class LLMRouter:
"""Single LLM gateway. Wraps LiteLLM + Langfuse + Compass provider-agnostic routing."""
def __init__(
self,
config: LLMGatewayConfig | None = None,
langfuse: Langfuse | None = None,
) -> None:
self.config = config or LLMGatewayConfig()
if self.config.enable_langfuse:
self.langfuse = langfuse or Langfuse(
public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
host=os.getenv("LANGFUSE_HOST"),
)
else:
self.langfuse = None # type: ignore[assignment]
self._configure_provider_env()
def _configure_provider_env(self) -> None:
"""Set provider-specific env vars that LiteLLM reads at call time."""
if self.config.provider == "ollama" and self.config.endpoint:
# LiteLLM standard env for Ollama base URL
os.environ.setdefault("OLLAMA_API_BASE", self.config.endpoint)
# anthropic / openai / azure: their SDKs already read standard env names
# (ANTHROPIC_API_KEY, OPENAI_API_KEY, AZURE_*). No override here — user
# sets them directly. config.api_key remains advisory.
def select_model(
self,
@@ -45,14 +113,63 @@ class LLMRouter:
urgency: Urgency = Urgency.NORMAL,
batch_size: int = 1,
) -> Model:
if context_size > CLAUDE_LONG_CONTEXT_THRESHOLD:
return Model.GEMINI_25_PRO
if urgency == Urgency.CRITICAL or task == TaskType.CLAUSE_REVIEW:
return Model.OPUS_47
if batch_size > BULK_BATCH_THRESHOLD or task == TaskType.BULK_CLASSIFICATION:
return Model.HAIKU_45
if task == TaskType.EMBEDDING:
return Model.VOYAGE_MULTILINGUAL_2
"""Resolve task to concrete Model based on profile + overrides + heuristics.
Resolution order:
1. ``config.default_model`` (BYOK string override) — wraps in Model.MOCK or matches enum
2. ``profile=hybrid`` promotion rules (criticality + context size + urgency)
3. ``_PROFILE_DEFAULTS[profile][task]``
4. Fallback ``Model.SONNET_46`` (defensive; raises for custom profile)
"""
# BYOK string override (Model enum exact match, else best-effort lookup)
if self.config.default_model:
for m in Model:
if m.value == self.config.default_model:
return m
# Unknown model string — fall through to profile default with warning
log.warning(
"llm_gateway.default_model_unknown",
model=self.config.default_model,
fallback_profile=self.config.profile,
)
# Mock provider — always returns Model.MOCK regardless of task
if self.config.provider == "mock":
return Model.MOCK
# Hybrid profile: cloud promotion logic
if self.config.profile == "hybrid":
if urgency == Urgency.CRITICAL or task == TaskType.CLAUSE_REVIEW:
return Model.OPUS_47
if context_size > LOCAL_LONG_CONTEXT_THRESHOLD:
return Model.GEMINI_25_PRO
return _PROFILE_DEFAULTS["hybrid"][task]
# Cloud profiles: long context fallback to Gemini
if self.config.profile in ("cloud-cheap", "cloud-premium"):
if context_size > CLOUD_LONG_CONTEXT_THRESHOLD:
return Model.GEMINI_25_PRO
if urgency == Urgency.CRITICAL and self.config.profile == "cloud-cheap":
# Promote cheap → premium on critical
return Model.OPUS_47
if batch_size > BULK_BATCH_THRESHOLD and task != TaskType.CLAUSE_REVIEW:
return Model.HAIKU_45
return _PROFILE_DEFAULTS[self.config.profile][task]
# Local profile: stay local even on critical (user explicitly opted out of cloud)
if self.config.profile == "local-data-sovereign":
if context_size > LOCAL_LONG_CONTEXT_THRESHOLD or task == TaskType.LONG_CONTEXT:
return Model.OLLAMA_LLAMA_33_70B
return _PROFILE_DEFAULTS["local-data-sovereign"][task]
# Custom profile: NO opinionated defaults — require explicit config or override
if self.config.profile == "custom":
raise GatewayRejected(
"profile='custom' requires LLM_DEFAULT_MODEL env or per-call model_override "
"— no profile defaults available (ADR-002)"
)
# Defensive fallback
return Model.SONNET_46
async def complete(
@@ -69,8 +186,12 @@ class LLMRouter:
) -> Any:
"""Run an LLM completion through the gateway.
Required `metadata` keys: ``tenant_id``, ``operation``. Missing keys
Required ``metadata`` keys: ``tenant_id``, ``operation``. Missing keys
raise :class:`GatewayRejected` — no defaults, no inference.
Mock provider returns a deterministic ``_MockResponse`` keyed by
``(operation, prompt_hash[:8])`` — used by CI eval framework and unit
tests without LLM credentials. See ADR-002 "Implementation outline".
"""
if "tenant_id" not in metadata:
raise GatewayRejected("LLM call missing tenant_id in metadata (ADR-001 M5)")
@@ -79,19 +200,39 @@ class LLMRouter:
model = model_override or self.select_model(task, context_size, urgency, batch_size)
trace = self.langfuse.trace(
name=metadata["operation"],
metadata=metadata,
tags=[task.value, model.value],
)
generation = trace.generation(
name=metadata["operation"],
model=model.value,
input={"prompt_preview": prompt[:500]},
metadata={"prompt_version": metadata.get("prompt_version")},
)
# Mock provider short-circuit — no LiteLLM, no Langfuse generation
if self.config.provider == "mock" or model == Model.MOCK:
return _make_mock_response(prompt, metadata)
trace = None
generation = None
if self.langfuse is not None:
trace = self.langfuse.trace(
name=metadata["operation"],
metadata={**metadata, "profile": self.config.profile, "provider": self.config.provider},
tags=[task.value, model.value, self.config.profile],
)
generation = trace.generation(
name=metadata["operation"],
model=model.value,
input={"prompt_preview": prompt[:500]},
metadata={
"prompt_version": metadata.get("prompt_version"),
"routing_decision": {
"profile": self.config.profile,
"provider": self.config.provider,
"urgency": urgency.value,
"context_size": context_size,
"batch_size": batch_size,
},
},
)
try:
# Import LiteLLM lazily — local profile installations bez cloud SDKs
# nadal mogą import this module bez LiteLLM at module-load time.
import litellm
response = await litellm.acompletion(
model=model.value,
messages=[{"role": "user", "content": prompt}],
@@ -99,15 +240,66 @@ class LLMRouter:
**litellm_kwargs,
)
usage = getattr(response, "usage", None)
generation.end(
output={"text": response.choices[0].message.content[:500]},
usage={
"input": getattr(usage, "prompt_tokens", 0) if usage else 0,
"output": getattr(usage, "completion_tokens", 0) if usage else 0,
},
)
if generation is not None:
generation.end(
output={"text": response.choices[0].message.content[:500]},
usage={
"input": getattr(usage, "prompt_tokens", 0) if usage else 0,
"output": getattr(usage, "completion_tokens", 0) if usage else 0,
},
)
return response
except Exception as exc:
generation.end(level="ERROR", status_message=str(exc))
log.exception("llm_gateway.complete.failed", task=task.value, model=model.value)
if generation is not None:
generation.end(level="ERROR", status_message=str(exc))
log.exception(
"llm_gateway.complete.failed",
task=task.value,
model=model.value,
profile=self.config.profile,
provider=self.config.provider,
)
raise
class _MockResponse:
"""LiteLLM-shaped response stub dla provider='mock'.
Deterministic content keyed by (operation, prompt_hash[:8]) — same input
yields same output. Used by CI eval framework and unit tests.
"""
class _Choice:
def __init__(self, content: str) -> None:
self.message = _MockResponse._Message(content)
class _Message:
def __init__(self, content: str) -> None:
self.content = content
self.role = "assistant"
class _Usage:
def __init__(self) -> None:
self.prompt_tokens = 0
self.completion_tokens = 0
self.total_tokens = 0
def __init__(self, content: str) -> None:
self.choices = [_MockResponse._Choice(content)]
self.usage = _MockResponse._Usage()
self.id = f"mock-{int(time.time())}"
self.model = Model.MOCK.value
def _make_mock_response(prompt: str, metadata: dict[str, Any]) -> _MockResponse:
"""Deterministic mock — JSON keyed by operation + prompt hash."""
prompt_hash = hashlib.sha256(prompt.encode("utf-8")).hexdigest()[:8]
payload = {
"mock": True,
"operation": metadata.get("operation"),
"prompt_hash": prompt_hash,
"tenant_id": metadata.get("tenant_id"),
"note": "deterministic mock response — replace with actual extraction "
"by setting LLM_PROVIDER != mock",
}
return _MockResponse(json.dumps(payload))
@@ -0,0 +1,196 @@
"""Offline unit tests dla provider-agnostic gateway routing (ADR-002).
These tests do NOT hit any LLM:
- Env override resolution
- Profile → default model resolution
- Mock provider deterministic stub
- GatewayRejected enforcement (tenant_id + operation)
Run::
uv run pytest packages/llm-gateway/tests/test_llm_gateway_config.py
"""
from __future__ import annotations
import asyncio
import os
import pytest
from compass_llm_gateway import (
GatewayRejected,
LLMGatewayConfig,
LLMRouter,
Model,
TaskType,
Urgency,
is_cloud_profile,
is_local_profile,
)
@pytest.fixture(autouse=True)
def _clear_llm_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Strip LLM_* env so each test starts from documented defaults."""
for key in list(os.environ):
if key.startswith("LLM_"):
monkeypatch.delenv(key, raising=False)
def test_default_profile_is_local_data_sovereign() -> None:
"""ADR-002: default deployment profile = local-data-sovereign (moat #4 jako default)."""
cfg = LLMGatewayConfig(enable_langfuse=False)
assert cfg.profile == "local-data-sovereign"
assert cfg.provider == "ollama"
assert cfg.endpoint == "http://localhost:11434"
def test_env_override_provider_and_profile(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("LLM_PROFILE", "cloud-cheap")
monkeypatch.setenv("LLM_PROVIDER", "anthropic")
monkeypatch.setenv("LLM_ENDPOINT", "")
cfg = LLMGatewayConfig(enable_langfuse=False)
assert cfg.profile == "cloud-cheap"
assert cfg.provider == "anthropic"
def test_profile_predicates() -> None:
assert is_cloud_profile("cloud-cheap") is True
assert is_cloud_profile("cloud-premium") is True
assert is_cloud_profile("local-data-sovereign") is False
assert is_local_profile("local-data-sovereign") is True
assert is_local_profile("hybrid") is True
assert is_local_profile("cloud-cheap") is False
def test_local_profile_resolves_to_bielik_for_extraction() -> None:
cfg = LLMGatewayConfig(profile="local-data-sovereign", provider="ollama", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_EXTRACTION) == Model.OLLAMA_BIELIK_11B
def test_local_profile_uses_llama_for_review_and_long_context() -> None:
cfg = LLMGatewayConfig(profile="local-data-sovereign", provider="ollama", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_REVIEW) == Model.OLLAMA_LLAMA_33_70B
# Local long-context threshold = 120k, lower than cloud's 180k (Llama smaller window)
assert router.select_model(TaskType.CLAUSE_EXTRACTION, context_size=150_000) == Model.OLLAMA_LLAMA_33_70B
def test_cloud_cheap_profile_resolves_to_sonnet_default() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_EXTRACTION) == Model.SONNET_46
assert router.select_model(TaskType.CLAUSE_REVIEW) == Model.OPUS_47
assert router.select_model(TaskType.BULK_CLASSIFICATION, batch_size=500) == Model.HAIKU_45
def test_cloud_cheap_promotes_to_opus_on_critical_urgency() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_EXTRACTION, urgency=Urgency.CRITICAL) == Model.OPUS_47
def test_cloud_long_context_routes_to_gemini() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_EXTRACTION, context_size=200_000) == Model.GEMINI_25_PRO
def test_hybrid_profile_promotes_critical_to_cloud_opus() -> None:
cfg = LLMGatewayConfig(profile="hybrid", provider="ollama", enable_langfuse=False)
router = LLMRouter(config=cfg)
# Typical extraction stays local
assert router.select_model(TaskType.CLAUSE_EXTRACTION) == Model.OLLAMA_BIELIK_11B
# Compliance review always cloud (Opus)
assert router.select_model(TaskType.CLAUSE_REVIEW) == Model.OPUS_47
# Critical urgency → Opus
assert router.select_model(TaskType.CLAUSE_EXTRACTION, urgency=Urgency.CRITICAL) == Model.OPUS_47
# Long context → Gemini
assert router.select_model(TaskType.CLAUSE_EXTRACTION, context_size=150_000) == Model.GEMINI_25_PRO
def test_byok_default_model_override(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("LLM_DEFAULT_MODEL", Model.OPUS_47.value)
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
# Override beats profile default — even bulk classification gets Opus
assert router.select_model(TaskType.BULK_CLASSIFICATION, batch_size=500) == Model.OPUS_47
def test_custom_profile_requires_explicit_model() -> None:
cfg = LLMGatewayConfig(profile="custom", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
with pytest.raises(GatewayRejected, match="LLM_DEFAULT_MODEL"):
router.select_model(TaskType.CLAUSE_EXTRACTION)
def test_mock_provider_returns_mock_model() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="mock", enable_langfuse=False)
router = LLMRouter(config=cfg)
assert router.select_model(TaskType.CLAUSE_EXTRACTION) == Model.MOCK
def test_mock_complete_returns_deterministic_stub() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="mock", enable_langfuse=False)
router = LLMRouter(config=cfg)
metadata = {"tenant_id": "t-test", "operation": "extract_liability"}
response_a = asyncio.run(
router.complete("Liability clause text X", task=TaskType.CLAUSE_EXTRACTION, metadata=metadata)
)
response_b = asyncio.run(
router.complete("Liability clause text X", task=TaskType.CLAUSE_EXTRACTION, metadata=metadata)
)
# Deterministic: same prompt + same metadata operation → same content
assert response_a.choices[0].message.content == response_b.choices[0].message.content
assert "mock" in response_a.choices[0].message.content.lower()
assert response_a.model == Model.MOCK.value
def test_complete_rejects_missing_tenant_id() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="mock", enable_langfuse=False)
router = LLMRouter(config=cfg)
with pytest.raises(GatewayRejected, match="tenant_id"):
asyncio.run(
router.complete(
"anything",
task=TaskType.CLAUSE_EXTRACTION,
metadata={"operation": "extract"}, # missing tenant_id
)
)
def test_complete_rejects_missing_operation() -> None:
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="mock", enable_langfuse=False)
router = LLMRouter(config=cfg)
with pytest.raises(GatewayRejected, match="operation"):
asyncio.run(
router.complete(
"anything",
task=TaskType.CLAUSE_EXTRACTION,
metadata={"tenant_id": "t-test"}, # missing operation
)
)
def test_ollama_endpoint_propagated_to_litellm_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ollama provider should set OLLAMA_API_BASE so LiteLLM finds local endpoint."""
monkeypatch.delenv("OLLAMA_API_BASE", raising=False)
cfg = LLMGatewayConfig(
profile="local-data-sovereign",
provider="ollama",
endpoint="http://ollama.internal:11434",
enable_langfuse=False,
)
LLMRouter(config=cfg)
assert os.environ.get("OLLAMA_API_BASE") == "http://ollama.internal:11434"
def test_unknown_default_model_string_falls_through_to_profile(monkeypatch: pytest.MonkeyPatch) -> None:
"""BYOK string that doesn't match Model enum → log warning, use profile default."""
monkeypatch.setenv("LLM_DEFAULT_MODEL", "garbage/non-existent-model:v1")
cfg = LLMGatewayConfig(profile="cloud-cheap", provider="anthropic", enable_langfuse=False)
router = LLMRouter(config=cfg)
# Falls through to profile default (Sonnet for cloud-cheap extraction)
assert router.select_model(TaskType.CLAUSE_EXTRACTION) == Model.SONNET_46
+89
View File
@@ -0,0 +1,89 @@
<#
.SYNOPSIS
Bootstrap script — local LLM stack (Ollama + Bielik 11B) per ADR-002.
.DESCRIPTION
Installs Ollama (winget), pulls SpeakLeash/bielik-11b-v2.3-instruct,
optionally pulls llama3.3:70b-instruct-q4_K_M (review + long-context
fallback), verifies that the Ollama HTTP endpoint responds.
Use case: `local-data-sovereign` and `hybrid` deployment profiles.
Hardware: Bielik 11B Q4 ~7GB VRAM; Llama 3.3 70B Q4 ~40GB VRAM
(skip Llama on consumer GPUs — RTX 3070/4070/4080 cannot host it).
.PARAMETER PullLlama
Switch — opt in to pulling Llama 3.3 70B Q4 (~40GB).
.EXAMPLE
.\scripts\setup_local_llm.ps1
.\scripts\setup_local_llm.ps1 -PullLlama
#>
[CmdletBinding()]
param(
[switch]$PullLlama
)
$ErrorActionPreference = 'Stop'
$OllamaApi = $env:OLLAMA_API_BASE
if (-not $OllamaApi) { $OllamaApi = 'http://localhost:11434' }
$BielikTag = 'SpeakLeash/bielik-11b-v2.3-instruct'
$LlamaTag = 'llama3.3:70b-instruct-q4_K_M'
function Write-Step { param([string]$msg) Write-Host "[setup_local_llm] $msg" -ForegroundColor Cyan }
function Write-Err { param([string]$msg) Write-Host "[setup_local_llm ERROR] $msg" -ForegroundColor Red }
# 1. Install Ollama (winget)
if (Get-Command ollama -ErrorAction SilentlyContinue) {
Write-Step "Ollama already installed."
} else {
Write-Step "Installing Ollama via winget..."
winget install --id Ollama.Ollama --accept-source-agreements --accept-package-agreements
# Refresh PATH for current session
$env:Path = [System.Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path','User')
}
# 2. Ensure Ollama service is running
function Test-OllamaEndpoint {
try {
$null = Invoke-WebRequest -Uri "$OllamaApi/api/tags" -UseBasicParsing -TimeoutSec 5
return $true
} catch { return $false }
}
if (-not (Test-OllamaEndpoint)) {
Write-Step "Starting Ollama service in background..."
Start-Process -FilePath ollama -ArgumentList 'serve' -WindowStyle Hidden
Start-Sleep -Seconds 3
}
if (-not (Test-OllamaEndpoint)) {
Write-Err "Ollama endpoint $OllamaApi not reachable. Check Windows service or 'ollama serve' output."
exit 1
}
# 3. Pull Bielik 11B (default model for `local-data-sovereign` PL extraction)
Write-Step "Pulling $BielikTag (~7GB, takes a while on first run)..."
& ollama pull $BielikTag
# 4. Optionally pull Llama 3.3 70B
if ($PullLlama) {
Write-Step "Pulling $LlamaTag (~40GB, requires 40+ GB VRAM to run)..."
& ollama pull $LlamaTag
} else {
Write-Step "Skipping Llama 3.3 70B (pass -PullLlama to opt in)."
Write-Step "Hint: Llama 70B needs 40+ GB VRAM — consumer GPUs cannot host it."
}
# 5. Verify endpoint
Write-Step "Verifying endpoint $OllamaApi/api/tags..."
$tags = Invoke-WebRequest -Uri "$OllamaApi/api/tags" -UseBasicParsing | Select-Object -ExpandProperty Content
Write-Host $tags
Write-Step "Done."
Write-Step "Next: set in .env.local:"
Write-Step " LLM_PROFILE=local-data-sovereign"
Write-Step " LLM_PROVIDER=ollama"
Write-Step " LLM_ENDPOINT=$OllamaApi"
Write-Step "Then: uv run pytest packages/llm-gateway/tests/"
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Bootstrap script — local LLM stack (Ollama + Bielik 11B) per ADR-002.
#
# Installs Ollama, pulls SpeakLeash/bielik-11b-v2.3-instruct, optionally pulls
# llama3.3:70b-instruct-q4_K_M (review + long-context fallback), verifies that
# the Ollama HTTP endpoint responds.
#
# Use case: `local-data-sovereign` and `hybrid` deployment profiles.
# Hardware: Bielik 11B Q4 ≈ 7GB VRAM; Llama 3.3 70B Q4 ≈ 40GB VRAM
# (skip Llama on consumer GPUs — RTX 3070/4070/4080 cannot host it).
set -euo pipefail
OLLAMA_API="${OLLAMA_API_BASE:-http://localhost:11434}"
BIELIK_TAG="SpeakLeash/bielik-11b-v2.3-instruct"
LLAMA_TAG="llama3.3:70b-instruct-q4_K_M"
PULL_LLAMA="${PULL_LLAMA:-no}" # set PULL_LLAMA=yes to opt in
log() { printf "\033[1;36m[setup_local_llm]\033[0m %s\n" "$*"; }
err() { printf "\033[1;31m[setup_local_llm ERROR]\033[0m %s\n" "$*" >&2; }
# 1. Install Ollama
if command -v ollama >/dev/null 2>&1; then
log "Ollama already installed: $(ollama --version 2>/dev/null || echo unknown)"
else
log "Installing Ollama via official installer..."
curl -fsSL https://ollama.ai/install.sh | sh
fi
# 2. Ensure Ollama service is running
if ! curl -fsS "$OLLAMA_API/api/tags" >/dev/null 2>&1; then
log "Starting Ollama service in background..."
ollama serve >/tmp/ollama.log 2>&1 &
sleep 3
fi
if ! curl -fsS "$OLLAMA_API/api/tags" >/dev/null 2>&1; then
err "Ollama endpoint $OLLAMA_API not reachable. Check /tmp/ollama.log."
exit 1
fi
# 3. Pull Bielik 11B (default model for `local-data-sovereign` PL extraction)
log "Pulling $BIELIK_TAG (≈7GB, takes a while on first run)..."
ollama pull "$BIELIK_TAG"
# 4. Optionally pull Llama 3.3 70B (review + long-context fallback)
if [ "$PULL_LLAMA" = "yes" ]; then
log "Pulling $LLAMA_TAG (≈40GB, requires 40+ GB VRAM to actually run)..."
ollama pull "$LLAMA_TAG"
else
log "Skipping Llama 3.3 70B (set PULL_LLAMA=yes to opt in)."
log "Hint: Llama 70B needs 40+ GB VRAM — consumer GPUs (RTX 3070/4070/4080)"
log " cannot host it. Use cloud profile or smaller model for review."
fi
# 5. Verify endpoint
log "Verifying endpoint $OLLAMA_API/api/tags..."
TAGS=$(curl -fsS "$OLLAMA_API/api/tags")
echo "$TAGS"
log "Done."
log "Next: set in .env.local:"
log " LLM_PROFILE=local-data-sovereign"
log " LLM_PROVIDER=ollama"
log " LLM_ENDPOINT=$OLLAMA_API"
log "Then: uv run pytest packages/llm-gateway/tests/ -k ollama"