neuroroute 0.17.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. neuroroute-0.17.0/PKG-INFO +71 -0
  2. neuroroute-0.17.0/README.package.md +30 -0
  3. neuroroute-0.17.0/pyproject.toml +66 -0
  4. neuroroute-0.17.0/setup.cfg +4 -0
  5. neuroroute-0.17.0/src/neuroroute/__init__.py +13 -0
  6. neuroroute-0.17.0/src/neuroroute/_compat.py +20 -0
  7. neuroroute-0.17.0/src/neuroroute/bench.py +71 -0
  8. neuroroute-0.17.0/src/neuroroute/cli.py +206 -0
  9. neuroroute-0.17.0/src/neuroroute/config.py +191 -0
  10. neuroroute-0.17.0/src/neuroroute/model_id.py +64 -0
  11. neuroroute-0.17.0/src/neuroroute/openai_server.py +183 -0
  12. neuroroute-0.17.0/src/neuroroute/py.typed +0 -0
  13. neuroroute-0.17.0/src/neuroroute/result.py +43 -0
  14. neuroroute-0.17.0/src/neuroroute/router.py +91 -0
  15. neuroroute-0.17.0/src/neuroroute/templates/neuroroute.yaml +102 -0
  16. neuroroute-0.17.0/src/neuroroute/train_cli.py +87 -0
  17. neuroroute-0.17.0/src/neuroroute.egg-info/PKG-INFO +71 -0
  18. neuroroute-0.17.0/src/neuroroute.egg-info/SOURCES.txt +40 -0
  19. neuroroute-0.17.0/src/neuroroute.egg-info/dependency_links.txt +1 -0
  20. neuroroute-0.17.0/src/neuroroute.egg-info/entry_points.txt +2 -0
  21. neuroroute-0.17.0/src/neuroroute.egg-info/requires.txt +25 -0
  22. neuroroute-0.17.0/src/neuroroute.egg-info/top_level.txt +1 -0
  23. neuroroute-0.17.0/tests/test_guardrail_messages.py +36 -0
  24. neuroroute-0.17.0/tests/test_model_wrapper.py +244 -0
  25. neuroroute-0.17.0/tests/test_phase10_risk_floor.py +87 -0
  26. neuroroute-0.17.0/tests/test_phase11_benchmark.py +67 -0
  27. neuroroute-0.17.0/tests/test_phase12_api.py +208 -0
  28. neuroroute-0.17.0/tests/test_phase16_api.py +111 -0
  29. neuroroute-0.17.0/tests/test_phase16_config.py +71 -0
  30. neuroroute-0.17.0/tests/test_phase16_package.py +67 -0
  31. neuroroute-0.17.0/tests/test_phase16_post.py +135 -0
  32. neuroroute-0.17.0/tests/test_phase16_serve.py +130 -0
  33. neuroroute-0.17.0/tests/test_phase2_benchmark.py +154 -0
  34. neuroroute-0.17.0/tests/test_phase3_baselines.py +359 -0
  35. neuroroute-0.17.0/tests/test_phase4_estimator.py +114 -0
  36. neuroroute-0.17.0/tests/test_phase5_planner.py +178 -0
  37. neuroroute-0.17.0/tests/test_phase6_executor.py +225 -0
  38. neuroroute-0.17.0/tests/test_phase7_rag.py +152 -0
  39. neuroroute-0.17.0/tests/test_phase8_confidence.py +266 -0
  40. neuroroute-0.17.0/tests/test_phase9_observability.py +173 -0
  41. neuroroute-0.17.0/tests/test_risk_scorer_handcheck.py +38 -0
  42. neuroroute-0.17.0/tests/test_safety.py +43 -0
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: neuroroute
3
+ Version: 0.17.0
4
+ Summary: Traffic controller for AI models — route each request to the right tier.
5
+ Author: NeuroRoute
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/allesko64/neurorouter
8
+ Project-URL: Repository, https://github.com/allesko64/neurorouter
9
+ Keywords: llm,routing,openai,cost,neuro
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: openai>=1.55.0
20
+ Requires-Dist: pyyaml>=6.0
21
+ Requires-Dist: python-dotenv>=1.0.0
22
+ Requires-Dist: tenacity>=9.0.0
23
+ Requires-Dist: numpy>=1.26.0
24
+ Requires-Dist: scikit-learn>=1.4.0
25
+ Requires-Dist: fastembed>=0.4.0
26
+ Requires-Dist: joblib>=1.3.0
27
+ Requires-Dist: httpx>=0.27.0
28
+ Requires-Dist: pydantic>=2.0.0
29
+ Provides-Extra: server
30
+ Requires-Dist: fastapi>=0.115.0; extra == "server"
31
+ Requires-Dist: uvicorn[standard]>=0.32.0; extra == "server"
32
+ Requires-Dist: websockets>=12.0; extra == "server"
33
+ Provides-Extra: rag
34
+ Requires-Dist: asyncpg>=0.29.0; extra == "rag"
35
+ Requires-Dist: pgvector>=0.3.0; extra == "rag"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
38
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
39
+ Requires-Dist: httpx>=0.27.0; extra == "dev"
40
+ Requires-Dist: build>=1.2.0; extra == "dev"
41
+
42
+ # neuroroute
43
+
44
+ Installable **NeuroRoute** core — route each AI request to the right model tier.
45
+
46
+ ```bash
47
+ pip install -e ".[server]"
48
+ neuroroute init
49
+ neuroroute serve --config neuroroute.yaml --port 8080
50
+ ```
51
+
52
+ ```python
53
+ from neuroroute import NeuroRoute
54
+
55
+ router = NeuroRoute.from_config("neuroroute.yaml")
56
+ result = router.run("What is the capital of France?", budget=0.5)
57
+ print(result.answer, result.route, result.cost, result.confidence, result.reason)
58
+ ```
59
+
60
+ ### CLI
61
+
62
+ | Command | Purpose |
63
+ |---------|---------|
64
+ | `neuroroute init` | Write starter `neuroroute.yaml` |
65
+ | `neuroroute serve` | OpenAI-compatible `/v1/chat/completions` + `/feedback` |
66
+ | `neuroroute bench data.csv` | Run a CSV test set → JSONL |
67
+ | `neuroroute train data.csv` | Retrain difficulty classifier |
68
+
69
+ Docs: [`docs/package/`](../docs/package/) (quickstart, config, SDK, Docker).
70
+
71
+ Edit YAML for models / prices / `api_key_env` / thresholds / risk keywords — never put secret key values in the file.
@@ -0,0 +1,30 @@
1
+ # neuroroute
2
+
3
+ Installable **NeuroRoute** core — route each AI request to the right model tier.
4
+
5
+ ```bash
6
+ pip install -e ".[server]"
7
+ neuroroute init
8
+ neuroroute serve --config neuroroute.yaml --port 8080
9
+ ```
10
+
11
+ ```python
12
+ from neuroroute import NeuroRoute
13
+
14
+ router = NeuroRoute.from_config("neuroroute.yaml")
15
+ result = router.run("What is the capital of France?", budget=0.5)
16
+ print(result.answer, result.route, result.cost, result.confidence, result.reason)
17
+ ```
18
+
19
+ ### CLI
20
+
21
+ | Command | Purpose |
22
+ |---------|---------|
23
+ | `neuroroute init` | Write starter `neuroroute.yaml` |
24
+ | `neuroroute serve` | OpenAI-compatible `/v1/chat/completions` + `/feedback` |
25
+ | `neuroroute bench data.csv` | Run a CSV test set → JSONL |
26
+ | `neuroroute train data.csv` | Retrain difficulty classifier |
27
+
28
+ Docs: [`docs/package/`](../docs/package/) (quickstart, config, SDK, Docker).
29
+
30
+ Edit YAML for models / prices / `api_key_env` / thresholds / risk keywords — never put secret key values in the file.
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "neuroroute"
7
+ version = "0.17.0"
8
+ description = "Traffic controller for AI models — route each request to the right tier."
9
+ readme = "README.package.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "NeuroRoute" }]
13
+ keywords = ["llm", "routing", "openai", "cost", "neuro"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+ dependencies = [
24
+ "openai>=1.55.0",
25
+ "pyyaml>=6.0",
26
+ "python-dotenv>=1.0.0",
27
+ "tenacity>=9.0.0",
28
+ "numpy>=1.26.0",
29
+ "scikit-learn>=1.4.0",
30
+ "fastembed>=0.4.0",
31
+ "joblib>=1.3.0",
32
+ "httpx>=0.27.0",
33
+ "pydantic>=2.0.0",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ # FastAPI stack stays optional so `import neuroroute` never pulls it in (Phase 16 / T16.1).
38
+ server = [
39
+ "fastapi>=0.115.0",
40
+ "uvicorn[standard]>=0.32.0",
41
+ "websockets>=12.0",
42
+ ]
43
+ rag = [
44
+ "asyncpg>=0.29.0",
45
+ "pgvector>=0.3.0",
46
+ ]
47
+ dev = [
48
+ "pytest>=8.0.0",
49
+ "pytest-asyncio>=0.24.0",
50
+ "httpx>=0.27.0",
51
+ "build>=1.2.0",
52
+ ]
53
+
54
+ [project.urls]
55
+ Homepage = "https://github.com/allesko64/neurorouter"
56
+ Repository = "https://github.com/allesko64/neurorouter"
57
+
58
+ [project.scripts]
59
+ neuroroute = "neuroroute.cli:main"
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
63
+ include = ["neuroroute*"]
64
+
65
+ [tool.setuptools.package-data]
66
+ neuroroute = ["py.typed", "templates/*.yaml"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ """neuroroute — installable AI model router core (Phase 16).
2
+
3
+ Framework-free by design: importing this package must not import FastAPI.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from neuroroute.result import RouteResult
9
+ from neuroroute.router import NeuroRoute
10
+
11
+ __all__ = ["NeuroRoute", "RouteResult", "__version__"]
12
+
13
+ __version__ = "0.17.0"
@@ -0,0 +1,20 @@
1
+ """Make the existing `app.*` brain importable while the package is a facade."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ _BACKEND_ROOT = Path(__file__).resolve().parents[2]
9
+
10
+
11
+ def ensure_backend_on_path() -> Path:
12
+ """Insert backend/ so `import app...` works next to the installed package."""
13
+ root = str(_BACKEND_ROOT)
14
+ if root not in sys.path:
15
+ sys.path.insert(0, root)
16
+ return _BACKEND_ROOT
17
+
18
+
19
+ def backend_root() -> Path:
20
+ return _BACKEND_ROOT
@@ -0,0 +1,71 @@
1
+ """Run a user CSV through NeuroRoute and write results (Phase 16.5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from neuroroute.router import NeuroRoute
11
+
12
+
13
+ def _read_prompts(path: Path) -> list[dict[str, str]]:
14
+ with path.open(encoding="utf-8", newline="") as f:
15
+ reader = csv.DictReader(f)
16
+ if not reader.fieldnames:
17
+ raise ValueError(f"empty CSV: {path}")
18
+ fields = {name.lower(): name for name in reader.fieldnames}
19
+ prompt_key = (
20
+ fields.get("prompt")
21
+ or fields.get("text")
22
+ or fields.get("query")
23
+ or reader.fieldnames[0]
24
+ )
25
+ rows: list[dict[str, str]] = []
26
+ for i, row in enumerate(reader):
27
+ text = (row.get(prompt_key) or "").strip()
28
+ if not text:
29
+ continue
30
+ rows.append({"id": str(row.get("id") or f"row-{i+1}"), "prompt": text})
31
+ if not rows:
32
+ raise ValueError(f"no prompts found in {path}")
33
+ return rows
34
+
35
+
36
+ async def run_bench_async(
37
+ router: NeuroRoute,
38
+ csv_path: Path,
39
+ *,
40
+ budget: float | None = None,
41
+ limit: int | None = None,
42
+ provider: Any | None = None,
43
+ ) -> list[dict[str, Any]]:
44
+ rows = _read_prompts(csv_path)
45
+ if limit is not None:
46
+ rows = rows[: max(0, int(limit))]
47
+ out: list[dict[str, Any]] = []
48
+ for row in rows:
49
+ result = await router.arun(
50
+ row["prompt"], budget=budget, provider=provider, query_id=row["id"]
51
+ )
52
+ out.append(
53
+ {
54
+ "id": row["id"],
55
+ "prompt": row["prompt"],
56
+ "answer": result.answer,
57
+ "route": result.route,
58
+ "cost": result.cost,
59
+ "latency_ms": result.latency_ms,
60
+ "confidence": result.confidence,
61
+ "reason": result.reason,
62
+ }
63
+ )
64
+ return out
65
+
66
+
67
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ with path.open("w", encoding="utf-8") as f:
70
+ for row in rows:
71
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
@@ -0,0 +1,206 @@
1
+ """CLI: neuroroute init | serve | bench | train (Phase 16.4–16.6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ import sys
9
+ from importlib import resources
10
+ from pathlib import Path
11
+
12
+
13
+ def _build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="neuroroute",
16
+ description="NeuroRoute — route each request to the right model tier.",
17
+ )
18
+ sub = parser.add_subparsers(dest="command")
19
+
20
+ init = sub.add_parser("init", help="Write a starter neuroroute.yaml")
21
+ init.add_argument(
22
+ "--force",
23
+ action="store_true",
24
+ help="Overwrite existing neuroroute.yaml",
25
+ )
26
+ init.add_argument(
27
+ "--path",
28
+ default="neuroroute.yaml",
29
+ help="Output path (default: ./neuroroute.yaml)",
30
+ )
31
+
32
+ serve = sub.add_parser(
33
+ "serve",
34
+ help="Run OpenAI-compatible server (POST /v1/chat/completions)",
35
+ )
36
+ serve.add_argument(
37
+ "--config",
38
+ "-c",
39
+ default="neuroroute.yaml",
40
+ help="Path to neuroroute.yaml",
41
+ )
42
+ serve.add_argument("--host", default="127.0.0.1")
43
+ serve.add_argument("--port", type=int, default=8080)
44
+ serve.add_argument("--reload", action="store_true")
45
+
46
+ bench = sub.add_parser("bench", help="Run prompts from a CSV test set")
47
+ bench.add_argument("csv", help="CSV with a prompt/text column")
48
+ bench.add_argument(
49
+ "--config",
50
+ "-c",
51
+ default="neuroroute.yaml",
52
+ help="Path to neuroroute.yaml",
53
+ )
54
+ bench.add_argument(
55
+ "--out",
56
+ "-o",
57
+ default="bench_results.jsonl",
58
+ help="JSONL output path",
59
+ )
60
+ bench.add_argument("--budget", type=float, default=None)
61
+ bench.add_argument("--limit", type=int, default=None)
62
+
63
+ train = sub.add_parser(
64
+ "train",
65
+ help="Retrain difficulty classifier from labeled CSV",
66
+ )
67
+ train.add_argument(
68
+ "csv",
69
+ help="CSV with prompt + small_correct (yes/no) or hard (0/1)",
70
+ )
71
+ train.add_argument(
72
+ "--out",
73
+ default="artifacts/difficulty_clf.joblib",
74
+ help="Output classifier path",
75
+ )
76
+ return parser
77
+
78
+
79
+ def main(argv: list[str] | None = None) -> int:
80
+ parser = _build_parser()
81
+ args = parser.parse_args(argv)
82
+
83
+ if args.command is None:
84
+ parser.print_help()
85
+ return 0
86
+ if args.command == "init":
87
+ return _cmd_init(args)
88
+ if args.command == "serve":
89
+ return _cmd_serve(args)
90
+ if args.command == "bench":
91
+ return _cmd_bench(args)
92
+ if args.command == "train":
93
+ return _cmd_train(args)
94
+
95
+ parser.error(f"unknown command: {args.command}")
96
+ return 2
97
+
98
+
99
+ def _cmd_init(args: argparse.Namespace) -> int:
100
+ dest = Path(args.path).expanduser()
101
+ if dest.exists() and not args.force:
102
+ print(f"already exists: {dest} (use --force to overwrite)", file=sys.stderr)
103
+ return 1
104
+ dest.parent.mkdir(parents=True, exist_ok=True)
105
+ try:
106
+ template = resources.files("neuroroute").joinpath(
107
+ "templates/neuroroute.yaml"
108
+ )
109
+ data = template.read_text(encoding="utf-8")
110
+ except Exception:
111
+ # Fallback when package data is missing
112
+ fallback = (
113
+ Path(__file__).resolve().parent / "templates" / "neuroroute.yaml"
114
+ )
115
+ data = fallback.read_text(encoding="utf-8")
116
+ dest.write_text(data, encoding="utf-8")
117
+ print(f"wrote {dest.resolve()}")
118
+ print("Next: set API keys in the env vars named by api_key_env, then:")
119
+ print(f" neuroroute serve --config {dest}")
120
+ return 0
121
+
122
+
123
+ def _cmd_serve(args: argparse.Namespace) -> int:
124
+ config_path = Path(args.config).expanduser()
125
+ if not config_path.exists():
126
+ print(f"config not found: {config_path}", file=sys.stderr)
127
+ print("hint: run `neuroroute init` first", file=sys.stderr)
128
+ return 1
129
+
130
+ try:
131
+ import uvicorn
132
+ except ImportError:
133
+ print(
134
+ "Missing server deps. Install with: pip install 'neuroroute[server]'",
135
+ file=sys.stderr,
136
+ )
137
+ return 1
138
+
139
+ from neuroroute.openai_server import create_openai_app
140
+ from neuroroute.router import NeuroRoute
141
+
142
+ router = NeuroRoute.from_config(config_path)
143
+ app = create_openai_app(router=router)
144
+
145
+ print(
146
+ f"NeuroRoute OpenAI server on http://{args.host}:{args.port}\n"
147
+ f" POST /v1/chat/completions model=neuroroute|neuroroute-budget-0.3\n"
148
+ f" POST /feedback request_id + rating good|bad\n"
149
+ f" config: {config_path.resolve()}"
150
+ )
151
+ uvicorn.run(app, host=args.host, port=int(args.port), reload=bool(args.reload))
152
+ return 0
153
+
154
+
155
+ def _cmd_bench(args: argparse.Namespace) -> int:
156
+ from neuroroute.bench import run_bench_async, write_jsonl
157
+ from neuroroute.router import NeuroRoute
158
+
159
+ config_path = Path(args.config).expanduser()
160
+ csv_path = Path(args.csv).expanduser()
161
+ out_path = Path(args.out).expanduser()
162
+ if not config_path.exists():
163
+ print(f"config not found: {config_path}", file=sys.stderr)
164
+ return 1
165
+ if not csv_path.exists():
166
+ print(f"csv not found: {csv_path}", file=sys.stderr)
167
+ return 1
168
+
169
+ router = NeuroRoute.from_config(config_path)
170
+ rows = asyncio.run(
171
+ run_bench_async(
172
+ router,
173
+ csv_path,
174
+ budget=args.budget,
175
+ limit=args.limit,
176
+ )
177
+ )
178
+ write_jsonl(out_path, rows)
179
+ mean_cost = sum(r["cost"] for r in rows) / max(len(rows), 1)
180
+ print(json.dumps({"n": len(rows), "mean_cost": mean_cost, "out": str(out_path)}))
181
+ return 0
182
+
183
+
184
+ def _cmd_train(args: argparse.Namespace) -> int:
185
+ from neuroroute.train_cli import train_from_csv
186
+
187
+ csv_path = Path(args.csv).expanduser()
188
+ out_path = Path(args.out).expanduser()
189
+ if not csv_path.exists():
190
+ print(f"csv not found: {csv_path}", file=sys.stderr)
191
+ return 1
192
+ try:
193
+ report = train_from_csv(csv_path, out_path=out_path)
194
+ except Exception as exc:
195
+ print(f"train failed: {exc}", file=sys.stderr)
196
+ return 1
197
+ print(json.dumps(report, indent=2))
198
+ print(
199
+ f"Load it via classifier_path: {out_path} in neuroroute.yaml",
200
+ file=sys.stderr,
201
+ )
202
+ return 0
203
+
204
+
205
+ if __name__ == "__main__":
206
+ raise SystemExit(main())
@@ -0,0 +1,191 @@
1
+ """Load Phase-16 package config — unified YAML or legacy path pointers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+ from neuroroute._compat import backend_root, ensure_backend_on_path
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class PackageConfig:
16
+ path: Path
17
+ default_budget: float = 1.0
18
+ log_path: Path | None = None
19
+ unified: bool = False
20
+ raw: dict[str, Any] = field(default_factory=dict)
21
+ # Legacy path mode (still supported)
22
+ tiers_path: Path | None = None
23
+ confidence_path: Path | None = None
24
+ policy_path: Path | None = None
25
+ risk_keywords: list[str] = field(default_factory=list)
26
+ risk_keywords_replace: bool = False
27
+
28
+
29
+ def _resolve(base: Path, raw: str | Path | None, fallback: Path) -> Path:
30
+ if raw is None or str(raw).strip() == "":
31
+ return fallback
32
+ p = Path(raw)
33
+ if p.is_absolute():
34
+ return p
35
+ cand = (base / p).resolve()
36
+ if cand.exists():
37
+ return cand
38
+ return (backend_root() / p).resolve()
39
+
40
+
41
+ def _looks_unified(raw: dict[str, Any]) -> bool:
42
+ tiers = raw.get("tiers")
43
+ if not isinstance(tiers, dict) or not tiers:
44
+ return False
45
+ # Unified files define models inline; legacy neuroroute.yaml only has *_path keys.
46
+ sample = next(iter(tiers.values()))
47
+ return isinstance(sample, dict) and "model" in sample
48
+
49
+
50
+ def load_package_config(path: str | Path) -> PackageConfig:
51
+ cfg_path = Path(path).expanduser().resolve()
52
+ if not cfg_path.exists():
53
+ raise FileNotFoundError(f"config not found: {cfg_path}")
54
+
55
+ with cfg_path.open(encoding="utf-8") as f:
56
+ raw: dict[str, Any] = yaml.safe_load(f) or {}
57
+
58
+ base = cfg_path.parent
59
+ default_tiers = backend_root() / "config" / "tiers.yaml"
60
+ default_conf = backend_root() / "config" / "confidence.yaml"
61
+ default_policy = backend_root() / "config" / "policy.yaml"
62
+
63
+ log_raw = raw.get("log_path")
64
+ log_path = None
65
+ if log_raw:
66
+ lp = Path(str(log_raw))
67
+ log_path = lp if lp.is_absolute() else (base / lp).resolve()
68
+
69
+ keywords = [str(k) for k in (raw.get("risk_keywords") or []) if str(k).strip()]
70
+
71
+ if _looks_unified(raw):
72
+ return PackageConfig(
73
+ path=cfg_path,
74
+ default_budget=float(raw.get("default_budget", 1.0)),
75
+ log_path=log_path,
76
+ unified=True,
77
+ raw=raw,
78
+ risk_keywords=keywords,
79
+ risk_keywords_replace=bool(raw.get("risk_keywords_replace", False)),
80
+ )
81
+
82
+ # Legacy: pointers to split YAML files (or a bare tiers.yaml).
83
+ if "tiers" in raw and "tiers_path" not in raw and not _looks_unified(raw):
84
+ tiers_path = cfg_path
85
+ else:
86
+ tiers_path = _resolve(base, raw.get("tiers_path"), default_tiers)
87
+
88
+ return PackageConfig(
89
+ path=cfg_path,
90
+ default_budget=float(raw.get("default_budget", 1.0)),
91
+ log_path=log_path,
92
+ unified=False,
93
+ raw=raw,
94
+ tiers_path=tiers_path,
95
+ confidence_path=_resolve(base, raw.get("confidence_path"), default_conf),
96
+ policy_path=_resolve(base, raw.get("policy_path"), default_policy),
97
+ risk_keywords=keywords,
98
+ risk_keywords_replace=bool(raw.get("risk_keywords_replace", False)),
99
+ )
100
+
101
+
102
+ def apply_package_config(pkg: PackageConfig) -> Any:
103
+ """Push package YAML into the live brain singletons. Returns ConfidenceConfig."""
104
+ ensure_backend_on_path()
105
+
106
+ from app.confidence.combine import (
107
+ get_confidence_config,
108
+ load_confidence_config_from_mapping,
109
+ set_confidence_config,
110
+ )
111
+ from app.estimator.risk import set_risk_keywords
112
+ from app.models.config import (
113
+ get_config,
114
+ load_config_from_mapping,
115
+ set_config,
116
+ )
117
+ from app.models.wrapper import configure_provider_api_key_envs
118
+ from app.planner.policy import get_policy, load_policy_from_mapping, set_policy
119
+
120
+ if pkg.unified:
121
+ model_cfg = load_config_from_mapping(pkg.raw)
122
+ set_config(model_cfg)
123
+
124
+ conf_raw = pkg.raw.get("confidence")
125
+ if isinstance(conf_raw, dict):
126
+ conf = load_confidence_config_from_mapping(conf_raw)
127
+ else:
128
+ conf = get_confidence_config(
129
+ backend_root() / "config" / "confidence.yaml", reload=True
130
+ )
131
+ set_confidence_config(conf)
132
+
133
+ default_policy_path = backend_root() / "config" / "policy.yaml"
134
+ with default_policy_path.open(encoding="utf-8") as f:
135
+ default_policy = yaml.safe_load(f) or {}
136
+ if pkg.raw.get("rules") or pkg.raw.get("thresholds"):
137
+ policy_raw = {
138
+ "thresholds": pkg.raw.get("thresholds")
139
+ or default_policy.get("thresholds")
140
+ or {},
141
+ "rules": pkg.raw.get("rules") or default_policy.get("rules") or [],
142
+ }
143
+ set_policy(load_policy_from_mapping(policy_raw))
144
+ else:
145
+ get_policy(default_policy_path, reload=True)
146
+ else:
147
+ assert pkg.tiers_path and pkg.policy_path and pkg.confidence_path
148
+ get_config(pkg.tiers_path, reload=True)
149
+ get_policy(pkg.policy_path, reload=True)
150
+ conf = get_confidence_config(pkg.confidence_path, reload=True)
151
+ set_confidence_config(conf)
152
+
153
+ # Provider API key env vars from tier.api_key_env (YAML never holds secrets).
154
+ from app.models.config import get_config as _gc
155
+
156
+ live = _gc()
157
+ provider_envs: dict[str, str] = {}
158
+ for tier in live.tiers.values():
159
+ if not tier.api_key_env:
160
+ continue
161
+ model = tier.model or ""
162
+ provider = model.split("/", 1)[0] if "/" in model else "openai"
163
+ provider_envs[provider] = tier.api_key_env
164
+ configure_provider_api_key_envs(provider_envs)
165
+
166
+ set_risk_keywords(
167
+ pkg.risk_keywords or None,
168
+ replace=pkg.risk_keywords_replace,
169
+ )
170
+
171
+ if pkg.log_path is not None:
172
+ import os
173
+
174
+ os.environ["NEUROROUTE_DB"] = str(pkg.log_path)
175
+ from app.logging.store import get_store
176
+
177
+ get_store(pkg.log_path, reload=True)
178
+
179
+ classifier_raw = pkg.raw.get("classifier_path")
180
+ if classifier_raw:
181
+ clf_path = Path(str(classifier_raw))
182
+ if not clf_path.is_absolute():
183
+ cand = (pkg.path.parent / clf_path).resolve()
184
+ clf_path = cand if cand.exists() else (backend_root() / clf_path).resolve()
185
+ from app.estimator.estimator import load_estimator
186
+
187
+ load_estimator(clf_path)
188
+
189
+ from app.confidence.combine import get_confidence_config as _gconf
190
+
191
+ return _gconf()