laya-router 0.1.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 (38) hide show
  1. laya_router-0.1.0/.dockerignore +12 -0
  2. laya_router-0.1.0/.github/workflows/ci.yml +17 -0
  3. laya_router-0.1.0/.github/workflows/publish.yml +34 -0
  4. laya_router-0.1.0/.gitignore +18 -0
  5. laya_router-0.1.0/Dockerfile +19 -0
  6. laya_router-0.1.0/LICENSE +201 -0
  7. laya_router-0.1.0/Makefile +35 -0
  8. laya_router-0.1.0/PKG-INFO +290 -0
  9. laya_router-0.1.0/README.md +258 -0
  10. laya_router-0.1.0/backtest/analyze.py +104 -0
  11. laya_router-0.1.0/backtest/bench_latency.py +57 -0
  12. laya_router-0.1.0/backtest/build_dataset.py +132 -0
  13. laya_router-0.1.0/backtest/dataset.jsonl +180 -0
  14. laya_router-0.1.0/backtest/judge.py +172 -0
  15. laya_router-0.1.0/backtest/judgements.jsonl +180 -0
  16. laya_router-0.1.0/backtest/results.jsonl +180 -0
  17. laya_router-0.1.0/backtest/run_backtest.py +160 -0
  18. laya_router-0.1.0/backtest/tiers.glm.yaml +16 -0
  19. laya_router-0.1.0/examples/quickstart.py +15 -0
  20. laya_router-0.1.0/examples/streaming.py +24 -0
  21. laya_router-0.1.0/pyproject.toml +58 -0
  22. laya_router-0.1.0/src/laya_router/__init__.py +3 -0
  23. laya_router-0.1.0/src/laya_router/config.py +74 -0
  24. laya_router-0.1.0/src/laya_router/observability.py +67 -0
  25. laya_router-0.1.0/src/laya_router/policy.py +55 -0
  26. laya_router-0.1.0/src/laya_router/routing.py +64 -0
  27. laya_router-0.1.0/src/laya_router/server.py +295 -0
  28. laya_router-0.1.0/src/laya_router/tiers.yaml +14 -0
  29. laya_router-0.1.0/tests/conftest.py +57 -0
  30. laya_router-0.1.0/tests/test_backtest.py +248 -0
  31. laya_router-0.1.0/tests/test_config.py +47 -0
  32. laya_router-0.1.0/tests/test_e2e_openai_sdk.py +129 -0
  33. laya_router-0.1.0/tests/test_observability.py +177 -0
  34. laya_router-0.1.0/tests/test_policy.py +57 -0
  35. laya_router-0.1.0/tests/test_routing.py +76 -0
  36. laya_router-0.1.0/tests/test_server.py +470 -0
  37. laya_router-0.1.0/tests/test_slow_real_laya.py +29 -0
  38. laya_router-0.1.0/tests/test_smoke.py +5 -0
