feat: expose typed fev decisions and system one api
Browse files- API.md +74 -0
- CHANGES.md +10 -2
- README.md +77 -75
- RUNNING.md +8 -4
- examples/typed-request.json +20 -0
- fev4b/__init__.py +3 -2
- fev4b/decisions.py +112 -0
- fev4b/integrity.py +1 -1
- fev4b/model.py +15 -1
- fev4b/server.py +118 -0
- fev_config.json +1 -1
- manifest.json +48 -16
- provenance.json +4 -2
- requirements-serve.txt +1 -0
- requirements-test.txt +2 -0
- serve.py +30 -0
- tests/test_decisions.py +139 -0
API.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fev typed-decision API
|
| 2 |
+
|
| 3 |
+
The reference server exposes the text-only subset of the System One API. Choice, Noul and Score requests work with `typesafe-sdk[zstd]==0.7.5` using `base_url="http://127.0.0.1:8000"` and `model="fev-4b"`. No SDK patch is required. This is not an OpenAI chat-completions endpoint.
|
| 4 |
+
|
| 5 |
+
## Start
|
| 6 |
+
|
| 7 |
+
Download the full HF package as shown in README.md. Install `requirements.txt` and `requirements-serve.txt`, then run:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
.venv/bin/python serve.py --model-dir . --port 8000
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
One resident CUDA BF16 model serves requests sequentially. Startup verification hashes all bundled files. The first inference may take about 50 seconds for cold kernels; use a client timeout of at least 120 seconds. CPU and Apple Silicon are not supported by this reference loader.
|
| 14 |
+
|
| 15 |
+
For access beyond localhost, set `FEV_API_KEY` to a secret and pass `--host 0.0.0.0`. The server requires `Authorization: Bearer <secret>` on both endpoints when the variable is set. Put it behind your managed reverse proxy for TLS, admission control, rate limits and monitoring. It logs no request contents. This small server is an integration reference, not a qualified production serving stack.
|
| 16 |
+
|
| 17 |
+
## Request and response
|
| 18 |
+
|
| 19 |
+
`POST /v1/systemone`, `Content-Type: application/json`:
|
| 20 |
+
|
| 21 |
+
```json
|
| 22 |
+
{
|
| 23 |
+
"model": "fev-4b",
|
| 24 |
+
"state": "Мне дважды списали оплату.",
|
| 25 |
+
"questions": {
|
| 26 |
+
"billing": {"type": "noul", "instructions": "Это вопрос об оплате?"}
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Response shape (probabilities shown here are illustrative):
|
| 32 |
+
|
| 33 |
+
```json
|
| 34 |
+
{
|
| 35 |
+
"model": "fev-4b",
|
| 36 |
+
"answers": {"billing": {"type": "noul", "noul": 0.95}},
|
| 37 |
+
"usage": {"input_tokens": 100, "output_tokens": 0, "sequences": 1}
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
The state can be a string, JSON object or array. Instructions and option descriptions can also be strings, objects or arrays. All rules and category definitions come from the caller. Named answers preserve question IDs.
|
| 42 |
+
|
| 43 |
+
- `choice`: `criteria` maps 1–255 option names to descriptions (or null to use the name). Returns `choice`, `probabilities` and `confidence`.
|
| 44 |
+
- `noul`: optional `criteria` maps `true` and/or `false` to descriptions. Returns `noul`, the probability of yes.
|
| 45 |
+
- `score`: `criteria` lists 2–255 ordered level descriptions. Returns the expected zero-based level index in `score`, plus `legend`, `probabilities` and `confidence`. A score may lie between levels; it is not the most likely integer level.
|
| 46 |
+
|
| 47 |
+
See `examples/typed-request.json` for all three types in one request:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
curl http://127.0.0.1:8000/v1/systemone \
|
| 51 |
+
-H 'Content-Type: application/json' --data-binary @examples/typed-request.json
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Python without HTTP:
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
from fev4b import Fev4B
|
| 58 |
+
model = Fev4B("/path/to/downloaded/fev-4b")
|
| 59 |
+
result = model.decide({"state": "Нужен возврат денег", "questions": {
|
| 60 |
+
"refund": {"type": "noul", "instructions": "Клиент просит вернуть деньги?"}
|
| 61 |
+
}})
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
`GET /v1/models` returns the available model ID. Responses include `x-typesafe-request-id`.
|
| 65 |
+
|
| 66 |
+
## Limits and errors
|
| 67 |
+
|
| 68 |
+
1–64 questions, 16,384 encoded tokens for the complete joint sequence, 1 MiB JSON body before and after decompression, JSON nesting at most 32 levels. Oversized token requests are rejected before inference; no state or rules are truncated. Requests use one joint forward pass. Questions share attention and can influence one another.
|
| 69 |
+
|
| 70 |
+
Plain JSON and `Content-Encoding: zstd` are accepted. Images, assets, box questions, multipart bodies, transfer-encoded/chunked bodies and unknown fields are rejected. The Python SDK selects compatible JSON automatically for text-only questions. No outbound image fetching or external inference occurs.
|
| 71 |
+
|
| 72 |
+
Errors use an HTTP status and JSON `detail`: 401 for authentication, 404 for endpoints, 411 for missing length, 413 for body size, 415 for media/encoding, 422 for invalid schema or token length, and 500 for inference failure. No partial answers are returned.
|
| 73 |
+
|
| 74 |
+
The `confidence` field is a native distribution-derived statistic, not an independently measured probability of correctness. Set decision thresholds using evidence appropriate to your workload. API compatibility does not imply quality equivalence to other decision models.
|
CHANGES.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
| 1 |
# Release composition
|
| 2 |
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Release composition
|
| 2 |
|
| 3 |
+
## v0.2.0
|
| 4 |
|
| 5 |
+
Adds the text-only `Fev4B.decide` interface, a resident reference HTTP server for `POST /v1/systemone` and `GET /v1/models`, strict typed-request/response validation, zstd decoding, TypeSafe SDK contract checks, and public GitHub documentation. Choice, Noul and Score use the existing native decision head. No checkpoint, shared adapter, tokenizer, native source, temperature, precision, routing primitive or routing cutoff changed. The routing response version is now 0.2.0.
|
| 6 |
+
|
| 7 |
+
The package verifier accepts the v0.1.0 and v0.2.0 manifest formats. All files in the selected model package are still checked by size and SHA256. Version tags remain separate; v0.1.0 is retained unchanged.
|
| 8 |
+
|
| 9 |
+
## v0.1.0
|
| 10 |
+
|
| 11 |
+
Packages the complete decision checkpoint with a shared LoRA adapter, customer-agnostic routing composition, local loader, CLI, integrity checks, synthetic examples and release documentation. Checkpoint weights, tokenizer, readout, native source, license and notices are retained without modification.
|
| 12 |
+
|
| 13 |
+
The seven routing primitives are copied byte-for-byte from the frozen runtime used for the 303-case development measurement. Full ancestry and file hashes are in `provenance.json` and `manifest.json`.
|
README.md
CHANGED
|
@@ -16,86 +16,105 @@ tags:
|
|
| 16 |
|
| 17 |
## Model summary
|
| 18 |
|
| 19 |
-
|
| 20 |
|
| 21 |
-
Built on the Qwen3.5-4B architecture,
|
|
|
|
|
|
|
| 22 |
|
| 23 |
## Model details
|
| 24 |
|
| 25 |
-
|
|
| 26 |
|---|---|
|
| 27 |
-
| Developer | Flomni
|
| 28 |
-
|
|
| 29 |
-
|
|
|
|
|
| 30 |
| Precision | BF16 checkpoint and readout; FP32 adapter, unmerged |
|
| 31 |
-
|
|
| 32 |
-
|
|
| 33 |
-
|
|
| 34 |
-
|
|
| 35 |
| Reference hardware | NVIDIA A10G, 24 GB; CUDA BF16 |
|
| 36 |
-
| License | Apache-2.0; bundled notices
|
| 37 |
-
|
| 38 |
-
The context bound is an execution limit, not a claim of validated accuracy at every length. This is a complete custom Python package, not a standard text-generation checkpoint or a drop-in OpenAI endpoint.
|
| 39 |
|
| 40 |
-
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
| 47 |
|
| 48 |
## Intended uses
|
| 49 |
|
| 50 |
-
-
|
| 51 |
-
-
|
| 52 |
-
-
|
| 53 |
-
-
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
|
| 57 |
-
##
|
| 58 |
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
uvx --from huggingface-hub==1.31.0 hf download murabcd/fev-4b \
|
| 63 |
-
--revision v0.1.0 --local-dir Fev-4B
|
| 64 |
-
cd Fev-4B
|
| 65 |
-
python3 run.py --verify-only
|
| 66 |
-
```
|
| 67 |
|
| 68 |
-
On a Linux server with a compatible NVIDIA GPU and driver:
|
| 69 |
|
| 70 |
```bash
|
|
|
|
|
|
|
|
|
|
| 71 |
uv venv --python 3.12
|
| 72 |
-
uv pip install -r requirements.txt
|
| 73 |
-
.venv/bin/python run.py --
|
|
|
|
| 74 |
```
|
| 75 |
|
| 76 |
-
|
| 77 |
|
| 78 |
```python
|
| 79 |
-
import
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
model
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
```
|
| 87 |
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
|
| 90 |
## Training and release procedure
|
| 91 |
|
| 92 |
-
This release
|
| 93 |
|
| 94 |
-
|
| 95 |
|
| 96 |
## Evaluation
|
| 97 |
|
| 98 |
-
The
|
| 99 |
|
| 100 |
| Outcome | Cases |
|
| 101 |
|---|---:|
|
|
@@ -103,9 +122,9 @@ The unchanged candidate was measured over **303 development cases** using the fu
|
|
| 103 |
| Automatic route disagreement | 4 |
|
| 104 |
| Correct clarification | 35 |
|
| 105 |
| Unnecessary clarification | 6 |
|
| 106 |
-
| **
|
| 107 |
|
| 108 |
-
Five references have unresolved business mappings
|
| 109 |
|
| 110 |
| Development group | Agreement |
|
| 111 |
|---|---:|
|
|
@@ -115,41 +134,24 @@ Five references have unresolved business mappings. All four automatic disagreeme
|
|
| 115 |
| Generic decision checks | 98 / 100 |
|
| 116 |
| Runtime instruction switches | 32 / 32 |
|
| 117 |
|
| 118 |
-
There were 48 / 48 consistent route-order pairs and 16 / 16 instruction-switch pairs with both answers correct. Eight same-job native repeat checks had no numerical change. [Aggregate results](evaluation/summary.json)
|
| 119 |
|
| 120 |
-
These
|
| 121 |
|
| 122 |
## Compute and serving
|
| 123 |
|
| 124 |
-
The 303-case
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
The full public package was downloaded without authentication and loaded with Python network connections blocked. All file hashes passed, five synthetic smoke cases matched their expected decisions, and a same-job repeat passed. The packaged routing composition also reproduced all 303 saved development decisions without new inference. See [package verification](evaluation/packaging-verification.json). This checks release integrity and execution; it adds no independent accuracy evidence.
|
| 129 |
|
| 130 |
## Limitations
|
| 131 |
|
| 132 |
-
- Ambiguous or contradictory
|
| 133 |
-
- Missing history is not reconstructed. Runtime examples are
|
| 134 |
-
-
|
| 135 |
-
-
|
| 136 |
-
-
|
| 137 |
-
- This release provides inference code and weights. Authentication, request limits, monitoring, scenario execution and a serving API belong to the integrating application.
|
| 138 |
|
| 139 |
## License and reproducibility
|
| 140 |
|
| 141 |
-
Apache-2.0. Preserve [LICENSE](
|
| 142 |
-
|
| 143 |
-
## Citation
|
| 144 |
-
|
| 145 |
-
```bibtex
|
| 146 |
-
@misc{flomni2026fev4b,
|
| 147 |
-
title = {Fev-4B: Customer-Agnostic Conversation Routing},
|
| 148 |
-
author = {Flomni},
|
| 149 |
-
year = {2026},
|
| 150 |
-
howpublished = {\url{https://huggingface.co/murabcd/fev-4b}},
|
| 151 |
-
note = {Version 0.1.0}
|
| 152 |
-
}
|
| 153 |
-
```
|
| 154 |
-
|
| 155 |
-
Questions and issues: use this repository's Community tab.
|
|
|
|
| 16 |
|
| 17 |
## Model summary
|
| 18 |
|
| 19 |
+
Fev-4B is a decision model for classification, routing, triage and checks against supplied rules. Give it a document or conversation (the *state*) and named, typed questions. It returns option probabilities and structured decisions without generating text. Its text-decision server implements `POST /v1/systemone`, for use with the TypeSafe SDK through a custom base URL.
|
| 20 |
|
| 21 |
+
Built on the Qwen3.5-4B architecture, Fev combines a native decision readout with a shared LoRA adapter. Categories, business rules, examples and conversation history are supplied at runtime: customer-specific retraining is not required to change them. The package also includes a two-stage conversation router that can return a clarification signal when no route is sufficiently supported. Reference execution uses one 24 GB NVIDIA GPU.
|
| 22 |
+
|
| 23 |
+
This card describes Fev v0.2.0. The weights and routing policy are unchanged from v0.1.0; this version adds the public typed-decision interface and HTTP server.
|
| 24 |
|
| 25 |
## Model details
|
| 26 |
|
| 27 |
+
| | |
|
| 28 |
|---|---|
|
| 29 |
+
| Developer | Flomni ([github.com/murabcd/fev](https://github.com/murabcd/fev)) |
|
| 30 |
+
| Model type | Decision model: shared state and questions scored by a native readout; no text generation |
|
| 31 |
+
| Backbone | Qwen3.5-4B architecture; noncausal full attention |
|
| 32 |
+
| Adapter | Shared LoRA, rank 8, alpha 16; 10,387,456 parameters |
|
| 33 |
| Precision | BF16 checkpoint and readout; FP32 adapter, unmerged |
|
| 34 |
+
| Head | Native readout over question option codes; softmax probabilities |
|
| 35 |
+
| Context | 16,384 encoded tokens per native call, including state, questions and template; oversized requests rejected |
|
| 36 |
+
| Temperature | Fixed native temperature T = 1.5539092221462472; new-workload calibration has not been measured |
|
| 37 |
+
| Languages | Russian |
|
| 38 |
| Reference hardware | NVIDIA A10G, 24 GB; CUDA BF16 |
|
| 39 |
+
| License | Apache-2.0; bundled notices retained |
|
| 40 |
+
| Version | Fev v0.2.0; [versioned package](https://huggingface.co/murabcd/fev-4b/tree/v0.2.0) |
|
|
|
|
| 41 |
|
| 42 |
+
**Input.** Text, a JSON object or an array as the state, plus 1–64 named questions:
|
| 43 |
|
| 44 |
+
| Type | Options | Output |
|
| 45 |
+
|---|---|---|
|
| 46 |
+
| `choice` | 1–255 named options with optional descriptions | Probability per option, selected option and confidence |
|
| 47 |
+
| `score` | 2–255 ordered level descriptions | Probability per level, expected zero-based level index, legend and confidence |
|
| 48 |
+
| `noul` | Yes / no, with optional descriptions | Probability of yes |
|
| 49 |
|
| 50 |
+
A typed request is processed as one joint sequence in one forward pass. Questions share attention; they are not isolated from one another. The context limit is an execution bound, not a validated accuracy guarantee for long documents.
|
| 51 |
|
| 52 |
## Intended uses
|
| 53 |
|
| 54 |
+
- Classify or route messages using supplied category definitions and exclusions.
|
| 55 |
+
- Make yes/no checks against supplied requirements.
|
| 56 |
+
- Rate a state against an explicit ordered rubric.
|
| 57 |
+
- Keep business configuration outside model weights.
|
| 58 |
+
- Run conversation routing with explicit uncertainty handling.
|
| 59 |
|
| 60 |
+
The model returns decisions. The application owns follow-up questions, scenario execution and business actions. A clarification signal can continue automation; it does not require operator handoff.
|
| 61 |
|
| 62 |
+
## Out-of-scope uses
|
| 63 |
|
| 64 |
+
- Chat, summarisation, free-form answers or other text generation.
|
| 65 |
+
- Image assets, box questions and multipart requests through this API.
|
| 66 |
+
- Claims of production accuracy, calibrated probabilities on arbitrary workloads, or autonomous conversation resolution based only on this development benchmark.
|
| 67 |
+
- CPU, Apple Silicon, quantized or merged-adapter serving: these paths are not validated in this release.
|
| 68 |
|
| 69 |
+
## How to use
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
Download the complete versioned model package. On a Linux server with a compatible NVIDIA GPU and driver:
|
| 72 |
|
| 73 |
```bash
|
| 74 |
+
uvx --from huggingface-hub==1.31.0 hf download murabcd/fev-4b \
|
| 75 |
+
--revision v0.2.0 --local-dir fev-4b
|
| 76 |
+
cd fev-4b
|
| 77 |
uv venv --python 3.12
|
| 78 |
+
uv pip install -r requirements.txt -r requirements-serve.txt
|
| 79 |
+
.venv/bin/python run.py --verify-only
|
| 80 |
+
.venv/bin/python serve.py --port 8000
|
| 81 |
```
|
| 82 |
|
| 83 |
+
The server keeps one model resident. Its default address is localhost. Code, examples and integration instructions are also on [GitHub](https://github.com/murabcd/fev).
|
| 84 |
|
| 85 |
```python
|
| 86 |
+
from typesafe_sdk import Choice, Noul, TypeSafeClient
|
| 87 |
+
|
| 88 |
+
client = TypeSafeClient(
|
| 89 |
+
api_key="local", base_url="http://127.0.0.1:8000",
|
| 90 |
+
model="fev-4b", timeout=120,
|
| 91 |
+
)
|
| 92 |
+
response = client.system_one(
|
| 93 |
+
state="Мне дважды списали оплату. Верните лишнее списание.",
|
| 94 |
+
questions={
|
| 95 |
+
"team": Choice(
|
| 96 |
+
instructions="Кто должен обработать обращение?",
|
| 97 |
+
criteria={"billing": "Оплата и возврат денег", "delivery": "Доставка"},
|
| 98 |
+
),
|
| 99 |
+
"refund": Noul(instructions="Клиент просит вернуть деньги?"),
|
| 100 |
+
},
|
| 101 |
+
)
|
| 102 |
+
print(response.choices["team"].choice, response.nouls["refund"].noul)
|
| 103 |
```
|
| 104 |
|
| 105 |
+
Install the client with `pip install 'typesafe-sdk[zstd]==0.7.5'`. Text requests support plain JSON and zstd compression. The server exposes `GET /v1/models` and `POST /v1/systemone`. See [API.md](API.md) for limits, authentication, raw HTTP and Python usage.
|
| 106 |
+
|
| 107 |
+
For the conversation-routing policy, use `Fev4B.route(...)` or `run.py --input examples/request.json`; see [RUNNING.md](RUNNING.md). This policy makes a primary Choice call and, when applicable, a second call containing up to three route-applicability checks. It is distinct from a single native typed request.
|
| 108 |
|
| 109 |
## Training and release procedure
|
| 110 |
|
| 111 |
+
This release distributes a complete decision checkpoint, one shared adapter and inference code. The shared adapter comes from customer-agnostic synthetic decision research. No customer-specific adapter is selected at runtime, and no training was performed for the v0.2.0 interface release.
|
| 112 |
|
| 113 |
+
Checkpoint and adapter files retain their original precision and hashes. Exact ancestry, adapter hashes and changed-file boundaries are recorded in [provenance.json](provenance.json) and [CHANGES.md](CHANGES.md). This is an inference release, not a complete reproduction of historical training data or an independent audit of all upstream sources.
|
| 114 |
|
| 115 |
## Evaluation
|
| 116 |
|
| 117 |
+
The conversation-routing composition was measured on **303 development cases** with the full supplied business rules. Cases include synthetic and source-derived examples already consumed during development; this is not a fresh, independently human-labelled test set.
|
| 118 |
|
| 119 |
| Outcome | Cases |
|
| 120 |
|---|---:|
|
|
|
|
| 122 |
| Automatic route disagreement | 4 |
|
| 123 |
| Correct clarification | 35 |
|
| 124 |
| Unnecessary clarification | 6 |
|
| 125 |
+
| **Reference agreement** | **293 / 303 (96.7%)** |
|
| 126 |
|
| 127 |
+
Five references have unresolved business mappings, including all four automatic disagreements. Excluding those five gives 293 / 298 (98.3%). Both denominators are disclosed; the headline keeps the disputed cases.
|
| 128 |
|
| 129 |
| Development group | Agreement |
|
| 130 |
|---|---:|
|
|
|
|
| 134 |
| Generic decision checks | 98 / 100 |
|
| 135 |
| Runtime instruction switches | 32 / 32 |
|
| 136 |
|
| 137 |
+
There were 48 / 48 consistent route-order pairs and 16 / 16 instruction-switch pairs with both answers correct. Eight same-job native repeat checks had no numerical change. [Aggregate results](evaluation/summary.json) are included; customer records and configurations are excluded.
|
| 138 |
|
| 139 |
+
These results measure the routing composition. They do not establish general typed-task accuracy, unseen-customer generalization, resolved-conversation coverage or production readiness. API contract tests are separate from model-quality evaluation.
|
| 140 |
|
| 141 |
## Compute and serving
|
| 142 |
|
| 143 |
+
The sequential 303-case run on one A10G had a median model time of 613 ms and p95 of 2,442 ms, excluding download, model loading, network and queueing. The first case took 50.6 seconds including cold kernel initialization. Peak allocated GPU memory was 10.01 GB and reserved memory was 10.45 GB (decimal units).
|
| 144 |
|
| 145 |
+
The reference server serializes requests. Concurrent throughput, production cost and smaller hardware have not been qualified. After downloading the package and installing dependencies, inference uses local files and requires no Hub access or external inference provider. Use a reverse proxy for TLS, rate limits and production observability.
|
|
|
|
|
|
|
| 146 |
|
| 147 |
## Limitations
|
| 148 |
|
| 149 |
+
- Ambiguous or contradictory definitions can produce disagreement or excess clarification.
|
| 150 |
+
- Missing conversation history is not reconstructed. Runtime examples are not actual dialogue turns.
|
| 151 |
+
- The routing resolver supports a documented subset of explicit priority syntax, not arbitrary workflow DSL execution.
|
| 152 |
+
- Routing cutoffs of 0.8 / 0.2 are policy settings, not correctness guarantees. Probability calibration must be checked on the intended workload.
|
| 153 |
+
- Ordered-score quality and long-context accuracy have not been independently benchmarked.
|
|
|
|
| 154 |
|
| 155 |
## License and reproducibility
|
| 156 |
|
| 157 |
+
Apache-2.0. Preserve [LICENSE](LICENSE), [NOTICE](NOTICE) and bundled upstream notices. [manifest.json](manifest.json) records package hashes. Pin the `v0.2.0` tag or its commit when downloading. Weights are hosted on Hugging Face; source and usage examples are maintained on [GitHub](https://github.com/murabcd/fev).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RUNNING.md
CHANGED
|
@@ -9,11 +9,11 @@ CPU and MPS are deliberately rejected by this reference loader because they have
|
|
| 9 |
## Install and verify
|
| 10 |
|
| 11 |
```bash
|
| 12 |
-
uvx --from huggingface-hub==1.31.0 hf download murabcd/fev-4b --revision v0.
|
| 13 |
cd Fev-4B
|
| 14 |
python3 run.py --verify-only
|
| 15 |
uv venv --python 3.12
|
| 16 |
-
uv pip install -r requirements.txt
|
| 17 |
.venv/bin/python -m unittest discover -s tests -v
|
| 18 |
.venv/bin/python run.py --input examples/request.json
|
| 19 |
```
|
|
@@ -56,12 +56,16 @@ The preferred description must be A or B and each description must identify one
|
|
| 56 |
|
| 57 |
## Integration
|
| 58 |
|
| 59 |
-
Run one resident `Fev4B` instance in an isolated Python process and call `route` from your service. Calls within an instance are serialized. Multiple workers replicate the weights; budget VRAM accordingly. Concurrency and capacity have not been measured. Put authentication, TLS, request-size controls, timeouts and operational monitoring in your service.
|
| 60 |
|
| 61 |
Use a separate test application for integration. This release does not change any client workflow. After deploying a service in your own environment, connect its endpoint through the provider/API mechanism supported by your application; merely selecting a Hugging Face model ID does not start this custom runtime.
|
| 62 |
|
| 63 |
## Reproducibility and updates
|
| 64 |
|
| 65 |
-
Keep `v0.
|
| 66 |
|
| 67 |
Do not run with Python `-O`; native research invariants include assertions. This reference uses BF16 base/readout and FP32 unmerged adapter. Different precision, kernels, context, temperature, thresholds, wrapper logic or model merging require separate parity and quality verification. No training is run by the loader.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
## Install and verify
|
| 10 |
|
| 11 |
```bash
|
| 12 |
+
uvx --from huggingface-hub==1.31.0 hf download murabcd/fev-4b --revision v0.2.0 --local-dir Fev-4B
|
| 13 |
cd Fev-4B
|
| 14 |
python3 run.py --verify-only
|
| 15 |
uv venv --python 3.12
|
| 16 |
+
uv pip install -r requirements.txt -r requirements-test.txt
|
| 17 |
.venv/bin/python -m unittest discover -s tests -v
|
| 18 |
.venv/bin/python run.py --input examples/request.json
|
| 19 |
```
|
|
|
|
| 56 |
|
| 57 |
## Integration
|
| 58 |
|
| 59 |
+
Run one resident `Fev4B` instance in an isolated Python process and call `route` from your service. Calls within an instance are serialized. Multiple workers replicate the weights; budget VRAM accordingly. Concurrency and capacity have not been measured. Put authentication, TLS, request-size controls, timeouts and operational monitoring in your service. The loader does not start an endpoint automatically. Run `serve.py` explicitly for the text-only typed-decision API; see API.md.
|
| 60 |
|
| 61 |
Use a separate test application for integration. This release does not change any client workflow. After deploying a service in your own environment, connect its endpoint through the provider/API mechanism supported by your application; merely selecting a Hugging Face model ID does not start this custom runtime.
|
| 62 |
|
| 63 |
## Reproducibility and updates
|
| 64 |
|
| 65 |
+
Keep `v0.2.0` or the corresponding Hub commit pinned. The exact checkpoint, shared adapter and routing composition are recorded in `provenance.json`; every distributed file except `manifest.json` itself is hashed in the manifest. Hub download-cache metadata and Python bytecode are not release files.
|
| 66 |
|
| 67 |
Do not run with Python `-O`; native research invariants include assertions. This reference uses BF16 base/readout and FP32 unmerged adapter. Different precision, kernels, context, temperature, thresholds, wrapper logic or model merging require separate parity and quality verification. No training is run by the loader.
|
| 68 |
+
|
| 69 |
+
## Typed decisions and HTTP
|
| 70 |
+
|
| 71 |
+
`Fev4B.decide` exposes Choice, Noul and Score without the routing policy. Use `serve.py` for the text-only System One endpoint; see [API.md](API.md). The weights and routing policy are unchanged from v0.1.0.
|
examples/typed-request.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "fev-4b",
|
| 3 |
+
"state": "Мне дважды списали оплату. Верните лишнее списание, пожалуйста.",
|
| 4 |
+
"questions": {
|
| 5 |
+
"topic": {
|
| 6 |
+
"type": "choice",
|
| 7 |
+
"instructions": "Определите тему обращения.",
|
| 8 |
+
"criteria": {
|
| 9 |
+
"billing": "Оплата, списания, возврат денег",
|
| 10 |
+
"delivery": "Доставка заказа"
|
| 11 |
+
}
|
| 12 |
+
},
|
| 13 |
+
"refund": {"type": "noul", "instructions": "Клиент просит вернуть деньги?"},
|
| 14 |
+
"urgency": {
|
| 15 |
+
"type": "score",
|
| 16 |
+
"instructions": "Оцените срочность по указанным уровням.",
|
| 17 |
+
"criteria": ["Можно подождать", "Нужно решить в ближайшее время", "Нужна немедленная помощь"]
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
}
|
fev4b/__init__.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Fev-4B public inference interface."""
|
| 2 |
from .model import Fev4B, route_with_predict
|
| 3 |
from .integrity import verify_package
|
|
|
|
| 4 |
|
| 5 |
-
__all__ = ['Fev4B', 'route_with_predict', 'verify_package']
|
| 6 |
-
__version__ = '0.
|
|
|
|
| 1 |
"""Fev-4B public inference interface."""
|
| 2 |
from .model import Fev4B, route_with_predict
|
| 3 |
from .integrity import verify_package
|
| 4 |
+
from .decisions import decide_with_predict
|
| 5 |
|
| 6 |
+
__all__ = ['Fev4B', 'route_with_predict', 'decide_with_predict', 'verify_package']
|
| 7 |
+
__version__ = '0.2.0'
|
fev4b/decisions.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Text-only typed decisions. No model imports or customer defaults."""
|
| 2 |
+
import copy
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
MODEL_ID = 'fev-4b'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _json(value, depth=0):
|
| 9 |
+
if depth > 32:
|
| 10 |
+
raise ValueError('JSON nesting exceeds 32 levels')
|
| 11 |
+
if value is None or isinstance(value, (str, bool, int)):
|
| 12 |
+
return
|
| 13 |
+
if isinstance(value, float) and math.isfinite(value):
|
| 14 |
+
return
|
| 15 |
+
if isinstance(value, list):
|
| 16 |
+
for item in value:
|
| 17 |
+
_json(item, depth + 1)
|
| 18 |
+
return
|
| 19 |
+
if isinstance(value, dict) and all(isinstance(key, str) for key in value):
|
| 20 |
+
for item in value.values():
|
| 21 |
+
_json(item, depth + 1)
|
| 22 |
+
return
|
| 23 |
+
raise ValueError('Content must be finite JSON')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _content(value, *, nullable=False):
|
| 27 |
+
if value is None and nullable:
|
| 28 |
+
return
|
| 29 |
+
if not isinstance(value, (str, dict, list)):
|
| 30 |
+
raise ValueError('Content must be a string, object or array')
|
| 31 |
+
_json(value)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_request(request):
|
| 35 |
+
"""Validate without changing instructions, state, keys or option order."""
|
| 36 |
+
if not isinstance(request, dict) or set(request) != {'state', 'questions'}:
|
| 37 |
+
raise ValueError('Expected exactly state and questions; images and assets are unsupported')
|
| 38 |
+
_content(request['state'])
|
| 39 |
+
questions = request['questions']
|
| 40 |
+
if not isinstance(questions, dict) or not 1 <= len(questions) <= 64:
|
| 41 |
+
raise ValueError('Supply 1 to 64 questions')
|
| 42 |
+
for key, question in questions.items():
|
| 43 |
+
if not isinstance(key, str) or not key:
|
| 44 |
+
raise ValueError('Question IDs must be nonempty strings')
|
| 45 |
+
if not isinstance(question, dict) or set(question) - {'type', 'instructions', 'criteria'}:
|
| 46 |
+
raise ValueError('Unsupported question fields')
|
| 47 |
+
kind = question.get('type')
|
| 48 |
+
if kind not in ('choice', 'noul', 'score'):
|
| 49 |
+
raise ValueError('Supported question types: choice, noul, score')
|
| 50 |
+
_content(question.get('instructions'), nullable=True)
|
| 51 |
+
criteria = question.get('criteria')
|
| 52 |
+
if kind == 'choice':
|
| 53 |
+
if not isinstance(criteria, dict) or not 1 <= len(criteria) <= 255:
|
| 54 |
+
raise ValueError('Choice needs 1 to 255 options')
|
| 55 |
+
if any(not isinstance(option, str) or not option for option in criteria):
|
| 56 |
+
raise ValueError('Choice option keys must be nonempty strings')
|
| 57 |
+
elif kind == 'noul':
|
| 58 |
+
if criteria is not None and (not isinstance(criteria, dict) or set(criteria) - {'true', 'false'}):
|
| 59 |
+
raise ValueError('Noul criteria may contain only true and false')
|
| 60 |
+
elif not isinstance(criteria, list) or not 2 <= len(criteria) <= 255:
|
| 61 |
+
raise ValueError('Score needs 2 to 255 ordered levels')
|
| 62 |
+
descriptions = criteria.values() if isinstance(criteria, dict) else (criteria or [])
|
| 63 |
+
for description in descriptions:
|
| 64 |
+
_content(description, nullable=kind != 'score')
|
| 65 |
+
return copy.deepcopy(request)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _number(value, lower, upper):
|
| 69 |
+
return (type(value) in (int, float) and math.isfinite(value) and lower <= value <= upper)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def validate_response(request, response):
|
| 73 |
+
"""Reject incomplete/non-finite native outputs rather than inventing answers."""
|
| 74 |
+
answers = response.get('answers')
|
| 75 |
+
if not isinstance(answers, dict) or set(answers) != set(request['questions']):
|
| 76 |
+
raise RuntimeError('Incomplete typed decision response')
|
| 77 |
+
for key, question in request['questions'].items():
|
| 78 |
+
answer = answers[key]
|
| 79 |
+
kind = question['type']
|
| 80 |
+
if answer.get('type') != kind:
|
| 81 |
+
raise RuntimeError('Native answer type mismatch')
|
| 82 |
+
if kind == 'noul':
|
| 83 |
+
if not _number(answer.get('noul'), 0, 1):
|
| 84 |
+
raise RuntimeError('Invalid Noul probability')
|
| 85 |
+
continue
|
| 86 |
+
keys = list(question['criteria']) if kind == 'choice' else [str(i) for i in range(len(question['criteria']))]
|
| 87 |
+
probabilities = answer.get('probabilities')
|
| 88 |
+
if (not isinstance(probabilities, dict) or set(probabilities) != set(keys)
|
| 89 |
+
or any(not _number(p, 0, 1) for p in probabilities.values())
|
| 90 |
+
or not math.isclose(sum(probabilities.values()), 1, abs_tol=1e-5)
|
| 91 |
+
or not _number(answer.get('confidence'), 0, 1)):
|
| 92 |
+
raise RuntimeError('Invalid typed probability distribution')
|
| 93 |
+
if kind == 'choice':
|
| 94 |
+
if answer.get('choice') not in keys or probabilities[answer['choice']] != max(probabilities.values()):
|
| 95 |
+
raise RuntimeError('Choice does not match distribution')
|
| 96 |
+
else:
|
| 97 |
+
expected_score = sum(int(k) * p for k, p in probabilities.items())
|
| 98 |
+
if (not _number(answer.get('score'), 0, len(keys) - 1)
|
| 99 |
+
or not math.isclose(answer['score'], expected_score, abs_tol=1e-5)
|
| 100 |
+
or answer.get('legend') != dict(zip(keys, question['criteria']))):
|
| 101 |
+
raise RuntimeError('Score does not match distribution or legend')
|
| 102 |
+
usage = response.get('usage', {})
|
| 103 |
+
if (type(usage.get('input_tokens')) is not int or usage['input_tokens'] < 1
|
| 104 |
+
or usage.get('output_tokens') != 0 or usage.get('sequences') != 1):
|
| 105 |
+
raise RuntimeError('Typed decisions must use one sequence and generate zero tokens')
|
| 106 |
+
return response
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def decide_with_predict(request, *, predict):
|
| 110 |
+
request = validate_request(request)
|
| 111 |
+
response = validate_response(request, predict(request))
|
| 112 |
+
return {'model': MODEL_ID, **response}
|
fev4b/integrity.py
CHANGED
|
@@ -15,7 +15,7 @@ def file_sha256(path):
|
|
| 15 |
def verify_package(directory):
|
| 16 |
root = Path(directory).resolve()
|
| 17 |
manifest = json.loads((root / 'manifest.json').read_text())
|
| 18 |
-
if manifest['model'] != 'Fev-4B' or manifest['version']
|
| 19 |
raise ValueError('Unsupported package manifest')
|
| 20 |
files = manifest.get('files')
|
| 21 |
if not isinstance(files, dict) or not files:
|
|
|
|
| 15 |
def verify_package(directory):
|
| 16 |
root = Path(directory).resolve()
|
| 17 |
manifest = json.loads((root / 'manifest.json').read_text())
|
| 18 |
+
if manifest['model'] != 'Fev-4B' or manifest['version'] not in ('0.1.0', '0.2.0'):
|
| 19 |
raise ValueError('Unsupported package manifest')
|
| 20 |
files = manifest.get('files')
|
| 21 |
if not isinstance(files, dict) or not files:
|
fev4b/model.py
CHANGED
|
@@ -17,6 +17,7 @@ from fev.route_applicability import build_request
|
|
| 17 |
from fev.ranked_membership import resolve
|
| 18 |
from fev.research_controls import compare_responses
|
| 19 |
from .integrity import verify_package
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
def route_with_predict(request, *, unknown_key, predict):
|
|
@@ -44,7 +45,7 @@ def route_with_predict(request, *, unknown_key, predict):
|
|
| 44 |
evidence.update({key: value['noul'] for key, value in secondary['answers'].items()})
|
| 45 |
decision = resolve(evidence, choice, config['precedence'], unknown_key=unknown_key, yes=.8, no=.2)
|
| 46 |
responses = [primary] + ([secondary] if secondary is not None else [])
|
| 47 |
-
return {'model': 'Fev-4B', 'version': '0.
|
| 48 |
'route': decision.get('key'), 'probabilities': choice, 'applicability': evidence,
|
| 49 |
'queriedKeys': config['queriedKeys'], 'precedence': config['precedence'],
|
| 50 |
'usage': {key: sum(part['usage'][key] for part in responses)
|
|
@@ -136,3 +137,16 @@ class Fev4B:
|
|
| 136 |
raise RuntimeError('Model parameters changed during inference')
|
| 137 |
result['latencyMs'] = 1000 * (time.perf_counter() - started)
|
| 138 |
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
from fev.ranked_membership import resolve
|
| 18 |
from fev.research_controls import compare_responses
|
| 19 |
from .integrity import verify_package
|
| 20 |
+
from .decisions import decide_with_predict, validate_request
|
| 21 |
|
| 22 |
|
| 23 |
def route_with_predict(request, *, unknown_key, predict):
|
|
|
|
| 45 |
evidence.update({key: value['noul'] for key, value in secondary['answers'].items()})
|
| 46 |
decision = resolve(evidence, choice, config['precedence'], unknown_key=unknown_key, yes=.8, no=.2)
|
| 47 |
responses = [primary] + ([secondary] if secondary is not None else [])
|
| 48 |
+
return {'model': 'Fev-4B', 'version': '0.2.0', 'decision': decision,
|
| 49 |
'route': decision.get('key'), 'probabilities': choice, 'applicability': evidence,
|
| 50 |
'queriedKeys': config['queriedKeys'], 'precedence': config['precedence'],
|
| 51 |
'usage': {key: sum(part['usage'][key] for part in responses)
|
|
|
|
| 137 |
raise RuntimeError('Model parameters changed during inference')
|
| 138 |
result['latencyMs'] = 1000 * (time.perf_counter() - started)
|
| 139 |
return result
|
| 140 |
+
|
| 141 |
+
def decide(self, request):
|
| 142 |
+
"""Answer Choice/Noul/Score questions in one joint forward pass.
|
| 143 |
+
|
| 144 |
+
This exposes the native decision head, without the two-stage routing
|
| 145 |
+
policy. Question quality and calibration need workload-specific checks.
|
| 146 |
+
"""
|
| 147 |
+
request = validate_request(request)
|
| 148 |
+
with self._lock:
|
| 149 |
+
result = decide_with_predict(request, predict=self._predict)
|
| 150 |
+
if any(p._version != version or p.requires_grad for p, version in self._versions):
|
| 151 |
+
raise RuntimeError('Model parameters changed during inference')
|
| 152 |
+
return result
|
fev4b/server.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small synchronous reference HTTP server. Put behind a managed reverse proxy.
|
| 2 |
+
|
| 3 |
+
One resident model, serialized requests, bounded bodies, no request-content logs.
|
| 4 |
+
This is an integration reference, not a qualified high-throughput serving stack.
|
| 5 |
+
"""
|
| 6 |
+
import hmac
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import uuid
|
| 10 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 11 |
+
|
| 12 |
+
from .decisions import MODEL_ID, validate_request
|
| 13 |
+
|
| 14 |
+
MAX_BODY_BYTES = 1024 * 1024
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class HTTPError(Exception):
|
| 18 |
+
def __init__(self, status, detail):
|
| 19 |
+
self.status, self.detail = status, detail
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _unique_object(pairs):
|
| 23 |
+
result = {}
|
| 24 |
+
for key, value in pairs:
|
| 25 |
+
if key in result:
|
| 26 |
+
raise ValueError('Duplicate JSON keys are unsupported')
|
| 27 |
+
result[key] = value
|
| 28 |
+
return result
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_server(model, address=('127.0.0.1', 8000), *, api_key=None):
|
| 32 |
+
class Handler(BaseHTTPRequestHandler):
|
| 33 |
+
def setup(self):
|
| 34 |
+
super().setup()
|
| 35 |
+
self.connection.settimeout(30)
|
| 36 |
+
|
| 37 |
+
def log_message(self, *_):
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
def respond(self, status, body):
|
| 41 |
+
data = json.dumps(body, ensure_ascii=False, allow_nan=False).encode('utf-8')
|
| 42 |
+
self.send_response(status)
|
| 43 |
+
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
| 44 |
+
self.send_header('Content-Length', str(len(data)))
|
| 45 |
+
self.send_header('x-typesafe-request-id', str(uuid.uuid4()))
|
| 46 |
+
self.end_headers()
|
| 47 |
+
self.wfile.write(data)
|
| 48 |
+
|
| 49 |
+
def authorize(self):
|
| 50 |
+
if api_key and not hmac.compare_digest(
|
| 51 |
+
self.headers.get('Authorization', '').encode(), ('Bearer ' + api_key).encode()):
|
| 52 |
+
raise HTTPError(401, 'Invalid bearer token')
|
| 53 |
+
|
| 54 |
+
def do_GET(self):
|
| 55 |
+
try:
|
| 56 |
+
self.authorize()
|
| 57 |
+
if self.path == '/v1/models':
|
| 58 |
+
self.respond(200, {'models': [{'name': MODEL_ID, 'description':
|
| 59 |
+
'Fev-4B text decisions: Choice, Noul and Score; zero generated tokens.',
|
| 60 |
+
'release_date': '2026-10-24'}]})
|
| 61 |
+
else:
|
| 62 |
+
raise HTTPError(404, 'Unknown endpoint')
|
| 63 |
+
except HTTPError as error:
|
| 64 |
+
self.respond(error.status, {'detail': error.detail})
|
| 65 |
+
|
| 66 |
+
def read_payload(self):
|
| 67 |
+
if self.headers.get('Transfer-Encoding'):
|
| 68 |
+
raise HTTPError(400, 'Chunked request bodies are unsupported')
|
| 69 |
+
if len(self.headers.get_all('Content-Length', [])) != 1:
|
| 70 |
+
raise HTTPError(411, 'One Content-Length header is required')
|
| 71 |
+
try:
|
| 72 |
+
size = int(self.headers['Content-Length'])
|
| 73 |
+
except ValueError:
|
| 74 |
+
raise HTTPError(400, 'Invalid Content-Length') from None
|
| 75 |
+
if not 0 < size <= MAX_BODY_BYTES:
|
| 76 |
+
raise HTTPError(413, 'Request body exceeds the 1 MiB limit')
|
| 77 |
+
if self.headers.get_content_type() != 'application/json':
|
| 78 |
+
raise HTTPError(415, 'Content-Type must be application/json')
|
| 79 |
+
data = self.rfile.read(size)
|
| 80 |
+
if len(data) != size:
|
| 81 |
+
raise HTTPError(400, 'Incomplete request body')
|
| 82 |
+
encoding = self.headers.get('Content-Encoding', 'identity').lower()
|
| 83 |
+
if encoding == 'zstd':
|
| 84 |
+
import zstandard
|
| 85 |
+
try:
|
| 86 |
+
with zstandard.ZstdDecompressor(max_window_size=1024).stream_reader(io.BytesIO(data)) as stream:
|
| 87 |
+
data = stream.read(MAX_BODY_BYTES + 1)
|
| 88 |
+
except zstandard.ZstdError:
|
| 89 |
+
raise HTTPError(400, 'Invalid or oversized zstd frame') from None
|
| 90 |
+
if len(data) > MAX_BODY_BYTES:
|
| 91 |
+
raise HTTPError(413, 'Decoded request exceeds the 1 MiB limit')
|
| 92 |
+
elif encoding != 'identity':
|
| 93 |
+
raise HTTPError(415, 'Supported Content-Encoding: identity, zstd')
|
| 94 |
+
return json.loads(data.decode('utf-8'), object_pairs_hook=_unique_object,
|
| 95 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Non-finite JSON')))
|
| 96 |
+
|
| 97 |
+
def do_POST(self):
|
| 98 |
+
try:
|
| 99 |
+
self.authorize()
|
| 100 |
+
if self.path != '/v1/systemone':
|
| 101 |
+
raise HTTPError(404, 'Unknown endpoint')
|
| 102 |
+
payload = self.read_payload()
|
| 103 |
+
if not isinstance(payload, dict) or set(payload) != {'model', 'state', 'questions'}:
|
| 104 |
+
raise ValueError('Expected exactly model, state and questions; assets are unsupported')
|
| 105 |
+
if payload['model'] != MODEL_ID:
|
| 106 |
+
raise ValueError('Only model fev-4b is available')
|
| 107 |
+
request = validate_request({'state': payload['state'], 'questions': payload['questions']})
|
| 108 |
+
self.respond(200, model.decide(request))
|
| 109 |
+
except HTTPError as error:
|
| 110 |
+
self.respond(error.status, {'detail': error.detail})
|
| 111 |
+
except (ValueError, UnicodeError, RecursionError):
|
| 112 |
+
self.respond(422, {'detail': 'Invalid request or context limit exceeded; see API.md'})
|
| 113 |
+
except (TimeoutError, ConnectionError):
|
| 114 |
+
self.close_connection = True
|
| 115 |
+
except Exception:
|
| 116 |
+
self.respond(500, {'detail': 'Inference failed; no partial answers were returned'})
|
| 117 |
+
|
| 118 |
+
return HTTPServer(address, Handler)
|
fev_config.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
-
"version": "0.
|
| 4 |
"runtime": {
|
| 5 |
"maxLength": 16384,
|
| 6 |
"batchTokens": 16384,
|
|
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
+
"version": "0.2.0",
|
| 4 |
"runtime": {
|
| 5 |
"maxLength": 16384,
|
| 6 |
"batchTokens": 16384,
|
manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
-
"version": "0.
|
| 4 |
"files": {
|
| 5 |
".gitattributes": {
|
| 6 |
"bytes": 1570,
|
|
@@ -11,8 +11,8 @@
|
|
| 11 |
"sha256": "5d0d577387641d6e65cafa4cd63ffe002a3f960c032e99a48362c95f96ada8b9"
|
| 12 |
},
|
| 13 |
"CHANGES.md": {
|
| 14 |
-
"bytes":
|
| 15 |
-
"sha256": "
|
| 16 |
},
|
| 17 |
"LICENSE": {
|
| 18 |
"bytes": 11544,
|
|
@@ -23,12 +23,12 @@
|
|
| 23 |
"sha256": "381fb81e814716a5ef8e5eae26a08607d052cf12f019dba9da9e81298ef5cb75"
|
| 24 |
},
|
| 25 |
"README.md": {
|
| 26 |
-
"bytes":
|
| 27 |
-
"sha256": "
|
| 28 |
},
|
| 29 |
"RUNNING.md": {
|
| 30 |
-
"bytes":
|
| 31 |
-
"sha256": "
|
| 32 |
},
|
| 33 |
"adapter/adapter_config.json": {
|
| 34 |
"bytes": 1136,
|
|
@@ -163,24 +163,24 @@
|
|
| 163 |
"sha256": "f47e29b6fc6a51013ecb016c8204ff49ac8adbabdbfdd0eb6bf8fdddb63f4270"
|
| 164 |
},
|
| 165 |
"fev4b/__init__.py": {
|
| 166 |
-
"bytes":
|
| 167 |
-
"sha256": "
|
| 168 |
},
|
| 169 |
"fev4b/integrity.py": {
|
| 170 |
-
"bytes":
|
| 171 |
-
"sha256": "
|
| 172 |
},
|
| 173 |
"fev4b/model.py": {
|
| 174 |
-
"bytes":
|
| 175 |
-
"sha256": "
|
| 176 |
},
|
| 177 |
"fev_config.json": {
|
| 178 |
"bytes": 243,
|
| 179 |
-
"sha256": "
|
| 180 |
},
|
| 181 |
"provenance.json": {
|
| 182 |
-
"bytes":
|
| 183 |
-
"sha256": "
|
| 184 |
},
|
| 185 |
"requirements.txt": {
|
| 186 |
"bytes": 189,
|
|
@@ -205,6 +205,38 @@
|
|
| 205 |
"evaluation/packaging-verification.json": {
|
| 206 |
"bytes": 1855,
|
| 207 |
"sha256": "6abacf62c38fc5c5950ef26a207b7db5355655d92684c9eb44c1b12e6eb4434c"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
}
|
| 209 |
}
|
| 210 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
+
"version": "0.2.0",
|
| 4 |
"files": {
|
| 5 |
".gitattributes": {
|
| 6 |
"bytes": 1570,
|
|
|
|
| 11 |
"sha256": "5d0d577387641d6e65cafa4cd63ffe002a3f960c032e99a48362c95f96ada8b9"
|
| 12 |
},
|
| 13 |
"CHANGES.md": {
|
| 14 |
+
"bytes": 1234,
|
| 15 |
+
"sha256": "3e5fe80008d6c297c76defa1f64822e3fce603f0442eb11434460c02c3817cfc"
|
| 16 |
},
|
| 17 |
"LICENSE": {
|
| 18 |
"bytes": 11544,
|
|
|
|
| 23 |
"sha256": "381fb81e814716a5ef8e5eae26a08607d052cf12f019dba9da9e81298ef5cb75"
|
| 24 |
},
|
| 25 |
"README.md": {
|
| 26 |
+
"bytes": 9418,
|
| 27 |
+
"sha256": "bdd2d71f1ae7c26c1b4e2b9aad6e3368ba6aedc19188975fcbcfa2e87f285b3f"
|
| 28 |
},
|
| 29 |
"RUNNING.md": {
|
| 30 |
+
"bytes": 6392,
|
| 31 |
+
"sha256": "4c32e2264d680896c42ffa7b5d4a83a7deb1901f512a4583ea405d971f6a59f9"
|
| 32 |
},
|
| 33 |
"adapter/adapter_config.json": {
|
| 34 |
"bytes": 1136,
|
|
|
|
| 163 |
"sha256": "f47e29b6fc6a51013ecb016c8204ff49ac8adbabdbfdd0eb6bf8fdddb63f4270"
|
| 164 |
},
|
| 165 |
"fev4b/__init__.py": {
|
| 166 |
+
"bytes": 273,
|
| 167 |
+
"sha256": "d4f2e7ee272979f3a1e1c9e04b9815cbe254585a75b465089a9053a813414795"
|
| 168 |
},
|
| 169 |
"fev4b/integrity.py": {
|
| 170 |
+
"bytes": 1487,
|
| 171 |
+
"sha256": "563039e12806fa3523d052cb584cb4d5188c069d1b461a99125d8431a7d277a3"
|
| 172 |
},
|
| 173 |
"fev4b/model.py": {
|
| 174 |
+
"bytes": 8388,
|
| 175 |
+
"sha256": "70858a884ea34bc2ebfba5c3863124f0c247421cc53f1cf03f5d28b54b0068c1"
|
| 176 |
},
|
| 177 |
"fev_config.json": {
|
| 178 |
"bytes": 243,
|
| 179 |
+
"sha256": "f72bdcf114d213a17cd77c4e24608e5c37c39f12f7e6f3b3a09d417f7fbddf8c"
|
| 180 |
},
|
| 181 |
"provenance.json": {
|
| 182 |
+
"bytes": 1932,
|
| 183 |
+
"sha256": "f0d6918799cf10686e0f92236fa16217304ac98e3e656237d3468ee579d4c027"
|
| 184 |
},
|
| 185 |
"requirements.txt": {
|
| 186 |
"bytes": 189,
|
|
|
|
| 205 |
"evaluation/packaging-verification.json": {
|
| 206 |
"bytes": 1855,
|
| 207 |
"sha256": "6abacf62c38fc5c5950ef26a207b7db5355655d92684c9eb44c1b12e6eb4434c"
|
| 208 |
+
},
|
| 209 |
+
"API.md": {
|
| 210 |
+
"bytes": 4224,
|
| 211 |
+
"sha256": "16369fd2f3b8671c22f61680a6bef2fe60108fc458d55c0e4c10b8cf51363c62"
|
| 212 |
+
},
|
| 213 |
+
"examples/typed-request.json": {
|
| 214 |
+
"bytes": 871,
|
| 215 |
+
"sha256": "f2ddf12d2029db1ca6aab8fed26626b913979755a51a9beec914aff8c9877823"
|
| 216 |
+
},
|
| 217 |
+
"fev4b/decisions.py": {
|
| 218 |
+
"bytes": 5456,
|
| 219 |
+
"sha256": "b2122283d3be1afb4735ce353f091c7646b45280b7eeec08072cb4b79a3c7434"
|
| 220 |
+
},
|
| 221 |
+
"fev4b/server.py": {
|
| 222 |
+
"bytes": 5384,
|
| 223 |
+
"sha256": "0822c2cadb9634801ce31ef080bd1faf6f442de03996c280fd1c76e3ce56aabc"
|
| 224 |
+
},
|
| 225 |
+
"requirements-serve.txt": {
|
| 226 |
+
"bytes": 18,
|
| 227 |
+
"sha256": "da56c02977e00d88d897af40d227d773822aa7134d30e1d40c68e1518d666026"
|
| 228 |
+
},
|
| 229 |
+
"requirements-test.txt": {
|
| 230 |
+
"bytes": 52,
|
| 231 |
+
"sha256": "408006931c14be75c13e7cd0b4215fc92c229aeee567912032a4ce33a2637d8e"
|
| 232 |
+
},
|
| 233 |
+
"serve.py": {
|
| 234 |
+
"bytes": 1071,
|
| 235 |
+
"sha256": "bfd73163c06d348afa72db433cac988b15c54cf01eca76f58c80a932ef41eef2"
|
| 236 |
+
},
|
| 237 |
+
"tests/test_decisions.py": {
|
| 238 |
+
"bytes": 6724,
|
| 239 |
+
"sha256": "8ed5a03d65da031d00cce6c9eef2c062bec19f58c96dbdeed30f01d33e7e6b03"
|
| 240 |
}
|
| 241 |
}
|
| 242 |
}
|
provenance.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
-
"version": "0.
|
| 4 |
"publisher": "murabcd",
|
| 5 |
"baseCheckpoint": {
|
| 6 |
"repo": "perplexity-ai/pplx-decider-flash-v1.2",
|
|
@@ -36,5 +36,7 @@
|
|
| 36 |
"fev/research_controls.py": "853f748d4bc49aa079e03a5bd375cbb07012de578d1ebddd205ccaf300101c79"
|
| 37 |
},
|
| 38 |
"sourceFrozenManifestSha256": "28652bb88f086b2be4c6251dda581f5bdfdf4466ec09bf862e6eca005dab0cbf",
|
| 39 |
-
"upstreamManifestNote": "Upstream README hash was stale; execution artifacts all verified. Package manifest records the actual included README hash."
|
|
|
|
|
|
|
| 40 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"model": "Fev-4B",
|
| 3 |
+
"version": "0.2.0",
|
| 4 |
"publisher": "murabcd",
|
| 5 |
"baseCheckpoint": {
|
| 6 |
"repo": "perplexity-ai/pplx-decider-flash-v1.2",
|
|
|
|
| 36 |
"fev/research_controls.py": "853f748d4bc49aa079e03a5bd375cbb07012de578d1ebddd205ccaf300101c79"
|
| 37 |
},
|
| 38 |
"sourceFrozenManifestSha256": "28652bb88f086b2be4c6251dda581f5bdfdf4466ec09bf862e6eca005dab0cbf",
|
| 39 |
+
"upstreamManifestNote": "Upstream README hash was stale; execution artifacts all verified. Package manifest records the actual included README hash.",
|
| 40 |
+
"weightsUnchangedSinceVersion": "0.1.0",
|
| 41 |
+
"sourceRepository": "https://github.com/murabcd/fev"
|
| 42 |
}
|
requirements-serve.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
zstandard==0.25.0
|
requirements-test.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements-serve.txt
|
| 2 |
+
typesafe-sdk[zstd]==0.7.5
|
serve.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Start the resident Fev text-decision reference server."""
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from fev4b import Fev4B
|
| 7 |
+
from fev4b.server import create_server
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 12 |
+
parser.add_argument('--model-dir', type=Path, default=Path(__file__).resolve().parent)
|
| 13 |
+
parser.add_argument('--host', default='127.0.0.1')
|
| 14 |
+
parser.add_argument('--port', type=int, default=8000)
|
| 15 |
+
parser.add_argument('--device', default='cuda:0')
|
| 16 |
+
args = parser.parse_args()
|
| 17 |
+
api_key = os.environ.get('FEV_API_KEY')
|
| 18 |
+
if args.host not in ('127.0.0.1', 'localhost') and not api_key:
|
| 19 |
+
parser.error('Set FEV_API_KEY before binding outside localhost')
|
| 20 |
+
model = Fev4B(args.model_dir, device=args.device)
|
| 21 |
+
with create_server(model, (args.host, args.port), api_key=api_key) as server:
|
| 22 |
+
print(f'Fev ready at http://{args.host}:{args.port}', flush=True)
|
| 23 |
+
try:
|
| 24 |
+
server.serve_forever()
|
| 25 |
+
except KeyboardInterrupt:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == '__main__':
|
| 30 |
+
main()
|
tests/test_decisions.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contract checks with a fake predictor, plus real TypeSafe SDK over HTTP.
|
| 2 |
+
|
| 3 |
+
These tests validate the interface, not learned model quality.
|
| 4 |
+
"""
|
| 5 |
+
import copy
|
| 6 |
+
import json
|
| 7 |
+
import threading
|
| 8 |
+
import unittest
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from urllib.error import HTTPError
|
| 11 |
+
from urllib.request import Request, urlopen
|
| 12 |
+
|
| 13 |
+
from fev4b.decisions import decide_with_predict, validate_request
|
| 14 |
+
from fev4b.server import MAX_BODY_BYTES, create_server
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FakeModel:
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self.calls = []
|
| 22 |
+
|
| 23 |
+
def decide(self, request):
|
| 24 |
+
self.calls.append(copy.deepcopy(request))
|
| 25 |
+
def predict(actual):
|
| 26 |
+
answers = {}
|
| 27 |
+
for key, question in actual['questions'].items():
|
| 28 |
+
kind = question['type']
|
| 29 |
+
if kind == 'noul':
|
| 30 |
+
answers[key] = {'type': kind, 'noul': .9}
|
| 31 |
+
continue
|
| 32 |
+
keys = list(question['criteria']) if kind == 'choice' else [str(i) for i in range(len(question['criteria']))]
|
| 33 |
+
probabilities = dict.fromkeys(keys, 0.)
|
| 34 |
+
probabilities[keys[0]] = 1.
|
| 35 |
+
answers[key] = {'type': kind, 'probabilities': probabilities, 'confidence': 1.}
|
| 36 |
+
if kind == 'choice':
|
| 37 |
+
answers[key]['choice'] = keys[0]
|
| 38 |
+
else:
|
| 39 |
+
answers[key].update(score=0., legend=dict(zip(keys, question['criteria'])))
|
| 40 |
+
return {'answers': answers, 'usage': {'input_tokens': 100, 'output_tokens': 0, 'sequences': 1}}
|
| 41 |
+
return decide_with_predict(request, predict=predict)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DecisionTests(unittest.TestCase):
|
| 45 |
+
def test_reject_bad_schema_before_inference(self):
|
| 46 |
+
examples = [
|
| 47 |
+
{'state': 'x', 'questions': {}},
|
| 48 |
+
{'state': 'x', 'questions': {'q': {'type': 'box'}}},
|
| 49 |
+
{'state': 'x', 'questions': {'q': {'type': 'score', 'criteria': ['one']}}},
|
| 50 |
+
{'state': 'x', 'questions': {'q': {'type': 'noul', 'criteria': {'other': 'x'}}}},
|
| 51 |
+
{'state': {'x': float('nan')}, 'questions': {'q': {'type': 'noul'}}},
|
| 52 |
+
{'state': 'x', 'questions': {'q': {'type': 'choice', 'criteria': {'': None}}}},
|
| 53 |
+
]
|
| 54 |
+
for request in examples:
|
| 55 |
+
with self.subTest(request=request), self.assertRaises(ValueError):
|
| 56 |
+
decide_with_predict(request, predict=lambda _: self.fail('Called model for invalid input'))
|
| 57 |
+
|
| 58 |
+
def test_deep_copy_and_mixed_answer_validation(self):
|
| 59 |
+
payload = json.loads((ROOT/'examples/typed-request.json').read_text())
|
| 60 |
+
request = {k: payload[k] for k in ('state', 'questions')}
|
| 61 |
+
original = copy.deepcopy(request)
|
| 62 |
+
result = FakeModel().decide(request)
|
| 63 |
+
self.assertEqual(request, original)
|
| 64 |
+
self.assertEqual(result['model'], 'fev-4b')
|
| 65 |
+
self.assertEqual(result['answers']['topic']['choice'], 'billing')
|
| 66 |
+
self.assertEqual(result['answers']['urgency']['legend']['0'], request['questions']['urgency']['criteria'][0])
|
| 67 |
+
|
| 68 |
+
def test_invalid_native_answer_is_not_returned(self):
|
| 69 |
+
request = {'state': 'x', 'questions': {'q': {'type': 'noul'}}}
|
| 70 |
+
with self.assertRaises(RuntimeError):
|
| 71 |
+
decide_with_predict(request, predict=lambda _: {
|
| 72 |
+
'answers': {'q': {'type': 'noul', 'noul': float('nan')}},
|
| 73 |
+
'usage': {'input_tokens': 10, 'output_tokens': 0, 'sequences': 1}})
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class HTTPTests(unittest.TestCase):
|
| 77 |
+
def setUp(self):
|
| 78 |
+
self.model = FakeModel()
|
| 79 |
+
self.server = create_server(self.model, ('127.0.0.1', 0), api_key='local-test')
|
| 80 |
+
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
| 81 |
+
self.thread.start()
|
| 82 |
+
self.url = f'http://127.0.0.1:{self.server.server_port}'
|
| 83 |
+
|
| 84 |
+
def tearDown(self):
|
| 85 |
+
self.server.shutdown()
|
| 86 |
+
self.thread.join()
|
| 87 |
+
self.server.server_close()
|
| 88 |
+
|
| 89 |
+
def post(self, body, *, key='local-test', **headers):
|
| 90 |
+
raw = body if isinstance(body, bytes) else json.dumps(body).encode()
|
| 91 |
+
request = Request(self.url+'/v1/systemone', data=raw, headers={
|
| 92 |
+
'Authorization': 'Bearer '+key, 'Content-Type': 'application/json', **headers})
|
| 93 |
+
try:
|
| 94 |
+
with urlopen(request, timeout=5) as response:
|
| 95 |
+
return response.status, json.loads(response.read())
|
| 96 |
+
except HTTPError as error:
|
| 97 |
+
return error.code, json.loads(error.read())
|
| 98 |
+
|
| 99 |
+
def test_real_sdk_plain_and_compressed_mixed_questions(self):
|
| 100 |
+
from typesafe_sdk import Choice, Noul, Score, TypeSafeClient
|
| 101 |
+
for compression in (False, 'zstd'):
|
| 102 |
+
# Exceed SDK's automatic compression size threshold.
|
| 103 |
+
state = {'message': 'Оплата списана дважды. ' * 200, 'history': []}
|
| 104 |
+
with TypeSafeClient(api_key='local-test', base_url=self.url,
|
| 105 |
+
model='fev-4b', compression=compression) as client:
|
| 106 |
+
response = client.system_one(state=state, questions={
|
| 107 |
+
'team': Choice(criteria={'billing': 'Платежи', 'delivery': 'Доставка'}),
|
| 108 |
+
'refund': Noul(instructions='Нужен возврат?'),
|
| 109 |
+
'urgency': Score(criteria=['Низкая', 'Высокая']),
|
| 110 |
+
})
|
| 111 |
+
self.assertEqual(response.choices['team'].choice, 'billing')
|
| 112 |
+
self.assertEqual(response.nouls['refund'].noul, .9)
|
| 113 |
+
self.assertEqual(response.scores['urgency'].score, 0.)
|
| 114 |
+
self.assertEqual(response.usage.output_tokens, 0)
|
| 115 |
+
self.assertTrue(response.request_id)
|
| 116 |
+
self.assertEqual(client.models.list().models[0].name, 'fev-4b')
|
| 117 |
+
self.assertEqual(self.model.calls[-1]['state'], state)
|
| 118 |
+
self.assertEqual(len(self.model.calls), 2)
|
| 119 |
+
|
| 120 |
+
def test_auth_unknown_models_assets_and_duplicate_keys(self):
|
| 121 |
+
payload = json.loads((ROOT/'examples/typed-request.json').read_text())
|
| 122 |
+
self.assertEqual(self.post(payload, key='wrong')[0], 401)
|
| 123 |
+
payload['model'] = 'unavailable'
|
| 124 |
+
self.assertEqual(self.post(payload)[0], 422)
|
| 125 |
+
payload['model'] = 'fev-4b'
|
| 126 |
+
payload['assets'] = {'photo': {'url': 'http://example.invalid'}}
|
| 127 |
+
self.assertEqual(self.post(payload)[0], 422)
|
| 128 |
+
self.assertEqual(self.post(b'{"model":"fev-4b","model":"other"}')[0], 422)
|
| 129 |
+
self.assertEqual(self.model.calls, [])
|
| 130 |
+
|
| 131 |
+
def test_bounded_decompression(self):
|
| 132 |
+
import zstandard
|
| 133 |
+
large = zstandard.ZstdCompressor().compress(b' ' * (MAX_BODY_BYTES + 100))
|
| 134 |
+
self.assertIn(self.post(large, **{'Content-Encoding': 'zstd'})[0], (400, 413))
|
| 135 |
+
self.assertEqual(self.model.calls, [])
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == '__main__':
|
| 139 |
+
unittest.main()
|