@@ -0,0 +1,12 @@
1
+ .git
2
+ .venv
3
+ venv
4
+ __pycache__
5
+ *.py[cod]
6
+ .pytest_cache
7
+ dist
8
+ build
9
+ tests
10
+ examples
11
+ .github
12
+ dist_tmp
@@ -0,0 +1,17 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.11"
16
+ - run: python -m pip install -e ".[dev]"
17
+ - run: python -m pytest -q
@@ -0,0 +1,34 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.11"
16
+ - run: python -m pip install build
17
+ - run: python -m build
18
+ - uses: actions/upload-artifact@v4
19
+ with:
20
+ name: dist
21
+ path: dist/
22
+
23
+ publish:
24
+ needs: build
25
+ runs-on: ubuntu-latest
26
+ environment: pypi
27
+ permissions:
28
+ id-token: write # OIDC for PyPI trusted publishing
29
+ steps:
30
+ - uses: actions/download-artifact@v4
31
+ with:
32
+ name: dist
33
+ path: dist/
34
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,18 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ .pytest_cache/
9
+ .coverage
10
+ htmlcov/
11
+ .mypy_cache/
12
+ .ruff_cache/
13
+ .env
14
+ .env.*
15
+ !.env.example
16
+ *.onnx
17
+ .DS_Store
18
+ Thumbs.db
@@ -0,0 +1,19 @@
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY pyproject.toml README.md LICENSE ./
6
+ COPY src ./src
7
+
8
+ RUN pip install --no-cache-dir .
9
+
10
+ EXPOSE 8000
11
+
12
+ # laya downloads its checkpoints on the first routing decision; persist the
13
+ # download cache so container restarts do not re-download it.
14
+ VOLUME ["/root/.cache"]
15
+
16
+ # Override at runtime with -e LAYA_ROUTER_* (see README) as needed.
17
+ ENV LAYA_ROUTER_UPSTREAM_BASE_URL=https://api.openai.com/v1
18
+
19
+ CMD ["uvicorn", "laya_router.server:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The laya-router Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,35 @@
1
+ .PHONY: test test-slow backtest backtest-glm bench dataset judge analyze
2
+
3
+ test:
4
+ python -m pytest -q
5
+
6
+ test-slow:
7
+ python -m pytest -m slow -q
8
+
9
+ # Full reproducible backtest: dataset -> both-tier answers -> blind judge -> table.
10
+ # Requires OPENAI_API_KEY (and optionally OPENAI_BASE_URL); budget ~5-10 USD on OpenAI.
11
+ backtest: dataset
12
+ python backtest/run_backtest.py
13
+ python backtest/judge.py
14
+ python backtest/analyze.py
15
+
16
+ # Same pipeline on Z.ai (GLM): glm-4.5-flash is free, so the run only pays
17
+ # for frontier answers and judge calls. Needs OPENAI_API_KEY set to a Z.ai key.
18
+ backtest-glm: dataset
19
+ OPENAI_BASE_URL=https://api.z.ai/api/paas/v4 \
20
+ python backtest/run_backtest.py --tiers backtest/tiers.glm.yaml
21
+ OPENAI_BASE_URL=https://api.z.ai/api/paas/v4 \
22
+ python backtest/judge.py --tiers backtest/tiers.glm.yaml
23
+ python backtest/analyze.py
24
+
25
+ bench:
26
+ python backtest/bench_latency.py
27
+
28
+ dataset:
29
+ python backtest/build_dataset.py --with-lmsys
30
+
31
+ judge:
32
+ python backtest/judge.py
33
+
34
+ analyze:
35
+ python backtest/analyze.py
@@ -0,0 +1,290 @@
1
+ Metadata-Version: 2.5
2
+ Name: laya-router
3
+ Version: 0.1.0
4
+ Summary: OpenAI-compatible proxy that routes prompts to cheap or frontier LLMs using a local System 1 decision model (laya)
5
+ Project-URL: Homepage, https://github.com/Gjusev/laya-router
6
+ Project-URL: Issues, https://github.com/Gjusev/laya-router/issues
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: cost-optimization,laya,llm-routing,openai-api,proxy,system-one
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: fastapi>=0.110
20
+ Requires-Dist: httpx>=0.27
21
+ Requires-Dist: laya>=0.3
22
+ Requires-Dist: prometheus-client>=0.20
23
+ Requires-Dist: pydantic-settings>=2.2
24
+ Requires-Dist: pydantic>=2.7
25
+ Requires-Dist: pyyaml>=6.0
26
+ Requires-Dist: uvicorn[standard]>=0.29
27
+ Provides-Extra: dev
28
+ Requires-Dist: openai>=1.30; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: respx>=0.21; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # laya-router
34
+
35
+ > OpenAI-compatible proxy that routes every prompt to a cheap or a frontier model using a local System 1 decision model.
36
+
37
+ [![CI](https://github.com/Gjusev/laya-router/actions/workflows/ci.yml/badge.svg)](https://github.com/Gjusev/laya-router/actions/workflows/ci.yml)
38
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
39
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
40
+
41
+ Point your OpenAI SDK `base_url` at the proxy and change **nothing else**. A local [laya](https://github.com/NandhaKishorM/laya) model decides, per prompt, whether it deserves the frontier model or the cheap one — every routing decision runs on your machine and costs $0 in API terms.
42
+
43
+ Built on [laya](https://github.com/NandhaKishorM/laya), the open-source System 1 decision engine (Apache 2.0).
44
+
45
+ ## Contents
46
+
47
+ - [How it works](#how-it-works)
48
+ - [Quickstart](#quickstart)
49
+ - [Routing behavior](#routing-behavior)
50
+ - [API compatibility](#api-compatibility)
51
+ - [Configuration](#configuration)
52
+ - [Operations](#operations)
53
+ - [Backtest (reproducible)](#backtest-reproducible)
54
+ - [Limitations](#limitations)
55
+ - [Development](#development)
56
+ - [Roadmap](#roadmap)
57
+ - [License](#license)
58
+
59
+ ## How it works
60
+
61
+ ```
62
+ OpenAI SDK / curl / any client
63
+ │ (base_url = http://127.0.0.1:8000/v1)
64
+ ▼
65
+ ┌─────────────────────── laya-router (FastAPI) ───────────────────────┐
66
+ │ 1. Fast path (regex, ~0 ms) ─────────────────────────────► cheap │
67
+ │ 2. laya Router (local, one forward pass) → complexity + confidence │
68
+ │ 3. Policy: complex OR low-confidence → frontier; else → cheap │
69
+ │ 4. httpx → upstream (SSE passthrough when stream=true) │
70
+ │ 5. Observability: X-Laya-* headers, /metrics, JSONL decision log │
71
+ └─────────────────────────────────────────────────────────────────────┘
72
+ ```
73
+
74
+ The client's `model` field is ignored — the router picks the model. Everything else in the request body (temperature, tools, `max_tokens`, …) is forwarded byte-exact.
75
+
76
+ ## Quickstart
77
+
78
+ The proxy speaks the OpenAI API and forwards to any OpenAI-compatible upstream (default: `https://api.openai.com/v1`).
79
+
80
+ **Option A — pip** (PyPI release pending; install from git for now):
81
+
82
+ ```bash
83
+ pip install git+https://github.com/Gjusev/laya-router.git
84
+ export LAYA_ROUTER_UPSTREAM_API_KEY=sk-... # or forward client keys, see Configuration
85
+ laya-router # serves http://127.0.0.1:8000/v1
86
+ ```
87
+
88
+ **Option B — Docker:**
89
+
90
+ ```bash
91
+ docker build -t laya-router .
92
+ docker run -p 8000:8000 -e LAYA_ROUTER_UPSTREAM_API_KEY=sk-... laya-router
93
+ ```
94
+
95
+ **Option C — from source** (Python 3.10+, [uv](https://docs.astral.sh/uv/)):
96
+
97
+ ```bash
98
+ git clone https://github.com/Gjusev/laya-router.git && cd laya-router
99
+ uv venv && uv pip install -e ".[dev]"
100
+ uv run laya-router
101
+ ```
102
+
103
+ Then adopt it in two lines — the stock OpenAI client, only `base_url` changes:
104
+
105
+ ```python
106
+ from openai import OpenAI
107
+
108
+ client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="sk-...")
109
+ completion = client.chat.completions.create(
110
+ model="ignored-by-proxy",
111
+ messages=[{"role": "user", "content": "Say hi in three words"}],
112
+ )
113
+ print(completion.model, "->", completion.choices[0].message.content)
114
+ ```
115
+
116
+ Or with curl:
117
+
118
+ ```console
119
+ $ curl -s http://127.0.0.1:8000/v1/chat/completions \
120
+ -H "Authorization: Bearer sk-..." -H "Content-Type: application/json" \
121
+ -d '{"model":"ignored","messages":[{"role":"user","content":"Say hi"}]}' -i
122
+ HTTP/1.1 200 OK
123
+ x-laya-route: cheap
124
+ x-laya-model: gpt-4o-mini
125
+ x-laya-confidence: 0.8957
126
+ x-laya-reason: complexity=simple
127
+ content-type: application/json
128
+ ...
129
+ ```
130
+
131
+ More runnable examples: [`examples/quickstart.py`](examples/quickstart.py) and [`examples/streaming.py`](examples/streaming.py).
132
+
133
+ > **First request is slow by design:** laya loads its decision checkpoints once (~10 s cold start on CPU; kept warm afterwards). Warm routing decisions measured on this project's benchmark run (AMD64 CPU, 179 prompts, [`backtest/bench_latency.py`](backtest/bench_latency.py)): p50 460 ms, p95 1.4 s, p99 2.7 s — free in API cost, not in latency; run the proxy next to your workload if you are latency-sensitive.
134
+
135
+ ## Routing behavior
136
+
137
+ Three layers, cheapest first:
138
+
139
+ 1. **Fast path** — greetings and other zero-content prompts match a regex and go straight to the cheap tier without invoking the model at all (`x-laya-reason: fast-path:trivial`).
140
+ 2. **laya decision** — one local forward pass classifies the prompt (`simple` / `standard` / `complex`) with a calibrated confidence.
141
+ 3. **Confidence gate** — if `answer_confidence` is below `LAYA_ROUTER_MIN_CONFIDENCE`, the request escalates to frontier (reason gains `+low-confidence`). Unknown complexity labels also escalate: spend more rather than risk quality.
142
+
143
+ Response headers on every request:
144
+
145
+ | Header | Meaning |
146
+ |---|---|
147
+ | `X-Laya-Route` | Tier chosen: `cheap` or `frontier` |
148
+ | `X-Laya-Model` | Upstream model actually used |
149
+ | `X-Laya-Confidence` | laya's calibrated confidence for the decision (1.0 on the fast path) |
150
+ | `X-Laya-Reason` | Decision trace: `complexity=…`, `+low-confidence`, or `fast-path:trivial` |
151
+
152
+ ## API compatibility
153
+
154
+ | Surface | Status |
155
+ |---|---|
156
+ | `POST /v1/chat/completions` (non-streaming) | ✅ Full passthrough, only `model` swapped |
157
+ | `POST /v1/chat/completions` (`stream: true`) | ✅ SSE relayed as it arrives |
158
+ | Tool calls / JSON mode / other body fields | ⚙️ Forwarded untouched (passthrough should carry them; not yet covered by tests) |
159
+ | `GET /healthz`, `GET /metrics` | ✅ Operational endpoints (proxy-specific) |
160
+ | `/v1/embeddings`, `/v1/models`, other endpoints | ❌ Out of scope for v1 — see [Roadmap](#roadmap) |
161
+
162
+ Out of scope for v1 (by design): embeddings, formally supported tool-calls, multi-tenant key management, admin UI.
163
+
164
+ ## Configuration
165
+
166
+ All settings come from `LAYA_ROUTER_*` environment variables (or a `.env` file):
167
+
168
+ | Variable | Default | Meaning |
169
+ |---|---|---|
170
+ | `LAYA_ROUTER_UPSTREAM_BASE_URL` | `https://api.openai.com/v1` | Any OpenAI-compatible API (vLLM, Ollama, OpenRouter, …) |
171
+ | `LAYA_ROUTER_UPSTREAM_API_KEY` | unset | When unset, each client's `Authorization` header is forwarded as-is |
172
+ | `LAYA_ROUTER_TIERS_FILE` | packaged `tiers.yaml` | Which model to use per tier, and list prices for cost estimation |
173
+ | `LAYA_ROUTER_UPSTREAM_TIMEOUT_S` | `120` | Upstream request timeout |
174
+ | `LAYA_ROUTER_MIN_CONFIDENCE` | `0.45` | Escalate below this confidence; `0` disables the gate (see the calibration sweep under Backtest) |
175
+ | `LAYA_ROUTER_DECISION_LOG` | unset | Path for the JSONL decision log (one line per request) |
176
+ | `LAYA_ROUTER_RATE_LIMIT_RPM` | `0` (off) | Per-client-IP requests per minute |
177
+
178
+ Tiers (packaged default, fully editable):
179
+
180
+ ```yaml
181
+ cheap:
182
+ model: gpt-4o-mini
183
+ price: {input_per_m: 0.15, output_per_m: 0.60}
184
+ frontier:
185
+ model: gpt-4o
186
+ price: {input_per_m: 2.50, output_per_m: 10.00}
187
+ ```
188
+
189
+ ## Operations
190
+
191
+ - **Liveness:** `GET /healthz` → `{"status": "ok"}`
192
+ - **Prometheus:** `GET /metrics` — `laya_router_requests_total{tier,status}` (including 400/429/503 degraded paths) and `laya_router_routing_seconds`
193
+ - **Decision log:** set `LAYA_ROUTER_DECISION_LOG` to record per-request JSONL: tier, model, complexity, confidence, reason, status, routing latency, and a truncated prompt preview
194
+ - **Rate limit:** `LAYA_ROUTER_RATE_LIMIT_RPM` returns OpenAI-shaped 429s with `Retry-After`
195
+
196
+ Degraded behavior is explicit: a failing routing engine yields a structured 503 (counted in metrics, logged), never a silent always-frontier fallback; upstream errors and non-JSON bodies pass through byte-exact with routing headers attached.
197
+
198
+ ## Backtest (reproducible)
199
+
200
+ The honest eval answers every prompt with **both** tiers, so routing mistakes are measurable, then a blind judge (fixed rubric, temperature 0, seeded A/B shuffle) compares the cheap answer against the frontier one. Definitions are published with the numbers: the router is *correct* when it routed cheap and the judge says win/tie, a *miss* when cheap loses, and *over-escalation* when it spent frontier money on a simple prompt.
201
+
202
+ ```bash
203
+ export OPENAI_API_KEY=sk-... # OpenAI budget: ~5-10 USD for 300 prompts x 2 tiers
204
+ make backtest # dataset -> both-tier answers -> blind judge -> table
205
+ ```
206
+
207
+ Cheaper: run the same pipeline on **Z.ai (GLM)** — this is how the published numbers below were produced:
208
+
209
+ ```bash
210
+ export OPENAI_API_KEY=<your-z.ai-key>
211
+ make backtest-glm # same eval, tiers from backtest/tiers.glm.yaml
212
+ ```
213
+
214
+ Any other OpenAI-compatible upstream works the same way: point `OPENAI_BASE_URL` at it and pass a matching `--tiers` file (or set `LAYA_ROUTER_TIERS_FILE`).
215
+
216
+ ### Measured results (first published run)
217
+
218
+ Dataset: 80 MT-Bench questions + 100 synthetic trivial prompts (the seeded LMSYS-Chat-1M sample is still pending — TODO). Tiers: `glm-5.3-flash` (cheap) vs `glm-5.3` (frontier), both at `reasoning_effort=low`, judge `glm-5.3`. Raw evidence: [`backtest/dataset.jsonl`](backtest/dataset.jsonl), [`backtest/results.jsonl`](backtest/results.jsonl), [`backtest/judgements.jsonl`](backtest/judgements.jsonl).
219
+
220
+ | Metric | Value |
221
+ |---|---|
222
+ | Prompts (both tiers answered) | 180 |
223
+ | % routed to cheap | 80.6% |
224
+ | Cost saving vs always-frontier | 54.9% |
225
+ | Win/tie/lose of cheap vs frontier (cheap-routed, judged) | 28 / 87 / 30 |
226
+ | Routing precision (cheap verdict win/tie) | 79.3% |
227
+ | Over-escalations (frontier, costly only) | 35 |
228
+ | Routing cost per 1,000 requests | $0 (local laya) |
229
+
230
+ Confidence-gate calibration (simulated offline from recorded per-prompt confidences):
231
+
232
+ | min_confidence | % cheap | cost saving | misses | precision |
233
+ |---|---|---|---|---|
234
+ | 0.0 (off) | 80.6% | 54.9% | 30 | 79.3% |
235
+ | 0.45 (default) | ~72% | ~46% | ~27 | ~79% |
236
+ | 0.55 | 53.3% | 30.0% | 21 | 78.1% |
237
+ | 0.70 | 27.2% | 10.4% | 10 | 79.6% |
238
+
239
+ Two honest findings from this run:
240
+
241
+ - **Misses are dominated by judge noise, not routing error.** On the 100 trivial prompts (near-identical answers), the judge scored cheap 16 wins and 17 losses — a symmetric noise floor. Roughly half of the 30 recorded misses are likely noise, not real quality losses.
242
+ - **The confidence gate buys little precision.** Precision stays flat (~79%) across the whole threshold range: raising the gate spends savings (~2 points per miss avoided) without improving correctness. The default (0.45) sits in the flat zone; cost-sensitive operators can disable it (`0`) and quality-sensitive ones can raise it.
243
+
244
+ ## Limitations
245
+
246
+ - Single-process by design: the rate limiter and metrics are in-memory (fine for one replica; a shared store would be needed for a fleet).
247
+ - The published backtest numbers come from one judge (`glm-5.3`) on one model pair (`glm-5.3-flash` vs `glm-5.3`); agreement with a second judge and results on other model pairs are not yet measured (TODO(measure)). The measured judge noise floor (~16% of trivial prompts scored non-tie) bounds the precision claims above.
248
+ - The laya classifier labeled 142/180 prompts "simple" and only 3 "standard" — the question set under-detects the middle band; tuning the custom questions is the next quality lever.
249
+ - The seeded LMSYS-Chat-1M sample (120 real user turns) is not yet in the dataset.
250
+ - Routing adds a one-time checkpoint load (~10 s) and a per-decision CPU cost (measured p50 460 ms / p99 2.7 s on AMD64 — reproducible via `make bench`); it pays for itself on the first avoided frontier call, not in added latency.
251
+ - Not on PyPI yet — install from git.
252
+
253
+ ## Development
254
+
255
+ ```bash
256
+ uv venv && uv pip install -e ".[dev]"
257
+ pytest # unit + integration; fully offline, no checkpoints downloaded
258
+ pytest -m slow # opt-in: real laya engine (downloads checkpoints on first use)
259
+ make backtest # full eval pipeline (needs an OpenAI budget)
260
+ ```
261
+
262
+ Project layout:
263
+
264
+ ```
265
+ src/laya_router/
266
+ server.py # FastAPI app: endpoint, rate limit, streaming relay
267
+ policy.py # fast paths, tier choice, confidence gate, RoutingDecision
268
+ routing.py # laya engine wrapper + the routing question set
269
+ config.py # settings (pydantic-settings) + tiers.yaml loader
270
+ observability.py # Prometheus metrics + JSONL decision log
271
+ backtest/ # dataset builder, both-tier runner, blind judge, analysis
272
+ examples/ # quickstart.py, streaming.py
273
+ tests/ # offline by default; @slow marks real-checkpoint tests
274
+ ```
275
+
276
+ Contributions welcome — open an issue first for anything non-trivial, keep commits conventional (`feat:`, `fix:`, `test:`, `docs:`, `chore:`), and all code/docs in English.
277
+
278
+ ## Roadmap
279
+
280
+ - [x] MVP: `POST /v1/chat/completions` (non-streaming) with laya-based tier routing
281
+ - [x] Streaming (SSE) passthrough
282
+ - [x] Confidence gating + deterministic fast paths
283
+ - [x] Observability: Prometheus `/metrics`, JSONL decision log, `/healthz`, Docker
284
+ - [x] Reproducible backtest harness (`make backtest`)
285
+ - [x] Published backtest numbers in the README (GLM pair; OpenAI-pair run pending)
286
+ - [ ] PyPI release
287
+
288
+ ## License
289
+
290
+ Apache 2.0. See [LICENSE](LICENSE).