Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
systemone: one decision API, POST /v1/brio removed
JustVugg37b3ad756638
diff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlindex 1940b3ec..7d737b20 100644--- a/.github/workflows/check.yml+++ b/.github/workflows/check.yml@@ -108,7 +108,7 @@ jobs:python c/tests/mimo_tiny_harness.py --binary c/mimo --fixture c/mimo_tinycd c && ASAN_OPTIONS=detect_leaks=0:detect_stack_use_after_return=0 UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 \python -m unittest tests.test_mimo_prefix_serve tests.test_brio_serve.MimoBrioServe \- tests.test_brio_api.MimoBrioEndToEnd+ tests.test_systemone_api.MimoSystemOneEndToEndv4-tiny:name: Linux (generated tiny V4 target oracle)diff --git a/README.it.md b/README.it.mdindex d24f3e2e..f685af2a 100644--- a/README.it.md+++ b/README.it.md@@ -610,11 +610,11 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # misura e salva il profilo di esecuziGran parte di ciò che si chiede a un modello è una scelta, non un paragrafo:quale coda, quale verdetto, quale dei quattro valori può prendere un campo. Lamodalità System One passa al motore le opzioni e legge la probabilità di ciascuna-invece di generare: `completion_tokens` è 0, nessuna risposta può uscire dalla-tua lista, e ogni risposta arriva con un'entropia, così "il modello non è-sicuro" è un numero su cui mettere una soglia. Funziona su tutte e dieci le-famiglie, sullo stesso server, ed è opzionale per richiesta: la chat resta-identica byte per byte per chi non la chiede.+invece di generare: non si genera nulla, nessuna risposta può uscire dalla tua+lista, e ogni risposta arriva con una confidenza, così "il modello non è sicuro"+è un numero su cui mettere una soglia. Funziona su tutte e dieci le famiglie,+sullo stesso server, ed è opzionale per richiesta: la chat resta identica byte+per byte per chi non la chiede.```bash# nella TUI: lo stesso modello, a cui si dice di non scrivere@@ -623,20 +623,19 @@ identica byte per byte per chi non la chiede.> 340 lines, 8 files, no tests. CI is green but nothing covers that path.# da qualunque programma: una richiesta JSON al server in esecuzione-curl -s http://127.0.0.1:8000/v1/brio -H 'Content-Type: application/json' -d '{- "model": "qwen36",+curl -s http://127.0.0.1:8000/v1/systemone -H 'Content-Type: application/json' -d '{"state": "340 lines, 8 files, no tests. CI is green but nothing covers that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]}'+ "questions": {"review": {"type": "choice", "instructions": "What should the reviewer do?",+ "criteria": {"merge": null, "request changes": null, "close": null}}}}'```-`questions` fa molte domande su un documento letto una volta sola, e `schema`-riempie un oggetto JSON un campo alla volta, valido per costruzione. Misurato-su Qwen3.6 contro la generazione della stessa risposta sulla stessa macchina-CPU: 2,4x su uno schema a quattro campi, 5,7x su quattro domande sullo stesso-documento. Tutta la modalità, la forma di richiesta e risposta, e dove non-serve: [docs/systemone.md](docs/systemone.md). Anche la dashboard ha una pagina System One, e le stesse risposte arrivano da-`POST /v1/systemone`, l'API di Jev di TypeSafe: un client Jev passa a colibri cambiando solo il base URL.+`POST /v1/systemone` parla la richiesta e la risposta dell'API Jev di TypeSafe:+un client Jev passa a colibri cambiando solo il base URL. Più domande sullo+stesso documento lo leggono una volta sola: misurato su Qwen3.6 contro la+generazione delle stesse risposte sulla stessa macchina CPU, 5,7x su quattro+domande sullo stesso documento. Tutta la modalità, la forma di richiesta e+risposta, e dove non serve: [docs/systemone.md](docs/systemone.md). Anche la+dashboard ha una pagina System One.Su Windows un archivio di release include `coli.cmd`: fai doppio clic per l'avviodiff --git a/README.ja.md b/README.ja.mdindex 9509a924..9ea5bd03 100644--- a/README.ja.md+++ b/README.ja.md@@ -560,7 +560,7 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # このマシンで最速かつ安全人がモデルに求めることの多くは、段落ではなく選択です: どのキューか、どの判定か、あるフィールドが取り得る4 つの値のどれか。System One モードはエンジンに選択肢を渡し、生成する代わりにそれぞれの確率を読み取ります:-`completion_tokens` は 0 で、どの回答もリストの外に出ることはなく、すべての回答にエントロピーが付くため、+何も生成されず、どの回答もリストの外に出ることはなく、すべての回答に確信度 (confidence) が付くため、「モデルに確信がない」ことが閾値を設定できる数値になります。10 のファミリーすべてで、同じサーバー上で動作し、リクエストごとのオプトインです: 求めない人にとって、チャットはバイト単位で同一のままです。@@ -571,19 +571,17 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # このマシンで最速かつ安全> 340 lines, 8 files, no tests. CI is green but nothing covers that path.# from anywhere: one JSON request on the running server-curl -s http://127.0.0.1:8000/v1/brio -H 'Content-Type: application/json' -d '{- "model": "qwen36",+curl -s http://127.0.0.1:8000/v1/systemone -H 'Content-Type: application/json' -d '{"state": "340 lines, 8 files, no tests. CI is green but nothing covers that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]}'+ "questions": {"review": {"type": "choice", "instructions": "What should the reviewer do?",+ "criteria": {"merge": null, "request changes": null, "close": null}}}}'```-`questions` は 1 回だけ読んだ 1 つの文書について多くのことを尋ね、`schema` は JSON オブジェクトを-1 フィールドずつ埋めるため、構造上必ず妥当になります。Qwen3.6 で、同じ CPU マシン上で同じ回答を-生成する場合と比べて計測したところ、4 フィールドのスキーマで 2.4 倍、1 つの文書に対する 4 つの質問で-5.7 倍でした。モード全体、リクエストとレスポンスの形、そして役に立たない場面については-[docs/systemone.md](docs/systemone.md) を参照してください。ダッシュボードにも System One ページがあります。同じ回答は TypeSafe の Jev と同じ API である-`POST /v1/systemone` からも得られ、Jev のクライアントは base URL を変えるだけで切り替えられます。+`POST /v1/systemone` は TypeSafe の Jev API と同じリクエストとレスポンスを話します: Jev のクライアントは+base URL を変えるだけで colibri に切り替えられます。1 つの文書への複数の質問は文書を 1 回だけ読みます:+Qwen3.6 で、同じ CPU マシン上で同じ回答を生成する場合と比べて計測したところ、1 つの文書に対する+4 つの質問で 5.7 倍でした。モード全体、リクエストとレスポンスの形、そして役に立たない場面については+[docs/systemone.md](docs/systemone.md) を参照してください。ダッシュボードにも System One ページがあります。Windows ではリリースアーカイブに `coli.cmd` が同梱されています。ダブルクリックでクイックスタート、diff --git a/README.md b/README.mdindex 2a82399f..590de07b 100644--- a/README.md+++ b/README.md@@ -586,11 +586,11 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # measure and save this machine's fastMost of what people ask a model for is a choice, not a paragraph: which queue,which verdict, which of the four values a field may take. System One mode hands theengine the options and reads the probability of each one instead of-generating: `completion_tokens` is 0, no answer can fall outside your list,-and every answer comes with an entropy, so "the model is not sure" is a-number you can put a threshold on. It runs on all ten families, on the same-server, and it is opt-in per request: chat is byte-identical for everyone who-does not ask for it.+generating: nothing is generated, no answer can fall outside your list, and+every answer comes with a confidence, so "the model is not sure" is a number+you can put a threshold on. It runs on all ten families, on the same server,+and it is opt-in per request: chat is byte-identical for everyone who does not+ask for it.```bash# in the TUI: the same model, told to stop writing@@ -599,20 +599,18 @@ does not ask for it.> 340 lines, 8 files, no tests. CI is green but nothing covers that path.# from anywhere: one JSON request on the running server-curl -s http://127.0.0.1:8000/v1/brio -H 'Content-Type: application/json' -d '{- "model": "qwen36",+curl -s http://127.0.0.1:8000/v1/systemone -H 'Content-Type: application/json' -d '{"state": "340 lines, 8 files, no tests. CI is green but nothing covers that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]}'+ "questions": {"review": {"type": "choice", "instructions": "What should the reviewer do?",+ "criteria": {"merge": null, "request changes": null, "close": null}}}}'```-`questions` asks many things about one document read once, and `schema` fills-a JSON object one field at a time, valid by construction. Measured on Qwen3.6-against generating the same answer on the same CPU box: 2.4x on a four-field-schema, 5.7x on four questions about one document. The whole mode, the-request and reply shapes, and where it does not help: [docs/systemone.md](docs/systemone.md).-The dashboard has a System One page as well, and the same answers come over-`POST /v1/systemone`, the API of TypeSafe's Jev: a Jev client switches by changing its base URL.+`POST /v1/systemone` speaks the request and the reply of TypeSafe's Jev API: a+Jev client switches to colibri by changing its base URL. Many questions about+one document read it once: measured on Qwen3.6 against generating the same+answers on the same CPU box, 5.7x on four questions about one document. The+whole mode, the request and reply shapes, and where it does not help:+[docs/systemone.md](docs/systemone.md). The dashboard has a System One page as well.On Windows a release archive ships `coli.cmd`: double-click it for the quickdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 74ebb6b4..53747156 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -508,8 +508,8 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # 测量并保存本机最快且安全#### System One 模式:问一个封闭式问题人们向模型提出的大多数请求是一次选择,而不是一段文字:哪个队列、哪个结论、某个字段应取四个值中的哪一个。-System One 模式把允许的选项交给引擎,读出每个选项的概率,而不是生成文本:`completion_tokens` 为 0,-答案不可能落在你的列表之外,并且每个答案都附带一个熵,"模型没有把握"因此成为一个可以设阈值的数字。+System One 模式把允许的选项交给引擎,读出每个选项的概率,而不是生成文本:不生成任何内容,+答案不可能落在你的列表之外,并且每个答案都附带一个置信度(confidence),"模型没有把握"因此成为一个可以设阈值的数字。它在全部十个模型家族上可用,运行在同一个服务器上,且按请求可选:不请求它的聊天,输出逐字节保持不变。```bash@@ -519,18 +519,16 @@ System One 模式把允许的选项交给引擎,读出每个选项的概率,> 340 lines, 8 files, no tests. CI is green but nothing covers that path.# 从任何程序:向运行中的服务器发送一个 JSON 请求-curl -s http://127.0.0.1:8000/v1/brio -H 'Content-Type: application/json' -d '{- "model": "qwen36",+curl -s http://127.0.0.1:8000/v1/systemone -H 'Content-Type: application/json' -d '{"state": "340 lines, 8 files, no tests. CI is green but nothing covers that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]}'+ "questions": {"review": {"type": "choice", "instructions": "What should the reviewer do?",+ "criteria": {"merge": null, "request changes": null, "close": null}}}}'```-`questions` 可以对只读一次的文档提出多个问题;`schema` 逐字段填充一个 JSON 对象,结构上必然合法。-在 Qwen3.6 上与在同一台 CPU 机器上生成同样答案相比的实测:四字段 schema 快 2.4 倍,+`POST /v1/systemone` 使用与 TypeSafe 的 Jev API 相同的请求和回复:Jev 客户端只需更改 base URL 即可切换到 colibri。+对同一文档的多个问题只读取文档一次:在 Qwen3.6 上与在同一台 CPU 机器上生成同样答案相比的实测,对同一文档的四个问题快 5.7 倍。完整说明、请求与回复格式、以及它不适用的情形见 [docs/systemone.md](docs/systemone.md)。-仪表盘中也有 System One 页面。同样的回答也可以通过 `POST /v1/systemone` 获得,-它与 TypeSafe 的 Jev API 相同:Jev 客户端只需更改 base URL 即可切换。+仪表盘中也有 System One 页面。在 Windows 上,发布包附带 `coli.cmd`:双击即可快速开始,或在 cmd 或 PowerShell 中运行diff --git a/README.zh-TW.md b/README.zh-TW.mdindex b2662a7b..d086be64 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -509,8 +509,8 @@ COLI_MODEL=/nvme/glm52_i4 ./coli tune # 測量並儲存本機最快且安全#### System One 模式:問一個封閉式問題人們向模型提出的大多數請求是一次選擇,而不是一段文字:哪個佇列、哪個結論、某個欄位應取四個值中的哪一個。-System One 模式把允許的選項交給引擎,讀出每個選項的機率,而不是生成文字:`completion_tokens` 為 0,-答案不可能落在你的清單之外,並且每個答案都附帶一個熵,"模型沒有把握"因此成為一個可以設門檻的數字。+System One 模式把允許的選項交給引擎,讀出每個選項的機率,而不是生成文字:不生成任何內容,+答案不可能落在你的清單之外,並且每個答案都附帶一個信心值(confidence),"模型沒有把握"因此成為一個可以設門檻的數字。它在全部十個模型家族上可用,執行在同一個伺服器上,且按請求可選:不請求它的聊天,輸出逐位元組保持不變。```bash@@ -520,18 +520,16 @@ System One 模式把允許的選項交給引擎,讀出每個選項的機率,> 340 lines, 8 files, no tests. CI is green but nothing covers that path.# 從任何程式:向執行中的伺服器傳送一個 JSON 請求-curl -s http://127.0.0.1:8000/v1/brio -H 'Content-Type: application/json' -d '{- "model": "qwen36",+curl -s http://127.0.0.1:8000/v1/systemone -H 'Content-Type: application/json' -d '{"state": "340 lines, 8 files, no tests. CI is green but nothing covers that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]}'+ "questions": {"review": {"type": "choice", "instructions": "What should the reviewer do?",+ "criteria": {"merge": null, "request changes": null, "close": null}}}}'```-`questions` 可以對只讀一次的文件提出多個問題;`schema` 逐欄位填充一個 JSON 物件,結構上必然合法。-在 Qwen3.6 上與在同一台 CPU 機器上生成同樣答案相比的實測:四欄位 schema 快 2.4 倍,+`POST /v1/systemone` 使用與 TypeSafe 的 Jev API 相同的請求與回覆:Jev 用戶端只需更改 base URL 即可切換到 colibri。+對同一文件的多個問題只讀取文件一次:在 Qwen3.6 上與在同一台 CPU 機器上生成同樣答案相比的實測,對同一文件的四個問題快 5.7 倍。完整說明、請求與回覆格式、以及它不適用的情形見 [docs/systemone.md](docs/systemone.md)。-儀表板中也有 System One 頁面。同樣的回答也可以透過 `POST /v1/systemone` 取得,-它與 TypeSafe 的 Jev API 相同:Jev 用戶端只需更改 base URL 即可切換。+儀表板中也有 System One 頁面。在 Windows 上,發布壓縮檔附帶 `coli.cmd`:按兩下即可快速開始,或在 cmd 或 PowerShell 中執行diff --git a/c/Makefile b/c/Makefileindex ba3bca85..0152fd22 100644--- a/c/Makefile+++ b/c/Makefile@@ -1334,13 +1334,13 @@ mimo-tiny-generate:mimo-tiny-check: mimo-tiny-generate mimo$(EXE)$(PYTHON) tests/mimo_tiny_harness.py --binary ./mimo$(EXE) --fixture ./mimo_tiny-# The same fixture served: KV prefix reuse, Brio photos (the windowed layers' rings,-# pictures, nested and stale photos), and /v1/brio and chat logprobs through the-# gateway. Every comparison is against a cold engine, to the last printed digit.+# The same fixture served: KV prefix reuse, System One photos (the windowed layers'+# rings, pictures, nested and stale photos), and /v1/systemone and chat logprobs+# through the gateway. Every comparison is against a cold engine..PHONY: mimo-tiny-serve-checkmimo-tiny-serve-check: mimo-tiny-generate mimo$(EXE)$(PYTHON) -m unittest -v tests.test_mimo_prefix_serve tests.test_brio_serve.MimoBrioServe \- tests.test_brio_api.MimoBrioEndToEnd+ tests.test_systemone_api.MimoSystemOneEndToEnd# Qwen3.8-Flash-Next text-only sibling. qwen38.c owns the direct checkpoint# loader and SERVE=1 protocol. With CUDA=1 it links the same expert tier asdiff --git a/c/coli b/c/coliindex ce75aec8..28a0ee85 100755--- a/c/coli+++ b/c/coli@@ -27,7 +27,7 @@ Configuration through environment variables or flags (also valid after the subco--topp P adaptive expert top-p --topk N fixed top-k--ngen N maximum response tokens --cap N cache slots/layer"""-import os, sys, subprocess, argparse, json, time, signal, shutil, threading, re, codecs, tempfile, textwrap, struct, shlex+import os, sys, subprocess, argparse, json, math, time, signal, shutil, threading, re, codecs, tempfile, textwrap, struct, shlex# input() only gets line editing and UP/DOWN history once the readline module# has been LOADED — without it the terminal's arrow-key escape sequences are@@ -1793,17 +1793,37 @@ def install_chat_completer(commands=None, arguments=None):readline.parse_and_bind("tab: complete")readline.set_completer(complete)+def conversation_state(msgs):+ """The conversation so far as one text state, a "role: content" line per+ message with text parts joined: what /decide sends as the context."""+ lines=[]+ for message in msgs:+ if not isinstance(message, dict): continue+ content=message.get("content")+ if isinstance(content, list):+ content="".join(part.get("text","") for part in content+ if isinstance(part, dict) and isinstance(part.get("text",""), str))+ if content:+ lines.append(f"{message.get('role','user')}: {content}")+ return "\n".join(lines)++def decide_request(model_id, msgs, question, options):+ """The POST /v1/systemone body of one /decide turn: the conversation as the+ state, the question as one `choice` whose labels are the options."""+ return {"model": model_id, "state": conversation_state(msgs),+ "questions": {"decide": {"type": "choice", "instructions": question,+ "criteria": {option: None for option in options}}}}+def chat_brio(a, base, model_id, msgs, question, options, w):"""Un giro di modalita System One dalla TUI (/decide): una richiesta, una distribuzione.- Il ciclo (fotografia del prefisso, una lettura per opzione, normalizzazione- per lunghezza) sta nel gateway, non qui: sono tre cose facili da sbagliare e- devono stare in un posto solo. Qui si manda la conversazione come contesto- e si disegnano le barre."""+ Il ciclo (fotografia del prefisso, una lettura per opzione, normalizzazione)+ sta nel gateway, non qui: sono tre cose facili da sbagliare e devono stare+ in un posto solo. Qui si manda la conversazione come stato a+ POST /v1/systemone, una domanda `choice`, e si disegnano le barre."""import urllib.request, urllib.error- body=json.dumps({"model":model_id,"messages":msgs,"question":question,- "options":options}).encode()- req=urllib.request.Request(base.rstrip("/")+"/v1/brio", data=body,+ body=json.dumps(decide_request(model_id, msgs, question, options)).encode()+ req=urllib.request.Request(base.rstrip("/")+"/v1/systemone", data=body,headers={"Content-Type":"application/json"})if a.api_key: req.add_header("Authorization", f"Bearer {a.api_key}")print(f"\n {C.teal}◆ System One{C.r}")@@ -1815,27 +1835,30 @@ def chat_brio(a, base, model_id, msgs, question, options, w):sp.stop()try: detail=json.loads(e.read().decode("utf-8","replace")).get("error",{}).get("message","")except Exception: detail=""- print(f" {C.yel}[il server ha rifiutato: HTTP {e.code}{' — '+detail if detail else ''}]{C.r}\n")+ print(f" {C.yel}[il server ha rifiutato: HTTP {e.code}{': '+detail if detail else ''}]{C.r}\n")returnexcept OSError as e:sp.stop(); print(f" {C.yel}[server irraggiungibile: {e}]{C.r}\n"); returnsp.stop()+ answer=(out.get("answers") or {}).get("decide") or {}+ probabilities=answer.get("probabilities") or {}+ ranked=sorted(((option, float(probabilities.get(option, 0.0))) for option in options),+ key=lambda item: -item[1])bars=max(10, min(30, w-34))- for choice in out.get("choices", []):- p=choice.get("p",0.0); filled=int(round(p*bars))- colour=C.grn if choice["option"]==out.get("answer") else C.dgray- print(f" {colour}{choice['option'][:22]:<22}{C.r} {colour}{'█'*filled}{C.r}"- f"{C.dgray}{'░'*(bars-filled)}{C.r} {p*100:5.1f}%"- f" {C.dim}{choice.get('tokens',0)} tok{C.r}")- h=out.get("entropy",1.0)+ for option, p in ranked:+ filled=int(round(p*bars))+ colour=C.grn if option==answer.get("choice") else C.dgray+ print(f" {colour}{option[:22]:<22}{C.r} {colour}{'█'*filled}{C.r}"+ f"{C.dgray}{'░'*(bars-filled)}{C.r} {p*100:5.1f}%")# L'entropia e la parte che la generazione non sa dare: non "qual e la- # risposta" ma "quanto il modello sa di saperlo".+ # risposta" ma "quanto il modello sa di saperlo". Normalizzata su log(n).+ h=-sum(p*math.log(p) for _, p in ranked if p>0)/math.log(max(len(ranked),2))verdict=(f"{C.grn}sure{C.r}" if h<.4 elsef"{C.yel}unsure{C.r}" if h<.8 else f"{C.yel}DOES NOT KNOW{C.r}")usage=out.get("usage",{})- print(f" {C.b}→ {out.get('answer','?')}{C.r} {C.dim}entropy {h:.3f}{C.r} ({verdict})")- print(f" {C.dim}{time.time()-t0:.2f}s · {usage.get('read_tokens',0)} tokens read · "- f"{usage.get('completion_tokens',0)} generated{C.r}\n")+ print(f" {C.b}→ {answer.get('choice','?')}{C.r} {C.dim}entropy {h:.3f}{C.r} ({verdict})")+ print(f" {C.dim}{time.time()-t0:.2f}s · {usage.get('input_tokens',0)} prompt tokens · "+ f"{usage.get('output_tokens',0)} option tokens read · nothing generated{C.r}\n")# Families whose template thinks by default but that coli chat starts with thinking# OFF. On a model that streams its experts from disk at about 1 tok/s, the defaultdiff --git a/c/openai_server.py b/c/openai_server.pyindex 5ab75f14..ef6724fa 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -4652,7 +4652,7 @@ def _engine_extension_args(engine_k):That is this helper's decision for THESE endpoints, not a property of the requestbuilder. `gbytes_before_ext` is a per-call-site parameter, and the other caller that- sends an extension key -- /v1/brio -- does not pass it and keeps the header it has+ sends an extension key -- /v1/systemone's scoring -- does not pass it and keeps the header it hasalways sent; changing that endpoint's wire is not this change's to make."""if not engine_k:return {}@@ -5058,7 +5058,7 @@ class Engine:# whole of its contract: a DATA tail on every generated token, and an ECHO frame# for EVERY prompt position (" nan 0" at position 0) unless a pin photo covers the# prefix -- which means never resuming a read-out from a live prefix. colibri.c- # (glm) and mimo.c do; the engines that score /v1/brio options but resume+ # (glm) and mimo.c do; the engines that score /v1/systemone options but resume# read-outs from a live prefix would answer `echo` with a hole. Token-id intake# is glm's alone: serve_codec.h, which mimo reads its frames with, has no `ids=`.self.supports_logprobs_echo = arch in ("glm", "mimo")@@ -5768,11 +5768,10 @@ def is_image_engine(engine):# The endpoints that only make sense for a chat model, refused with a pointer# when the model draws images instead.-TEXT_ENDPOINTS = ("/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/brio",- "/v1/systemone")+TEXT_ENDPOINTS = ("/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/systemone")# The endpoints that generate or score text with a language model, refused with a# pointer to /v1/systemone when the model is a decision engine (chat=0).-GENERATING_ENDPOINTS = ("/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/brio")+GENERATING_ENDPOINTS = ("/v1/chat/completions", "/v1/completions", "/v1/messages")IMAGE_OPTION_KEYS = ("default_width", "default_height", "default_steps", "min_side","max_side", "multiple")@@ -6391,8 +6390,6 @@ class APIHandler(BaseHTTPRequestHandler):self.chat_completion(body, request_id)elif path == "/v1/completions":self.completion(body, request_id)- elif path == "/v1/brio":- self.brio(body, request_id)elif path == "/v1/systemone":self.systemone(body, request_id)elif path == "/v1/messages":@@ -6414,163 +6411,48 @@ class APIHandler(BaseHTTPRequestHandler):pass- # ---------------------------------------------------------------- modalita brio+ # ---------------------------------------------------------------- il canale di scoring#- # Il modello non genera: si legge il logprob di ogni opzione ammessa e si- # normalizza sulle sole opzioni. Torna una distribuzione, non una stringa.+ # Il percorso di POST /v1/systemone su un modello linguistico. Il modello non+ # genera: si legge il logprob di ogni opzione ammessa e si normalizza sulle+ # sole opzioni. Torna una distribuzione, non una stringa. (Un motore di+ # decisione, decide=1, risponde da se' con DECIDE: _systemone_decide.)## PERCHE' IL CICLO STA QUI E NON NEL CLIENT. Servono tre cose facili da# sbagliare: fotografare il prefisso condiviso (pin) cosi ogni opzione paga- # solo i propri token; NON mettere l'elenco delle opzioni nel prompt (su- # qwen36 erano 48 token su 123, meta del risparmio); e normalizzare per- # lunghezza, perche' sommare i logprob penalizza le opzioni da piu token --- # misurato, la somma diceva "merge" dove la generazione greedy dello stesso- # modello diceva "request changes". Un client che rifacesse questo ciclo- # sbaglierebbe una di queste tre, e il risultato resterebbe plausibile.+ # solo i propri token; leggere l'opzione come continuazione della risposta e+ # non come coda di un elenco; e normalizzare, perche' somma e media dei+ # logprob danno risposte diverse quando le opzioni hanno lunghezze diverse.+ # Un client che rifacesse questo ciclo sbaglierebbe una di queste tre, e il+ # risultato resterebbe plausibile.#- # COSA TORNA. Non solo il vincitore: la probabilita di OGNI opzione e- # l'entropia. E' la differenza con la generazione, che una risposta la da- # sempre e con la stessa faccia: qui "non lo so" e' un numero.- # TRE FORME, UN ENDPOINT. `options` e' la domanda singola. `questions` e'- # un elenco di domande sullo stesso stato, ognuna con le sue opzioni: lo- # stato viene fotografato una volta e ogni domanda paga solo se stessa,- # che e' dove sta il 5,7x misurato. `schema` e' un oggetto campo -> valori- # ammessi: il server scrive lo scheletro JSON, casella per casella, e per- # ognuna legge il logprob di ciascun valore. Il JSON non puo' uscire- # malformato perche' non lo scrive il modello. Prima queste due forme- # esistevano solo come script di misura: chi integrava doveva riscriverle.- @staticmethod- def _brio_options(options, where, limit=64):- if not isinstance(options, list) or not options:- raise APIError(400, f"`{where}` must be a non-empty array of strings.", where)- if len(options) > limit:- raise APIError(400, f"`{where}` accepts at most {limit} entries.", where)- seen = set()- for option in options:- if not isinstance(option, str) or not option.strip():- raise APIError(400, f"Every entry of `{where}` must be a non-empty string.", where)- if option in seen:- raise APIError(400, f"Duplicate option in `{where}`: {option!r}.", where)- seen.add(option)- if len(options) < 2:- raise APIError(400, f"`{where}` needs at least two options to choose between.", where)- return options-- def brio(self, body, request_id, send=True):- # `send=False` returns the result instead of writing it: /v1/systemone- # builds a `questions` request and re-shapes the answer. `_max_options`- # is that caller's word too (Jev allows 255 labels); clamped.- option_limit = min(int(body.get("_max_options", 64) or 64), 255)- forms = [k for k in ("options", "questions", "schema") if body.get(k) is not None]- if len(forms) != 1:- raise APIError(400, "Provide exactly one of `options`, `questions` or `schema`.",- forms[0] if forms else "options")- form = forms[0]- question = body.get("question")- if question is not None and not isinstance(question, str):- raise APIError(400, "`question` must be a string.", "question")- options = questions = schema = None- if form == "options":- options = self._brio_options(body["options"], "options")- elif form == "questions":- raw = body["questions"]- if not isinstance(raw, list) or not raw:- raise APIError(400, "`questions` must be a non-empty array.", "questions")- if len(raw) > 64:- raise APIError(400, "`questions` accepts at most 64 entries.", "questions")- questions = []- for i, entry in enumerate(raw):- if not isinstance(entry, dict):- raise APIError(400, f"`questions[{i}]` must be an object.", "questions")- text = entry.get("question")- if not isinstance(text, str) or not text.strip():- raise APIError(400, f"`questions[{i}].question` must be a non-empty string.",- "questions")- per = entry.get("normalize", body.get("normalize", "sum"))- if per not in ("mean", "sum"):- raise APIError(400, "`normalize` must be \"mean\" or \"sum\".", "normalize")- questions.append((text, self._brio_options(entry.get("options"),- f"questions[{i}].options",- option_limit), per))- else:- raw = body["schema"]- if not isinstance(raw, dict) or not raw:- raise APIError(400, "`schema` must be a non-empty object of field: [values].",- "schema")- if len(raw) > 64:- raise APIError(400, "`schema` accepts at most 64 fields.", "schema")- schema = []- for field, values in raw.items():- if not isinstance(field, str) or not field.strip():- raise APIError(400, "Every `schema` field name must be a non-empty string.",- "schema")- if any(ch in field for ch in '"\\\n'):- raise APIError(400, f"`schema` field {field!r} cannot contain quotes, "- "backslashes or newlines.", "schema")- schema.append((field, self._brio_options(values, f"schema.{field}")))- task = body.get("task")- if task is not None and not isinstance(task, str):- raise APIError(400, "`task` must be a string.", "task")- state = body.get("state")- messages = body.get("messages")- if state is not None and not isinstance(state, str):- raise APIError(400, "`state` must be a string.", "state")- if state is None and isinstance(messages, list):- # La conversazione in corso FA da stato: e' quello che la TUI manda- # quando si scrive /brio a meta chat.- parts = []- for message_index, message in enumerate(messages):- if not isinstance(message, dict):- raise APIError(400, "Every message must be an object.", "messages")- content = message.get("content")- if isinstance(content, list):- text_parts = []- for part_index, piece in enumerate(content):- if not isinstance(piece, dict):- continue- text = piece.get("text", "")- if not isinstance(text, str):- raise APIError(400, "Text content parts require a string `text` field.",- f"messages.{message_index}.content.{part_index}.text")- text_parts.append(text)- content = "".join(text_parts)- if content:- parts.append(f"{message.get('role', 'user')}: {content}")- state = "\n".join(parts)- if not state and not question and form == "options":- raise APIError(400, "Provide `state`, `messages` or `question`.", "state")- if not state and form != "options" and not body.get("_empty_state_ok"):- raise APIError(400, f"`{form}` needs a `state` (or `messages`) to decide on.", "state")- # "sum" (the joint log-probability of the option as a continuation)- # is the default: "mean" compares per-token averages, which silently- # favors multi-token options whenever the menu mixes token counts —- # e.g. DENY (2 tokens) beating ALLOW (1) on every safe change in a- # 30-case benchmark. "mean" stays available for menus whose options- # tokenize to the same length, and warns when they do not.- normalize = body.get("normalize", "sum")- if normalize not in ("mean", "sum"):- raise APIError(400, "`normalize` must be \"mean\" or \"sum\".", "normalize")+ # Lo stato viene fotografato una volta e ogni domanda paga solo se stessa:+ # e' la forma in cui il canale rende (5,7x misurato contro la chat).+ # (Fino alla 1.12.1 questo ciclo aveva anche un endpoint suo, POST /v1/brio,+ # con le forme options/questions/schema. /v1/systemone e' ora l'unica API.)+ def _score_questions(self, state, questions, normalize="sum", pin_state=True,+ fixed=None, cache_slot=None):+ """Score every question's options against `state` through the engine's+ logprob channel. `questions` is a list of (question text, options).++ Returns (answers, usage, headers): per question the options sorted by+ probability, each with `p`, `logprob`, `mean_logprob` and `tokens`, and+ the normalised entropy; `prompt_tokens` (the longest prompt) and+ `read_tokens` (the option tokens read); the timing headers.++ `fixed` is a text read before the state and photographed once per slot+ (/v1/systemone's `prefix`); `pin_state` False skips the photo of the+ state. The slot defaults to the one derived from the part that does not+ change: the fixed text when there is one, else the state."""# Lo slot si sceglie dallo STATO, non dalla domanda: mille domande# diverse sullo stesso contesto devono cadere sullo stesso slot, o la# fotografia del prefisso condiviso non le serve a niente. E' la stessa# regola di conversation_cache_slot per la chat, con la chiave presa# dalla parte che non cambia.- cache_slot = body.get("cache_slot")if cache_slot is None:cache_slot = conversation_cache_slot(- [{"role": "system", "content": state or ""}], self.server.kv_slots)- if isinstance(cache_slot, bool) or not isinstance(cache_slot, int) \- or not 0 <= cache_slot < self.server.kv_slots:- raise APIError(400, "Invalid cache slot.", "cache_slot")-- # /v1/systemone's two knobs, private keys like _max_options: `_prefix`- # is a fixed text the client sends before a changing state (a game's- # rules), photographed so only the state and the question are read;- # `_pin_state` False skips the photo of the state, which costs a round- # trip and a snapshot and pays only if the state comes back.- fixed = body.get("_prefix") or ""+ [{"role": "system", "content": fixed or state or ""}], self.server.kv_slots)fixed_prefix = f"{fixed}\n\n" if fixed else ""- pin_state = body.get("_pin_state", True)state_prefix = fixed_prefix + (f"Context:\n{state}\n\n" if state else "")started = time.time()read_total = 0@@ -6650,20 +6532,13 @@ class APIHandler(BaseHTTPRequestHandler):return scored, round(entropy, 6), n_prefix# Lo stato da solo, fotografato per primo: e' il livello che tutte- # le domande (o tutte le caselle) condividono. Con un livello solo- # la domanda si rilegge una volta per opzione; con due, 176 token- # invece di 496 su quattro item (misurato).- #- # Vale anche per la forma `options`: dentro una singola richiesta lo- # stato si legge comunque una volta (lo snapshot dello stato viene- # ripristinato quando `choose` fotografa il prefisso completo), ma- # il punto di ritorno sullo stato condiviso serve TRA richieste. La- # pagina web manda una domanda per richiesta sullo stesso documento;- # senza questa fotografia ogni domanda rifarebbe il prefill di tutto- # il documento, buttando via il "read once" che e' il senso della- # modalita. Con essa, ogni domanda successiva paga solo i propri- # token. Il costo e' uno snapshot in piu' su una richiesta one-shot,- # riusato o sfrattato.+ # le domande condividono. Con un livello solo la domanda si rilegge+ # una volta per opzione; con due, 176 token invece di 496 su quattro+ # item (misurato). Il punto di ritorno sullo stato serve anche TRA+ # richieste: la pagina web manda una domanda per richiesta sullo+ # stesso documento, e senza la fotografia ognuna rifarebbe il+ # prefill di tutto il documento. Quando la fotografia non puo'+ # pagare (uno stato visto una volta sola) systemone la spegne.# The fixed prefix is photographed once per slot, not per request:# sending it again would read it again (an identical prompt is not a# strict prefix of itself, so no photo can resume it), which is the@@ -6677,66 +6552,25 @@ class APIHandler(BaseHTTPRequestHandler):n_state, _ = score(state_prefix, True)prompt_max = max(prompt_max, n_state)- if form == "options":- prefix = state_prefix- if question:- prefix += f"Question: {question}\n"- prefix += "Answer:"- scored, entropy, _ = choose(prefix, options, normalize)- result = {"object": "brio.choice", "answer": scored[0]["option"],- "entropy": entropy, "normalize": normalize, "choices": scored}-- elif form == "questions":- answers = []- for text, choices, norm in questions:- prefix = state_prefix + f"Question: {text}\nAnswer:"- scored, entropy, _ = choose(prefix, choices, norm)- answers.append({"question": text, "answer": scored[0]["option"],- "entropy": entropy, "normalize": norm,- "choices": scored})- result = {"object": "brio.answers", "answers": answers}-- else:- # Lo scheletro JSON e' DATO: parentesi, virgolette e nomi dei- # campi li scriviamo noi, il modello sceglie solo il valore. Ogni- # casella si fotografa con dentro le scelte gia fatte, cosi il- # campo dopo vede quelli prima, come nella generazione.- head = state_prefix + (f"Task: {task}\n" if task else "")- filled, fields = {}, []- for field, values in schema:- skeleton = "{" + "".join(- f'"{k}": {json.dumps(v)}, ' for k, v in filled.items())- prefix = head + skeleton + f'"{field}": "'- scored, entropy, _ = choose(prefix, values, normalize)- filled[field] = scored[0]["option"]- fields.append({"field": field, "value": scored[0]["option"],- "p": scored[0]["p"], "entropy": entropy,- "choices": scored})- result = {"object": "brio.schema", "json": filled, "fields": fields,- "normalize": normalize}-- result.update({- "id": "brio-" + uuid.uuid4().hex,- "created": int(time.time()),- "model": self.server.model_id,- "usage": {"prompt_tokens": prompt_max, "completion_tokens": 0,- "read_tokens": read_total,- "total_tokens": prompt_max + read_total},- })+ answers = []+ for text, choices in questions:+ prefix = state_prefix + f"Question: {text}\nAnswer:"+ scored, entropy, _ = choose(prefix, choices, normalize)+ answers.append({"question": text, "answer": scored[0]["option"],+ "entropy": entropy, "choices": scored})headers = {"x-colibri-queue-wait-ms": str(round(queue_wait * 1000)),"x-colibri-elapsed-ms": str(round((time.time() - started) * 1000))}- if not send:- result["_headers"] = headers- return result- self.send_json(200, result, request_id, headers)+ return answers, {"prompt_tokens": prompt_max, "read_tokens": read_total}, headers# ------------------------------------------------------------ Jev-compatible## POST /v1/systemone speaks the request and the reply of TypeSafe's Jev# API (docs.typesafe.ai/api): a client written for it points at colibri- # and changes the base URL, nothing else. The three primitives map onto- # the `questions` form of /v1/brio, the same channel: the state is- # photographed once and every question pays only its own tokens.+ # and changes the base URL, nothing else. It is colibri's one decision+ # API. On a language model the three primitives become closed questions+ # on the scoring channel above (_score_questions): the state is+ # photographed once and every question pays only its own tokens. A+ # decision engine gets the request as it is (DECIDE, _systemone_decide).## noul -> one yes/no question. `noul` is the probability of yes. The# optional criteria (what true and false mean) go into the@@ -6745,9 +6579,10 @@ class APIHandler(BaseHTTPRequestHandler):# go into the question text, because a label alone ("billing")# does not say what it means. `confidence` follows their# documented formula, (n * peak - 1) / (n - 1).- # score -> the levels of `criteria` are the options "1".."n"; `score`- # is the expected value under the distribution, `legend` the- # levels by number, `confidence` as for choice.+ # score -> the levels of `criteria` are the options "1".."n" for the+ # model; the reply numbers them from 0 as Jev does. `score` is+ # the expected level, `legend` the levels as sent,+ # `confidence` as for choice.## What differs, stated rather than hidden: `model` echoes the served# model, not "jev-latest"; `usage.output_tokens` counts the option tokens@@ -6860,55 +6695,44 @@ class APIHandler(BaseHTTPRequestHandler):return# A question with one option has its answer already: nothing to score.asked = [entry for entry in plan if len(entry[3]) > 1]- result = {"answers": [], "usage": {"prompt_tokens": 0, "read_tokens": 0}}+ scored, usage, headers = [], {"prompt_tokens": 0, "read_tokens": 0}, Noneif asked:# Photograph the state when it can pay: within this request (two or# more questions read it), or because it came back from an earlier# one. A state that changes on every call (a game, a feed) is read# straight through instead. `pin_state` says it explicitly.- if options["pin_state"] is None:- options["pin_state"] = len(asked) > 1 or self.server.state_seen(state or "")- else:- self.server.state_seen(state or "")- inner = {"state": state or "", "_max_options": 255, "_empty_state_ok": True,- "normalize": options["normalize"], "_pin_state": options["pin_state"],- "questions": [{"question": text, "options": choices}- for _, _, text, choices, _ in asked]}- if options["prefix"]:- inner["_prefix"] = options["prefix"]- if options["cache_slot"] is not None:- inner["cache_slot"] = options["cache_slot"]- elif options["prefix"]:- # The photo of the prefix lives in a slot: route by the part- # that does not change, as the state is routed without one.- inner["cache_slot"] = conversation_cache_slot(- [{"role": "system", "content": options["prefix"]}], self.server.kv_slots)- result = self.brio(inner, request_id, send=False)- scored = iter(result["answers"])+ pin_state = options["pin_state"]+ seen = self.server.state_seen(state or "")+ if pin_state is None:+ pin_state = len(asked) > 1 or seen+ scored, usage, headers = self._score_questions(+ state or "", [(text, choices) for _, _, text, choices, _ in asked],+ normalize=options["normalize"], pin_state=pin_state,+ fixed=options["prefix"], cache_slot=options["cache_slot"])+ scored = iter(scored)answers = {}- for qid, kind, _, options, levels in plan:- if len(options) > 1:+ for qid, kind, _, choices, levels in plan:+ if len(choices) > 1:got = next(scored)p = {c["option"]: c["p"] for c in got["choices"]}else:- p = {options[0]: 1.0}+ p = {choices[0]: 1.0}if kind == "noul":answers[qid] = {"type": "noul", "noul": round(float(p.get("yes", 0.0)), 6)}elif kind == "choice":- answers[qid] = {"type": "choice", "choice": max(options, key=lambda o: p[o]),- "probabilities": {o: round(float(p[o]), 6) for o in options},+ answers[qid] = {"type": "choice", "choice": max(choices, key=lambda o: p[o]),+ "probabilities": {o: round(float(p[o]), 6) for o in choices},"confidence": self._systemone_confidence(p.values())}else:- values = [float(p[o]) for o in options]+ values = [float(p[o]) for o in choices]answers[qid] = {"type": "score","score": round(sum(i * v for i, v in enumerate(values)), 6),"legend": {str(i): legend for i, legend in enumerate(levels)},"probabilities": {str(i): round(v, 6) for i, v in enumerate(values)},"confidence": self._systemone_confidence(values)}- self.send_json(200, self._systemone_reply(answers, request_id,- result["usage"]["prompt_tokens"],- result["usage"]["read_tokens"]),- request_id, result.get("_headers"))+ self.send_json(200, self._systemone_reply(answers, request_id, usage["prompt_tokens"],+ usage["read_tokens"]),+ request_id, headers)def _systemone_options(self, body):"""colibri's optional fields on /v1/systemone, none of which a Jev clientdiff --git a/c/tests/test_brio_api.py b/c/tests/test_brio_api.pydeleted file mode 100644index 075748ac..00000000--- a/c/tests/test_brio_api.py+++ /dev/null@@ -1,441 +0,0 @@-"""The three forms of POST /v1/brio, driven through the gateway with a scoring-engine we control.--`options` is one closed question. `questions` is many questions on one state,-each with its own options, and the state must be photographed ONCE: that is-where the measured 5.7x lives, and a handler that re-reads the state per-question would still answer correctly while throwing the saving away, so the-pin order is asserted, not just the answers. `schema` fills a JSON object one-field at a time; the skeleton is data the server writes, so the field after-must see the value chosen for the field before, and nothing is ever generated.--The fake engine tokenises on whitespace and scores an option by a table, so-every answer here is chosen by the test, not by chance. It records every-call: prompt, max_tokens and pin, which is what the assertions read.--MimoBrioEndToEnd puts the real MiMo engine behind the same server, on the tiny-fixture (`make mimo mimo-tiny-generate`; skipped without them): the endpoint-reaches it, every option after the photo reads only its own tokens, the scores-equal a cold engine's, and chat logprobs pass the gateway's gate.-"""-import json-import math-import os-import subprocess-import sys-import threading-import unittest-from pathlib import Path-from unittest.mock import patch-from urllib.error import HTTPError-from urllib.request import Request, urlopen--sys.path.insert(0, str(Path(__file__).resolve().parent))-import mimo_serve_fixture # noqa: E402-import openai_server # noqa: E402-from family_registry import family_by_id # noqa: E402-from openai_server import APIServer # noqa: E402--STATE = "340 lines across 8 files, no tests. CI is green but nothing covers that path."---class ScoringEngine:- """Scores like the real channel, deterministically.-- `table` maps an option string to the mean log-probability its tokens get;- anything not in the table scores -5.0. A pinned call answers with ACCEPT- (prompt_tokens) and one ECHO per position, like an engine with the channel."""-- def __init__(self, table):- self.table = table- self.calls = []- self.kv_slots = 1-- def generate(self, prompt, max_tokens, temperature, top_p, on_text, cache_slot=0,- cancelled=None, grammar=None, stopped=None, on_accept=None, audio=None,- on_tool=None, image=None, logprobs=0, pin=False, on_echo=None):- self.calls.append({"prompt": prompt, "max_tokens": max_tokens, "pin": bool(pin),- "logprobs": logprobs})- words = prompt.split()- if on_accept:- on_accept({"prompt_tokens": len(words)})- if on_echo and logprobs:- # The option is whatever follows the last "Answer:" or the last- # opening quote of a skeleton cell; score its words from the table.- option = None- for key in self.table:- if prompt.endswith(" " + key):- option = key- per_token = self.table.get(option, -5.0)- for pos, _word in enumerate(words):- on_echo({"pos": pos, "logprob": per_token if option and pos >= len(words) - len(option.split()) else -1.0})-- def close(self):- pass---class BrioApi(unittest.TestCase):- def serve(self, table):- self.engine = ScoringEngine(table)- self.server = APIServer(("127.0.0.1", 0), self.engine, "test-model")- self.addCleanup(self.server.server_close)- self.addCleanup(self.server.shutdown)- import threading- threading.Thread(target=self.server.serve_forever, daemon=True).start()- self.base = f"http://127.0.0.1:{self.server.server_port}"-- def post(self, body):- request = Request(self.base + "/v1/brio", data=json.dumps(body).encode(),- headers={"Content-Type": "application/json"})- with urlopen(request, timeout=10) as response:- return json.loads(response.read())-- def post_error(self, body):- try:- self.post(body)- except HTTPError as error:- return error.code, json.loads(error.read())- self.fail("expected an error")-- def pins(self):- return [c["prompt"] for c in self.engine.calls if c["pin"]]-- # ---- options: the single form is unchanged ------------------------------- def test_single_form_still_answers_and_never_generates(self):- self.serve({"merge": -3.0, "request changes": -0.2, "close": -4.0})- out = self.post({"model": "test-model", "state": STATE,- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]})- self.assertEqual(out["object"], "brio.choice")- self.assertEqual(out["answer"], "request changes")- self.assertEqual(out["usage"]["completion_tokens"], 0)- self.assertTrue(all(c["max_tokens"] == 0 for c in self.engine.calls))- # Two photographs and no more: the shared state on its own, then the- # whole prefix. The options are never pinned. The state photograph is- # the return point that lets a later question on the same document- # reuse the snapshot instead of re-reading it (asserted below).- pins = self.pins()- self.assertEqual(len(pins), 2, pins)- self.assertEqual(pins[0], f"Context:\n{STATE}\n\n")- self.assertTrue(pins[1].startswith(pins[0]))- self.assertTrue(pins[1].endswith("Answer:"))-- def test_options_form_pins_the_shared_state_for_reuse_across_requests(self):- # The web asks one question per request on the same document. The state- # must be photographed on its own each time, so the engine has a strict- # prefix to restore and every question after the first pays only its own- # tokens instead of re-reading the whole document -- the "read once" the- # mode exists for. A handler that folded the state into the question- # prefix only would still answer correctly while re-reading it, so the- # pins are asserted, not just the answers.- self.serve({"merge": -3.0, "request changes": -0.2, "close": -4.0,- "yes": -0.1, "no": -2.0})- self.post({"model": "test-model", "state": STATE,- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]})- self.assertEqual([p for p in self.pins() if p == f"Context:\n{STATE}\n\n"],- [f"Context:\n{STATE}\n\n"])- self.post({"model": "test-model", "state": STATE,- "question": "Does it need tests?", "options": ["yes", "no"]})- # both requests photographed the same shared state prefix: the return- # point exists for the second question, not only the first- state_pins = [p for p in self.pins() if p == f"Context:\n{STATE}\n\n"]- self.assertEqual(len(state_pins), 2, self.pins())- # and every question prefix extends that shared state- question_pins = [p for p in self.pins() if p.endswith("Answer:")]- self.assertEqual(len(question_pins), 2, self.pins())- for pin in question_pins:- self.assertTrue(pin.startswith(f"Context:\n{STATE}\n\n"))-- # ---- questions: many on one state ----------------------------------------- def test_questions_share_one_state_photograph(self):- self.serve({"merge": -3.0, "request changes": -0.2, "close": -4.0,- "yes": -0.1, "no": -2.0, "high": -0.3, "low": -1.5})- out = self.post({"model": "test-model", "state": STATE, "questions": [- {"question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]},- {"question": "Does it need tests?", "options": ["yes", "no"]},- {"question": "How risky is it?", "options": ["high", "low"], "normalize": "sum"},- ]})- self.assertEqual(out["object"], "brio.answers")- self.assertEqual([a["answer"] for a in out["answers"]],- ["request changes", "yes", "high"])- self.assertEqual([a["normalize"] for a in out["answers"]], ["sum", "sum", "sum"])- for answer in out["answers"]:- self.assertAlmostEqual(sum(c["p"] for c in answer["choices"]), 1.0, places=6)- self.assertGreaterEqual(answer["entropy"], 0.0)- self.assertLessEqual(answer["entropy"], 1.0)- # The state is photographed exactly once, first, on its own; then each- # question once. Options are never pinned. This is the two-level order- # that makes the second question cost only its own words.- pins = self.pins()- self.assertEqual(len(pins), 4, pins)- self.assertEqual(pins[0], f"Context:\n{STATE}\n\n")- for pin, entry in zip(pins[1:], out["answers"]):- self.assertTrue(pin.startswith(pins[0]), "a question prefix must extend the state")- self.assertTrue(pin.endswith(f"Question: {entry['question']}\nAnswer:"))- self.assertEqual(out["usage"]["completion_tokens"], 0)- self.assertEqual(out["usage"]["read_tokens"],- sum(c["tokens"] for a in out["answers"] for c in a["choices"]))-- def test_default_normalize_is_sum(self):- # The default was "mean", whose per-token averages silently favor- # multi-token options on any menu that mixes token counts; "sum" is- # the joint log-probability and the only safe default.- self.serve({"merge": -3.0, "close": -4.0})- out = self.post({"model": "test-model", "state": STATE,- "question": "What should the reviewer do?",- "options": ["merge", "close"]})- self.assertEqual(out["normalize"], "sum")-- def test_mean_with_unequal_option_token_counts_warns(self):- import contextlib- import io- self.serve({"merge": -3.0, "request changes": -0.2})- stderr = io.StringIO()- with contextlib.redirect_stderr(stderr):- self.post({"model": "test-model", "state": STATE,- "question": "What should the reviewer do?",- "options": ["merge", "request changes"],- "normalize": "mean"})- self.assertIn("unequal option token counts", stderr.getvalue())- self.assertIn("merge=1", stderr.getvalue())- # Equal token counts stay quiet — mean is valid there. (The [api]- # request log also lands on stderr; only the bias warning matters.)- self.serve({"yes": -0.1, "no": -2.0})- stderr = io.StringIO()- with contextlib.redirect_stderr(stderr):- self.post({"model": "test-model", "state": STATE,- "question": "Ship it?", "options": ["yes", "no"],- "normalize": "mean"})- self.assertNotIn("unequal option token counts", stderr.getvalue())-- # ---- schema: a JSON object filled one cell at a time --------------------- def test_schema_fills_cells_in_order_and_each_cell_sees_the_ones_before(self):- self.serve({"merge": -3.0, "request changes": -0.2, "close": -4.0,- "yes": -0.1, "no": -2.0, "engine": -0.05, "docs": -3.0})- out = self.post({"model": "test-model", "state": STATE,- "task": "Review this pull request.",- "schema": {"decision": ["merge", "request changes", "close"],- "needs_tests": ["yes", "no"],- "area": ["engine", "docs"]}})- self.assertEqual(out["object"], "brio.schema")- self.assertEqual(out["json"], {"decision": "request changes",- "needs_tests": "yes", "area": "engine"})- self.assertEqual([f["field"] for f in out["fields"]],- ["decision", "needs_tests", "area"])- # the JSON is valid by construction and round-trips- self.assertEqual(json.loads(json.dumps(out["json"])), out["json"])- pins = self.pins()- self.assertEqual(len(pins), 4, pins) # state, then one per cell- self.assertTrue(pins[1].endswith('Task: Review this pull request.\n{"decision": "'))- # the second cell's skeleton carries the first cell's chosen value- self.assertTrue(pins[2].endswith('{"decision": "request changes", "needs_tests": "'))- self.assertTrue(pins[3].endswith(- '{"decision": "request changes", "needs_tests": "yes", "area": "'))- self.assertEqual(out["usage"]["completion_tokens"], 0)- self.assertTrue(all(c["max_tokens"] == 0 for c in self.engine.calls))- for field in out["fields"]:- self.assertIn("p", field)- self.assertIn("entropy", field)-- def test_schema_value_with_a_quote_is_written_as_valid_json(self):- self.serve({'say "hi"': -0.1, "stay quiet": -3.0})- out = self.post({"model": "test-model", "state": STATE,- "schema": {"reply": ['say "hi"', "stay quiet"],- "again": ['say "hi"', "stay quiet"]}})- self.assertEqual(out["json"]["reply"], 'say "hi"')- # the skeleton for the second cell must escape the first cell's value,- # or the JSON the server claims to build would not parse- self.assertIn('"reply": "say \\"hi\\"", "again": "', self.pins()[2])-- # ---- validation ----------------------------------------------------------- def test_exactly_one_form(self):- self.serve({})- code, body = self.post_error({"model": "test-model", "state": STATE,- "options": ["a", "b"], "questions": []})- self.assertEqual(code, 400)- self.assertIn("exactly one", body["error"]["message"])- code, _ = self.post_error({"model": "test-model", "state": STATE})- self.assertEqual(code, 400)-- def test_every_option_set_needs_two_entries(self):- self.serve({})- code, body = self.post_error({"model": "test-model", "state": STATE,- "schema": {"decision": ["merge"]}})- self.assertEqual(code, 400)- self.assertIn("schema.decision", body["error"]["message"])- code, body = self.post_error({"model": "test-model", "state": STATE,- "questions": [{"question": "q?", "options": ["only"]}]})- self.assertEqual(code, 400)- self.assertIn("questions[0].options", body["error"]["message"])-- def test_questions_and_schema_need_a_state(self):- self.serve({})- code, body = self.post_error({"model": "test-model",- "questions": [{"question": "q?", "options": ["a", "b"]}]})- self.assertEqual(code, 400)- self.assertIn("state", body["error"]["message"])-- def test_non_string_message_text_is_a_client_error(self):- self.serve({})- code, body = self.post_error({- "model": "test-model", "options": ["yes", "no"],- "messages": [{"role": "user", "content": [{"type": "text", "text": 7}]}],- })- self.assertEqual(code, 400)- self.assertEqual(body["error"]["param"], "messages.0.content.0.text")- self.assertEqual(self.engine.calls, [])- out = self.post({- "model": "test-model", "options": ["yes", "no"],- "messages": [{"role": "user", "content": [{"type": "text", "text": "Ship it?"}]}],- })- self.assertEqual(out["object"], "brio.choice")- self.assertEqual(self.pins()[0], "Context:\nuser: Ship it?\n\n")-- def test_schema_field_names_that_would_break_the_skeleton_are_refused(self):- self.serve({})- code, body = self.post_error({"model": "test-model", "state": STATE,- "schema": {'bad"name': ["a", "b"]}})- self.assertEqual(code, 400)- self.assertIn("quotes", body["error"]["message"])---class _Recorder:- """The real engine, with every call it is given written down: the prompt, the- pin, the ACCEPT count and the ECHO positions -- what the saving is read from."""-- def __init__(self, engine):- self.engine = engine- self.kv_slots = engine.kv_slots- self.calls = []-- def generate(self, prompt, *args, on_echo=None, on_accept=None, pin=False, **kwargs):- call = {"prompt": prompt, "pin": bool(pin), "echo": [], "accept": None}- self.calls.append(call)-- def echo(record):- call["echo"].append(record["pos"])- if on_echo:- on_echo(record)-- def accept(value):- call["accept"] = value.get("prompt_tokens")- if on_accept:- on_accept(value)-- return self.engine.generate(prompt, *args, on_echo=echo, on_accept=accept,- pin=pin, **kwargs)-- def __getattr__(self, name):- return getattr(self.engine, name)---def _cold_option_score(prefix, option):- """What one option scores on a fresh engine that reads the whole prompt: the sum- of the ECHO log-probabilities past the prefix, from the frames themselves."""- env = dict(os.environ, **mimo_serve_fixture.engine_env())- p = subprocess.Popen([str(mimo_serve_fixture.ENGINE), "8"], env=env,- stdin=subprocess.PIPE, stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL)- try:- while b"READY" not in p.stdout.readline():- pass- n_prefix, values = None, []- for rid, text in ((1, prefix), (2, prefix + " " + option)):- data = text.encode()- p.stdin.write(f"SUBMIT {rid} 0 {len(data)} 0 0 1 logprobs=1\n".encode()- + data + b"\n")- p.stdin.flush()- while True:- fields = p.stdout.readline().split()- if fields[0] == b"ECHO":- p.stdout.read(int(fields[2]) + 1)- if rid == 2 and int(fields[3]) >= n_prefix and fields[4] != b"nan":- values.append(float(fields[4]))- elif fields[0] == b"ACCEPT" and rid == 1:- n_prefix = int(fields[2])- elif fields[0] in (b"DONE", b"ERROR"):- break- # sum(), as the endpoint adds them: on Python 3.12 it is compensated, and a- # plain running total differs from it in the last bits- return sum(values), len(values)- finally:- p.stdin.close()- p.wait(timeout=30)- p.stdout.close()--[email protected](mimo_serve_fixture.available(),- "mimo is not built or the tiny MiMo fixture is absent "- "(make mimo mimo-tiny-generate)")-class MimoBrioEndToEnd(unittest.TestCase):- STATE = ("The release is late, the tests are red and the changelog is empty. "- "Two reviewers approved it last week.")- OPTIONS = ["ship it", "wait", "wait until the tests pass and the changelog is written"]-- def setUp(self):- engine = openai_server.Engine(- mimo_serve_fixture.ENGINE, mimo_serve_fixture.served_fixture(), cap=8,- env=dict(os.environ, **mimo_serve_fixture.engine_env()),- family=family_by_id("mimo"))- self.addCleanup(engine.process.stdout.close)- self.addCleanup(engine.close)- self.engine = _Recorder(engine)- self.server = APIServer(("127.0.0.1", 0), self.engine, "mimo-tiny")- self.addCleanup(self.server.server_close)- self.addCleanup(self.server.shutdown)- threading.Thread(target=self.server.serve_forever, daemon=True).start()- self.base = f"http://127.0.0.1:{self.server.server_port}"-- def post(self, path, body):- request = Request(self.base + path, data=json.dumps(body).encode(),- headers={"Content-Type": "application/json"})- with urlopen(request, timeout=120) as response:- return json.loads(response.read())-- def test_options_read_only_their_own_tokens_and_score_like_a_cold_engine(self):- out = self.post("/v1/brio", {"model": "mimo-tiny", "state": self.STATE,- "question": "What should we do?",- "options": self.OPTIONS})- self.assertEqual(out["object"], "brio.choice")- self.assertIn(out["answer"], self.OPTIONS)- self.assertEqual(out["usage"]["completion_tokens"], 0)- self.assertAlmostEqual(sum(c["p"] for c in out["choices"]), 1.0, places=9)-- calls = self.engine.calls- state, prefix, options = calls[0], calls[1], calls[2:]- self.assertTrue(state["pin"] and prefix["pin"])- self.assertEqual(len(options), len(self.OPTIONS))- # The question resumes from the state's photo, every option from the- # question's: each read-out starts exactly where the photo ends and covers- # nothing before it. A fallback to a full recompute would read from 0.- self.assertEqual(min(prefix["echo"]), state["accept"])- for call in options:- self.assertEqual(sorted(call["echo"]),- list(range(prefix["accept"], call["accept"])),- f"{call['prompt']!r} did not resume from the photo")- prompt = prefix["prompt"]- by_option = {c["option"]: c for c in out["choices"]}- for option in self.OPTIONS:- total, rows = _cold_option_score(prompt, option)- self.assertEqual(by_option[option]["tokens"], rows)- self.assertEqual(by_option[option]["logprob"], total,- f"{option!r}: the photo scored differently from a cold engine")-- def test_chat_logprobs_reach_the_engine(self):- with patch("openai_server.ARCH", "mimo"):- out = self.post("/v1/chat/completions", {- "model": "mimo-tiny", "max_tokens": 6, "logprobs": True,- "top_logprobs": 2, "enable_thinking": False,- "messages": [{"role": "user", "content": "Ship it?"}]})- choice = out["choices"][0]- entries = choice["logprobs"]["content"]- self.assertTrue(entries, "no per-token logprobs came back")- for entry in entries:- self.assertLessEqual(entry["logprob"], 0.0)- self.assertEqual(len(entry["top_logprobs"]), 2)---if __name__ == "__main__":- unittest.main()diff --git a/c/tests/test_decision_serve.py b/c/tests/test_decision_serve.pyindex c1aba8fd..79f28957 100644--- a/c/tests/test_decision_serve.py+++ b/c/tests/test_decision_serve.py@@ -250,8 +250,7 @@ class DecisionGateway(unittest.TestCase):self.serve(FakeDecisionEngine({}))for path, body in (("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}),("/v1/completions", {"prompt": "hi"}),- ("/v1/messages", {"max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]}),- ("/v1/brio", {"state": "x", "options": ["a", "b"]})):+ ("/v1/messages", {"max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]})):with self.subTest(path=path):status, error = self.post_error(path, dict(body, model="laya"))self.assertEqual(status, 400)@@ -259,6 +258,11 @@ class DecisionGateway(unittest.TestCase):self.assertEqual(error["error"]["code"], "unsupported_endpoint")self.assertIn("POST /v1/systemone", error["error"]["message"])+ def test_v1_brio_is_gone_here_too(self):+ self.serve(FakeDecisionEngine({}))+ status, error = self.post_error("/v1/brio", {"model": "laya", "state": "x", "options": ["a", "b"]})+ self.assertEqual((status, error["error"]["code"]), (404, "not_found"))+def test_models_card_and_health_say_decision(self):self.serve(FakeDecisionEngine({}))with urlopen(self.base + "/v1/models", timeout=10) as response:diff --git a/c/tests/test_deepseek_v4_brio.py b/c/tests/test_deepseek_v4_brio.pyindex dae48141..3bfdc66e 100644--- a/c/tests/test_deepseek_v4_brio.py+++ b/c/tests/test_deepseek_v4_brio.py@@ -1,7 +1,7 @@#!/usr/bin/env python3"""The numeric channel on the DeepSeek V4 serve path (SUBMIT logprobs=k / pin=1).-This is what `POST /v1/brio` speaks (docs/systemone.md), and #1648 found that this+This is what `POST /v1/systemone` speaks to a language model (docs/systemone.md), and #1648 found that thisengine accepted the header and then refused the request. The properties undertest are the exact ones a closed-set caller relies on:diff --git a/c/tests/test_systemone_api.py b/c/tests/test_systemone_api.pyindex 9005ce5a..18acb181 100644--- a/c/tests/test_systemone_api.py+++ b/c/tests/test_systemone_api.py@@ -1,29 +1,76 @@-"""POST /v1/systemone: the request and the reply of TypeSafe's Jev API, served-by the brio channel.+"""POST /v1/systemone: the request and the reply of TypeSafe's Jev API, and+colibri's one decision API.A client written for Jev sends `state`, `model` and a map of questions typednoul / choice / score, and reads `answers` keyed by its own ids plus-`usage.input_tokens/output_tokens`. This pins the mapping onto the `questions`-form of /v1/brio with the deterministic scoring engine of test_brio_api: what-each primitive puts in the prompt, what comes back, the confidence formula-their docs give, that any model name is accepted on this route, and that the-state is still photographed once for all the questions.+`usage.input_tokens/output_tokens`. On a language model each question is+scored through the engine's logprob channel; this pins that path with a+deterministic scoring engine: what each primitive puts in the prompt, what+comes back, the confidence formula their docs give, that any model name is+accepted on this route, that nothing is generated, and which photographs the+state and the questions get. (Up to 1.12.1 the same channel had its own route,+POST /v1/brio; it is gone, and the test that it is gone is here.)++MimoSystemOneEndToEnd puts the real MiMo engine behind the same server, on the+tiny fixture (`make mimo mimo-tiny-generate`; skipped without them): every+option after the photo reads only its own tokens, and the probabilities equal+a cold engine's."""import http.clientimport jsonimport math+import os+import subprocess+import sysimport threadingimport timeimport unittest+from pathlib import Path+from unittest.mock import patchfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopen-import openai_server-from openai_server import APIServer, cors_origin_list-if __package__:- from .test_brio_api import ScoringEngine-else:- from test_brio_api import ScoringEngine+sys.path.insert(0, str(Path(__file__).resolve().parent))+import mimo_serve_fixture # noqa: E402+import openai_server # noqa: E402+from family_registry import family_by_id # noqa: E402+from openai_server import APIServer, cors_origin_list # noqa: E402+++class ScoringEngine:+ """Scores like the real channel, deterministically.++ `table` maps an option string to the mean log-probability its tokens get;+ anything not in the table scores -5.0. A pinned call answers with ACCEPT+ (prompt_tokens) and one ECHO per position, like an engine with the channel."""++ def __init__(self, table):+ self.table = table+ self.calls = []+ self.kv_slots = 1++ def generate(self, prompt, max_tokens, temperature, top_p, on_text, cache_slot=0,+ cancelled=None, grammar=None, stopped=None, on_accept=None, audio=None,+ on_tool=None, image=None, logprobs=0, pin=False, on_echo=None):+ self.calls.append({"prompt": prompt, "max_tokens": max_tokens, "pin": bool(pin),+ "logprobs": logprobs})+ words = prompt.split()+ if on_accept:+ on_accept({"prompt_tokens": len(words)})+ if on_echo and logprobs:+ # The option is whatever follows the last "Answer:" or the last+ # opening quote of a skeleton cell; score its words from the table.+ option = None+ for key in self.table:+ if prompt.endswith(" " + key):+ option = key+ per_token = self.table.get(option, -5.0)+ for pos, _word in enumerate(words):+ on_echo({"pos": pos, "logprob": per_token if option and pos >= len(words) - len(option.split()) else -1.0})++ def close(self):+ pass+STATE = ("Hi, I've been trying to connect my Stripe account for 3 days and the ""integration keeps failing. I'm losing sales. Please help ASAP.")@@ -202,9 +249,34 @@ class SystemOneApi(unittest.TestCase):pins = self.pins()self.assertEqual(len(pins), 4, pins) # the state, then each question onceself.assertEqual(pins[0], f"Context:\n{STATE}\n\n")+ # every question prefix extends the state's photo and ends where an+ # option is read as the answer's continuation; options are never pinned+ for pin in pins[1:]:+ self.assertTrue(pin.startswith(pins[0]), "a question prefix must extend the state")+ self.assertTrue(pin.endswith("\nAnswer:"), pin[-40:])+ # nothing is generated: every engine call reads the prompt and stops+ self.assertTrue(all(c["max_tokens"] == 0 and c["logprobs"] for c in self.engine.calls))self.assertEqual(set(out["usage"]), {"input_tokens", "output_tokens", "cost"})self.assertGreater(out["usage"]["input_tokens"], 0)- self.assertGreater(out["usage"]["output_tokens"], 0)+ self.assertEqual(out["usage"]["output_tokens"], 6) # two one-token options x three++ def test_mean_with_unequal_option_token_counts_warns(self):+ import contextlib+ import io+ self.serve({"merge": -3.0, "request changes": -0.2, "yes": -0.1, "no": -2.0})+ unequal = {"q": {"type": "choice", "criteria": {"merge": None, "request changes": None}}}+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ self.post({"state": STATE, "questions": unequal, "normalize": "mean"})+ self.assertIn("unequal option token counts", stderr.getvalue())+ self.assertIn("merge=1", stderr.getvalue())+ # Equal token counts stay quiet: mean is valid there. (The [api] request+ # log also lands on stderr; only the bias warning matters.)+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ self.post({"state": STATE, "questions": {"q": {"type": "noul", "instructions": "?"}},+ "normalize": "mean"})+ self.assertNotIn("unequal option token counts", stderr.getvalue())def test_validation_errors_are_422(self):self.serve({})@@ -338,15 +410,51 @@ class SystemOneApi(unittest.TestCase):self.assertEqual(card["name"], "test-model")self.assertRegex(card["release_date"], r"^\d{4}-\d{2}-\d{2}$")- def test_brio_route_still_checks_the_model_name(self):+ def test_v1_brio_is_gone(self):+ """/v1/systemone is the one decision API; the route that scored closed+ sets on its own up to 1.12.1 answers like any unknown route."""self.serve({"a": -0.1, "b": -1.0})request = Request(self.base + "/v1/brio",- data=json.dumps({"model": "jev-latest", "state": STATE,+ data=json.dumps({"model": "test-model", "state": STATE,"options": ["a", "b"]}).encode(),headers={"Content-Type": "application/json"})with self.assertRaises(HTTPError) as caught:urlopen(request, timeout=10)self.assertEqual(caught.exception.code, 404)+ self.assertEqual(json.loads(caught.exception.read())["error"]["code"], "not_found")+ self.assertEqual(self.engine.calls, [])+++class DecideCommand(unittest.TestCase):+ """`/decide` in coli chat posts to /v1/systemone: the conversation so far as+ the state, the question as one choice whose labels are the options."""++ def test_the_tui_request_is_a_systemone_request(self):+ import importlib.machinery+ import importlib.util+ loader = importlib.machinery.SourceFileLoader(+ "coli_decide_test", str(Path(__file__).resolve().parent.parent / "coli"))+ spec = importlib.util.spec_from_loader(loader.name, loader)+ cli = importlib.util.module_from_spec(spec)+ loader.exec_module(cli)+ msgs = [{"role": "user", "content": "The PR has no tests."},+ {"role": "assistant", "content": [{"type": "text", "text": "Noted."},+ {"type": "image_url", "image_url": {"url": "x"}}]}]+ body = cli.decide_request("qwen36", msgs, "What now?", ["merge", "request changes"])+ self.assertEqual(body["state"], "user: The PR has no tests.\nassistant: Noted.")+ self.assertEqual(body["questions"], {"decide": {+ "type": "choice", "instructions": "What now?",+ "criteria": {"merge": None, "request changes": None}}})+ engine = ScoringEngine({"merge": -2.0, "request changes": -0.1})+ server = APIServer(("127.0.0.1", 0), engine, "qwen36")+ self.addCleanup(server.server_close)+ self.addCleanup(server.shutdown)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ request = Request(f"http://127.0.0.1:{server.server_port}/v1/systemone",+ data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})+ with urlopen(request, timeout=10) as response:+ out = json.loads(response.read())+ self.assertEqual(out["answers"]["decide"]["choice"], "request changes")class CorsOrigins(unittest.TestCase):@@ -360,5 +468,147 @@ class CorsOrigins(unittest.TestCase):("https://ui.example", "http://game.local:8080"))+class _Recorder:+ """The real engine, with every call it is given written down: the prompt, the+ pin, the ACCEPT count and the ECHO positions -- what the saving is read from."""++ def __init__(self, engine):+ self.engine = engine+ self.kv_slots = engine.kv_slots+ self.calls = []++ def generate(self, prompt, *args, on_echo=None, on_accept=None, pin=False, **kwargs):+ call = {"prompt": prompt, "pin": bool(pin), "echo": [], "accept": None}+ self.calls.append(call)++ def echo(record):+ call["echo"].append(record["pos"])+ if on_echo:+ on_echo(record)++ def accept(value):+ call["accept"] = value.get("prompt_tokens")+ if on_accept:+ on_accept(value)++ return self.engine.generate(prompt, *args, on_echo=echo, on_accept=accept,+ pin=pin, **kwargs)++ def __getattr__(self, name):+ return getattr(self.engine, name)+++def _cold_option_score(prefix, option):+ """What one option scores on a fresh engine that reads the whole prompt: the sum+ of the ECHO log-probabilities past the prefix, from the frames themselves."""+ env = dict(os.environ, **mimo_serve_fixture.engine_env())+ p = subprocess.Popen([str(mimo_serve_fixture.ENGINE), "8"], env=env,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL)+ try:+ while b"READY" not in p.stdout.readline():+ pass+ n_prefix, values = None, []+ for rid, text in ((1, prefix), (2, prefix + " " + option)):+ data = text.encode()+ p.stdin.write(f"SUBMIT {rid} 0 {len(data)} 0 0 1 logprobs=1\n".encode()+ + data + b"\n")+ p.stdin.flush()+ while True:+ fields = p.stdout.readline().split()+ if fields[0] == b"ECHO":+ p.stdout.read(int(fields[2]) + 1)+ if rid == 2 and int(fields[3]) >= n_prefix and fields[4] != b"nan":+ values.append(float(fields[4]))+ elif fields[0] == b"ACCEPT" and rid == 1:+ n_prefix = int(fields[2])+ elif fields[0] in (b"DONE", b"ERROR"):+ break+ # sum(), as the endpoint adds them: on Python 3.12 it is compensated, and a+ # plain running total differs from it in the last bits+ return sum(values), len(values)+ finally:+ p.stdin.close()+ p.wait(timeout=30)+ p.stdout.close()++[email protected](mimo_serve_fixture.available(),+ "mimo is not built or the tiny MiMo fixture is absent "+ "(make mimo mimo-tiny-generate)")+class MimoSystemOneEndToEnd(unittest.TestCase):+ # Short: the fixture has 256 positions, its tokenizer reads one byte per+ # token, and a choice question lists its labels in the prompt.+ STATE = "The release is late and the tests are red."+ OPTIONS = ["ship it", "wait", "wait for green tests"]++ def setUp(self):+ engine = openai_server.Engine(+ mimo_serve_fixture.ENGINE, mimo_serve_fixture.served_fixture(), cap=8,+ env=dict(os.environ, **mimo_serve_fixture.engine_env()),+ family=family_by_id("mimo"))+ self.addCleanup(engine.process.stdout.close)+ self.addCleanup(engine.close)+ self.engine = _Recorder(engine)+ self.server = APIServer(("127.0.0.1", 0), self.engine, "mimo-tiny")+ self.addCleanup(self.server.server_close)+ self.addCleanup(self.server.shutdown)+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ self.base = f"http://127.0.0.1:{self.server.server_port}"++ def post(self, path, body):+ request = Request(self.base + path, data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ with urlopen(request, timeout=120) as response:+ return json.loads(response.read())++ def test_options_read_only_their_own_tokens_and_score_like_a_cold_engine(self):+ out = self.post("/v1/systemone", {+ "model": "mimo-tiny", "state": self.STATE, "pin_state": True,+ "questions": {"q": {"type": "choice", "instructions": "What should we do?",+ "criteria": {option: None for option in self.OPTIONS}}}})+ answer = out["answers"]["q"]+ self.assertIn(answer["choice"], self.OPTIONS)+ self.assertAlmostEqual(sum(answer["probabilities"].values()), 1.0, places=5)++ calls = self.engine.calls+ state, prefix, options = calls[0], calls[1], calls[2:]+ self.assertTrue(state["pin"] and prefix["pin"])+ self.assertEqual(len(options), len(self.OPTIONS))+ # The question resumes from the state's photo, every option from the+ # question's: each read-out starts exactly where the photo ends and covers+ # nothing before it. A fallback to a full recompute would read from 0.+ self.assertEqual(min(prefix["echo"]), state["accept"])+ read = 0+ for call in options:+ self.assertEqual(sorted(call["echo"]),+ list(range(prefix["accept"], call["accept"])),+ f"{call['prompt']!r} did not resume from the photo")+ read += call["accept"] - prefix["accept"]+ self.assertEqual(out["usage"]["output_tokens"], read)+ # The probabilities are the softmax of what a cold engine reads for each+ # option after the same prompt (normalize sum), to the reply's 6 digits.+ cold = {option: _cold_option_score(prefix["prompt"], option)[0] for option in self.OPTIONS}+ top = max(cold.values())+ weights = {option: math.exp(value - top) for option, value in cold.items()}+ total = sum(weights.values())+ for option in self.OPTIONS:+ self.assertAlmostEqual(answer["probabilities"][option], weights[option] / total, places=6,+ msg=f"{option!r}: the photo scored differently from a cold engine")++ def test_chat_logprobs_reach_the_engine(self):+ with patch("openai_server.ARCH", "mimo"):+ out = self.post("/v1/chat/completions", {+ "model": "mimo-tiny", "max_tokens": 6, "logprobs": True,+ "top_logprobs": 2, "enable_thinking": False,+ "messages": [{"role": "user", "content": "Ship it?"}]})+ choice = out["choices"][0]+ entries = choice["logprobs"]["content"]+ self.assertTrue(entries, "no per-token logprobs came back")+ for entry in entries:+ self.assertLessEqual(entry["logprob"], 0.0)+ self.assertEqual(len(entry["top_logprobs"]), 2)++if __name__ == "__main__":unittest.main()diff --git a/docs/api.md b/docs/api.mdindex b41fa19f..691a709f 100644--- a/docs/api.md+++ b/docs/api.md@@ -22,10 +22,11 @@ curl http://127.0.0.1:8000/v1/chat/completions \```Implemented endpoints are `GET /v1/models`, `GET /v1/models/{model}`,-`POST /v1/chat/completions`, legacy `POST /v1/completions`, `POST /v1/brio`-(closed-set scoring, [systemone.md](systemone.md)) and `POST /v1/systemone`, the-request and reply of TypeSafe's Jev API served by the same channel, or answered-natively by a decision model such as [Laya](laya.md). Chat and+`POST /v1/chat/completions`, legacy `POST /v1/completions` and+`POST /v1/systemone`, colibri's one decision API ([systemone.md](systemone.md)):+the request and reply of TypeSafe's Jev API, scored by a language model through+its logprob channel or answered natively by a decision model such as+[Laya](laya.md). Chat andcompletion requests support JSON responses, SSE streaming, usage counts,`max_tokens`/`max_completion_tokens`, `temperature`, `top_p`, and up to fourcustom `stop` sequences. `max_tokens` is a ceiling, not a target: when the@@ -567,8 +568,7 @@ What you get is one workspace with a dock to switch page:- **System One**: closed-set answers. A document, a question and the only answersallowed; the engine reads the probability of each answer, generates nothing,and reports an entropy that says when it is not sure. Same thing as- `POST /v1/brio`, or `POST /v1/systemone` on a decision model (see- [systemone.md](systemone.md));+ `POST /v1/systemone` (see [systemone.md](systemone.md));- **Brain**, two views. *Explore* draws the[measured expert atlas](https://github.com/JustVugg/colibri/issues/175) of GLM-5.2 as a cortex with ten regions toenter (publish `experts.json` from `tools/expert_atlas/analyze.py --web`).diff --git a/docs/mimo.md b/docs/mimo.mdindex 583fc6e3..a5b1fa3d 100644--- a/docs/mimo.md+++ b/docs/mimo.md@@ -96,7 +96,7 @@ on (the web has its own reasoning toggle).## System One mode and prompt reuse-[System One mode](systemone.md) works on MiMo as on the other engines. `POST /v1/brio` scores a+[System One mode](systemone.md) works on MiMo as on the other engines. `POST /v1/systemone` scores aclosed set of options instead of generating, and `logprobs` on `/v1/chat/completions` and`/v1/completions` (with `echo`) is served too. What is particular to MiMo is what asnapshot (`SUBMIT pin=1`) has to hold:@@ -147,7 +147,7 @@ prompt computed cold.`make -C c mimo-tiny-serve-check` serves the same fixture and compares against a coldengine, frame by frame: prefix reuse across turns, System One options that slide the windowpast the snapshot, nested snapshots and a sibling question, a snapshot made stale by an-unrelated prompt, prompts with a picture, and `/v1/brio` and chat logprobs through the+unrelated prompt, prompts with a picture, and `/v1/systemone` and chat logprobs through thegateway. Every option must process only its own tokens. The gateway's patchesmatch the official Qwen2-VL processor bit for bit on the fixture's picture.diff --git a/docs/systemone.md b/docs/systemone.mdindex b34bd32b..e393498f 100644--- a/docs/systemone.md+++ b/docs/systemone.md@@ -1,11 +1,12 @@# System One mode: typed decisions with calibrated probabilities-System One mode answers closed questions with a probability per allowed option,-through an API compatible with TypeSafe's Jev (`POST /v1/systemone`). In System-One mode a language model stops writing and starts **scoring**. You give it a prompt-and a set of allowed options; it answers with how likely each option is, and with-an entropy that says how sure it is. Same binary, same model, same chat path: the-mode is a key on the request, not a build flag or a separate server.+System One mode answers closed questions with a probability per allowed+option. There is one API for it, `POST /v1/systemone`, with the request and+the reply of TypeSafe's Jev: a state, typed questions (`noul`, `choice`,+`score`), and for every question a probability per option. A language model+answers by **scoring** instead of writing; a decision model such as+[Laya](laya.md) answers natively. Same server and same model as the chat: the+mode is the endpoint, not a build flag or a separate process.## Why you would want it@@ -19,7 +20,7 @@ System One mode answers the three questions a closed-set decision actually has:|---|---|---|| which option | a string to parse | the option, by construction || how likely each one | not available | a probability per option, including ones the model would never write |-| does it know | not available | an entropy: 0 means one plausible option, 1 means all of them |+| does it know | not available | a `confidence` per answer, 1 when one option holds the mass and 0 when it is flat (the terminal and the page also show the entropy) |The third row is the one you cannot get any other way, and it is usually the onethat decides whether a decision can be automated.@@ -47,7 +48,7 @@ and then reach it however you prefer:| from | how ||---|---|-| your own code | `POST /v1/systemone` or `POST /v1/brio`, below |+| your own code | `POST /v1/systemone`, below || the terminal | `coli chat --attach http://127.0.0.1:8000`, then `/decide` || the browser | open the server's address, System One in the navigation dock |@@ -57,103 +58,81 @@ already warm for the others.## The HTTP endpoint```-POST /v1/brio-```--```json-{- "model": "qwen36",- "state": "The pull request changes the logprob maths in the engine. 340 lines, 8 files, no tests. CI is green but the project has no coverage on that path.",- "question": "What should the reviewer do?",- "options": ["merge", "request changes", "close"]-}+POST /v1/systemone```| field | required | meaning ||---|---|---|-| `model` | yes | as in every other endpoint |-| `options` | one of | 2 to 64 distinct non-empty strings: one closed question |-| `questions` | one of | an array of `{question, options}`: many questions on one state, see below |-| `schema` | one of | an object `field: [values]`: a JSON object filled one field at a time, see below |-| `task` | optional | with `schema`, what the object is for |-| `state` | one of | the text to decide on |-| `messages` | one of | a chat history used as the context instead of `state` |-| `question` | optional | what to ask about the state |-| `normalize` | optional | `sum` (default) or `mean`, see below |-| `cache_slot` | optional | forced KV slot; by default derived from `state` |--The reply:+| `state` | yes | what the questions are about: text, an object or an array (JSON is read as text) |+| `questions` | yes | an object of 1 to 64 questions, `id: question`; the reply uses the same ids |+| `model` | no | any name: the served model answers (a Jev client sends `jev-latest`) |+| `normalize`, `pin_state`, `prefix`, `cache_slot` | no | colibri's options, below |-```json-{- "object": "brio.choice",- "answer": "request changes",- "entropy": 0.121,- "normalize": "sum",- "choices": [- {"option": "request changes", "p": 0.974, "logprob": -0.252, "mean_logprob": -0.126, "tokens": 2},- {"option": "merge", "p": 0.023, "logprob": -4.007, "mean_logprob": -4.007, "tokens": 1},- {"option": "close", "p": 0.004, "logprob": -5.841, "mean_logprob": -5.841, "tokens": 1}- ],- "usage": {"prompt_tokens": 88, "completion_tokens": 0, "read_tokens": 4, "total_tokens": 92}-}-```+Every question has a `type`, optional `instructions` (text, object or array)+and its `criteria`:-`completion_tokens` is always **0**: nothing is generated. `read_tokens` counts the-option tokens the engine read to score them.+| type | criteria | the answer |+|---|---|---|+| `noul` | optional `{"true": ..., "false": ...}` descriptions | `noul`: the probability of yes |+| `choice` | `{label: description or null}`, 1 to 255 labels | `choice`, `probabilities` by label, `confidence` |+| `score` | `[level 0, level 1, ...]`, 1 to 255 levels | `score` (the expected level), `legend` and `probabilities` keyed `"0".."n-1"`, `confidence` |-### Many questions on one text: `questions`+```bash+curl -s http://127.0.0.1:8000/v1/systemone \+ -H "Authorization: Bearer $COLI_API_KEY" -H "Content-Type: application/json" \+ -d '{+ "state": "Hi, I have been trying to connect my Stripe account for 3 days and the integration keeps failing. I am losing sales. Please help ASAP.",+ "model": "jev-latest",+ "questions": {+ "urgency": {"type": "noul", "instructions": "Does this message express urgency?"},+ "department": {"type": "choice", "instructions": "Which team should handle this?",+ "criteria": {"billing": "payments, invoices, Stripe payouts",+ "technical": "bugs, outages, integration errors",+ "sales": "pricing, plans, upgrades"}},+ "severity": {"type": "score", "instructions": "How severe is the customer impact?",+ "criteria": ["no impact", "minor inconvenience", "blocked on one task",+ "losing money", "business down"]}+ }}'+```-The document is photographed once and every question pays only for its own-words. This is the case where System One mode saves the most (5.7x against the chat,-measured below), and the server keeps the order of the snapshots itself.+The reply, from Qwen3.6-35B-A3B on a CPU box (1m46 with the experts streamed+from disk, the state read once for the three questions):```json-{- "model": "qwen36",- "state": "340 lines, 8 files, no tests. CI is green but no coverage on that path.",- "questions": [- {"question": "What should the reviewer do?", "options": ["merge", "request changes", "close"]},- {"question": "Does it need tests?", "options": ["yes", "no"]},- {"question": "How risky is it?", "options": ["high", "medium", "low"], "normalize": "sum"}- ]-}+{"id": "req_5f0c...", "model": "qwen36", "provider": "colibri",+ "answers": {+ "urgency": {"type": "noul", "noul": 0.847606},+ "department": {"type": "choice", "choice": "technical",+ "probabilities": {"billing": 0.059806, "technical": 0.939983, "sales": 0.000211},+ "confidence": 0.909974},+ "severity": {"type": "score", "score": 2.831772,+ "legend": {"0": "no impact", "1": "minor inconvenience", "2": "blocked on one task",+ "3": "losing money", "4": "business down"},+ "probabilities": {"0": 0.044403, "1": 0.02624, "2": 0.034899, "3": 0.842097, "4": 0.052361},+ "confidence": 0.802621}},+ "usage": {"input_tokens": 86, "output_tokens": 15, "cost": 0}}```-The reply is `brio.answers`: an `answers` array in the same order, each entry-shaped like a single `brio.choice` (`question`, `answer`, `entropy`, `choices`),-and one `usage` for the whole request. Up to 64 questions, each with 2 to 64-options; `normalize` can be set per question or once for all of them.+`usage.output_tokens` counts the option tokens a language model **read**:+nothing is generated. The probabilities of a question always sum to 1 over+its options.-### Fill a JSON object: `schema`+### Many questions on one text-The braces, the quotes and the field names are data the server writes. For-each field, in the order you give them, the model only picks one of the values-you allow, with the fields already filled visible to it. The JSON cannot come-out malformed and no value can be outside your list, because nothing is-generated.+The document is photographed once and every question pays only for its own+words. This is the case where System One mode saves the most (5.7x against the+chat, measured below), and the server keeps the order of the snapshots itself:+the state alone first, then each question on top of it.-```json-{- "model": "qwen36",- "state": "340 lines, 8 files, no tests. CI is green but no coverage on that path.",- "task": "Review this pull request.",- "schema": {- "decision": ["merge", "request changes", "close"],- "needs_tests": ["yes", "no"],- "risk": ["high", "medium", "low"],- "area": ["engine", "gateway", "docs"]- }-}-```+A closed question with a list of answers is one `choice` whose labels are the+answers (`{"merge": null, "request changes": null, "close": null}`); a JSON+object whose fields each take one of a few values is one `choice` per field.-The reply is `brio.schema`: `json` is the filled object, ready to use, and-`fields` carries, per field, the chosen `value`, its `p`, the `entropy` of that-cell and the full `choices`. The entropy per field is the point: the measured-run below was sure about `area` (0.17) and not about `needs_tests` and `risk`-(0.95 and 0.99), and said so, where the chat wrote `"risk": "high"` with the-same face. `task` is optional. Field names cannot contain quotes, backslashes-or newlines; values can, they are escaped.+Up to 1.12.1 the same channel also had its own route, `POST /v1/brio`, with an+`options`, a `questions` and a `schema` form. It is gone: `/v1/systemone` is+the one decision API. A `schema` filled its fields in order, each seeing the+values chosen before it; questions on `/v1/systemone` are answered each on+its own, from the state.### From your own code@@ -162,25 +141,26 @@ API key header as the rest.```pythonimport requests-r = requests.post("http://127.0.0.1:8000/v1/brio", json={- "model": "qwen36",+r = requests.post("http://127.0.0.1:8000/v1/systemone", json={"state": open("ticket.txt").read(),- "questions": [- {"question": "Which queue?", "options": ["billing", "bugs", "sales"]},- {"question": "Urgent?", "options": ["yes", "no"]},- ]})-for a in r.json()["answers"]:- print(a["question"], "->", a["answer"], f"(entropy {a['entropy']:.2f})")+ "questions": {+ "queue": {"type": "choice", "instructions": "Which queue?",+ "criteria": {"billing": None, "bugs": None, "sales": None}},+ "urgent": {"type": "noul", "instructions": "Is it urgent?"},+ }})+answers = r.json()["answers"]+print(answers["queue"]["choice"], answers["queue"]["confidence"], answers["urgent"]["noul"])``````js-const r = await fetch("http://127.0.0.1:8000/v1/brio", {+const r = await fetch("http://127.0.0.1:8000/v1/systemone", {method: "POST", headers: {"Content-Type": "application/json"},- body: JSON.stringify({ model: "qwen36", state: ticket,- schema: { queue: ["billing", "bugs", "sales"], urgent: ["yes", "no"] } })+ body: JSON.stringify({ state: ticket, questions: {+ queue: { type: "choice", instructions: "Which queue?", criteria: { billing: null, bugs: null, sales: null } },+ urgent: { type: "noul", instructions: "Is it urgent?" } } })});-const { json, fields } = await r.json();-// json.queue, json.urgent are guaranteed to be values from your lists+const { answers } = await r.json();+// answers.queue.choice is one of your labels; answers.urgent.noul is P(yes)```### Switching from Jev: change the base URL, keep your code@@ -216,41 +196,7 @@ non-empty key, and a server started without one accepts any). The SDKsPOST to `<base_url>/v1/systemone` and list models at `<base_url>/v1/models`;both routes accept any `model` name (a Jev client sends `jev-latest`).-```bash-curl -s http://127.0.0.1:8000/v1/systemone \- -H "Authorization: Bearer $COLI_API_KEY" -H "Content-Type: application/json" \- -d '{- "state": "Hi, I have been trying to connect my Stripe account for 3 days and the integration keeps failing. I am losing sales. Please help ASAP.",- "model": "jev-latest",- "questions": {- "urgency": {"type": "noul", "instructions": "Does this message express urgency?"},- "department": {"type": "choice", "instructions": "Which team should handle this?",- "criteria": {"billing": "payments, invoices, Stripe payouts",- "technical": "bugs, outages, integration errors",- "sales": "pricing, plans, upgrades"}},- "severity": {"type": "score", "instructions": "How severe is the customer impact?",- "criteria": ["no impact", "minor inconvenience", "blocked on one task",- "losing money", "business down"]}- }}'-```--The reply, from Qwen3.6-35B-A3B on a CPU box (1m46 with the experts streamed-from disk, the state read once for the three questions):--```json-{"id": "req_5f0c...", "model": "qwen36", "provider": "colibri",- "answers": {- "urgency": {"type": "noul", "noul": 0.847606},- "department": {"type": "choice", "choice": "technical",- "probabilities": {"billing": 0.059806, "technical": 0.939983, "sales": 0.000211},- "confidence": 0.909974},- "severity": {"type": "score", "score": 2.831772,- "legend": {"0": "no impact", "1": "minor inconvenience", "2": "blocked on one task",- "3": "losing money", "4": "business down"},- "probabilities": {"0": 0.044403, "1": 0.02624, "2": 0.034899, "3": 0.842097, "4": 0.052361},- "confidence": 0.802621}},- "usage": {"input_tokens": 86, "output_tokens": 15, "cost": 0}}-```+### What a language model is askedHow the three primitives map onto a language model, so you know what it isactually asked:@@ -267,7 +213,7 @@ documentation gives, `(n * peak - 1) / (n - 1)`: 1 when all the mass sits onone label, 0 when flat; `noul` carries none, as in theirs. A question with asingle label or level is answered without asking the model.-What differs, stated rather than hidden:+What differs from Jev, stated rather than hidden:- `model` is the served model, `provider` is `"colibri"`, `usage.cost` is 0,and `id` is the request id (also the `x-typesafe-request-id` header).@@ -282,7 +228,7 @@ What differs, stated rather than hidden:`sum` rule below. The numbers will not match Jev's on the same input; thecontract is the same, the model is yours.-#### colibri's options+### colibri's optionsNone of these is sent by a Jev client; each is optional.@@ -297,12 +243,13 @@ A decision engine has no log-probabilities and no photos: it ignores`normalize` and `pin_state` and refuses `prefix` (put that text in `state` or`instructions`); `cache_slot` reaches it as the DECIDE slot.-### Do not put the options in the prompt+### Do not put the options in the state-Write the state and the question; leave the option list to the `options` field. On a-real case that list was 48 tokens of 123, and it is about half of what the mode-saves. Naming the options in the text also biases the scoring towards whichever one-the sentence happens to mention last.+Write the state and the instructions; leave the options to `criteria`. The+server lists a choice's labels once, in the question, and reads each one as+the answer's continuation. Repeating them in the state or the instructions+makes the prompt longer for every option read, and naming them in a sentence+biases the scoring towards whichever one the sentence happens to mention last.### `sum` or `mean`@@ -317,9 +264,12 @@ qwen36 one case went the other way (`sum` picked `merge` where the model'sown greedy answer was `request changes`), so when your options have verydifferent lengths, look at both.-## Reading the entropy+## Reading the answer-Normalised to 0..1 over the number of options.+`confidence` is `(n * peak - 1) / (n - 1)` over the `n` options: 1 when all+the mass sits on one, 0 when it is flat. The terminal and the page show the+entropy of the same probabilities, normalised to 0..1 over the number of+options:| entropy | reading ||---|---|@@ -343,11 +293,11 @@ coli chat --attach http://127.0.0.1:8000› The PR touches the engine and carries no tests. What should we do?◆ System One- request changes ███████████████████████░░░ 93.6% 2 tok- merge ██░░░░░░░░░░░░░░░░░░░░░░░░ 6.4% 1 tok- close ░░░░░░░░░░░░░░░░░░░░░░░░░░ 0.0% 1 tok- → request changes entropy 0.218 (confident)- 58.71s · 4 tokens read · 0 generated+ request changes ███████████████████████░░░ 93.6%+ merge ██░░░░░░░░░░░░░░░░░░░░░░░░ 6.4%+ close ░░░░░░░░░░░░░░░░░░░░░░░░░░ 0.0%+ → request changes entropy 0.218 (sure)+ 58.71s · 131 prompt tokens · 4 option tokens read · nothing generated› /decide✦ chat@@ -355,16 +305,17 @@ coli chat --attach http://127.0.0.1:8000`/decide` with options enters the mode with the conversation so far as the context;`/decide` alone returns to chat. `:decide` works too. TAB completes the commands.+Each question goes to `POST /v1/systemone` as one `choice` whose labels are the+options, with the conversation as the state.## In the browserThe **System One** entry in the navigation dock opens a page built around the sameshape: the document on top, read once, and questions accumulating below it, eachwith its own set of allowed options and its own answer. The bars show the-probability of every option, and the entropy sits next to the winner. On a-decision model (`capabilities` says `decision`) each question goes to-`POST /v1/systemone` as one `choice`, and the bars are its calibrated-probabilities.+probability of every option, and the entropy sits next to the winner. Each+question goes to `POST /v1/systemone` as one `choice`, on a language model and+on a decision model alike.Options are per question, not shared across the page: "how risky is this" wantslow/medium/high where "do we sign" wants yes/no, and one list for all of them@@ -413,9 +364,11 @@ first predictor instead.3. Sum the `ECHO` log probabilities at positions past the prefix, divide by thenumber of those positions, and take a softmax across the options.-That is exactly what `/v1/brio` does. Doing it in a client is possible and is how-the endpoint was prototyped, but three things are easy to get wrong: pinning, the-option list leaking into the prompt, and the length normalisation.+That is what `/v1/systemone` does on a language model (with `sum` by+default instead of the per-token mean of step 3). Doing it in a client is+possible and is how the endpoint was prototyped, but three things are easy to+get wrong: pinning, the option list leaking into the prompt, and the+normalisation.## Nested snapshots@@ -471,13 +424,11 @@ qwen36 (22 GB, 40 layers) over the gateway, one KV slot:| task | System One | generation ||---|---|---|| one question, 3 options | 65.7 s, 0 tokens generated | 79.6 s, 5 generated |-| a 4-field JSON schema | 103.8 s, 104 tokens processed | 246.0 s, 226 processed || 4 items sharing one instruction block | 45.7 s per item | 149.2 s per item |-The gap widens with how much the alternative has to **write** and how much scaffolding-it has to **re-read**. On the JSON case, generation also invented two field names that-were not in the schema; System One mode cannot, because the field names are yours and only-the values come from the model.+The gap widens with how much the alternative has to **write** and how much+scaffolding it has to **re-read**. (Measured on the route that preceded+`/v1/systemone`, with the same scoring channel and the same photographs.)Note that these are on a disk-streaming engine, where the prefill costs about0.9 s/token. The ratios are the point, not the absolute numbers.@@ -511,8 +462,8 @@ cannot tell which kind answered.|---|---|---|| `c/laya` | Laya (Convai Innovations): ModernBERT encoder + decision head | [laya.md](laya.md) |-A decision engine serves `POST /v1/systemone` only. Chat, completions,-messages and `/v1/brio` answer 400 with a pointer to `/v1/systemone`, and+A decision engine serves `POST /v1/systemone` only. Chat, completions and+messages answer 400 with a pointer to `/v1/systemone`, and`/v1/models` lists the model with `capabilities: ["systemone", "decision"]`(a language model says `["chat", "systemone"]`). The path is one round trip:the gateway checks the request, sends it to the engine as one record, anddiff --git a/site/index.html b/site/index.htmlindex 8ea33539..3781c1d1 100644--- a/site/index.html+++ b/site/index.html@@ -447,7 +447,7 @@ footer{border-top:1px solid var(--line)}options it may pick and it reports the probability of each one. Nothing is generated,so there is nothing to parse and no answer outside the list. Typed decisions withcalibrated probabilities, API compatible with Jev (<code>POST /v1/systemone</code>).</p>- <div class="chart"><div class="crow"><span class="cl">one question, 10 options<s>System One</s></span><span class="ct"><i style="width:38.8%"></i></span><span class="cv">101.2 s</span></div><div class="crow"><span class="cl"><s>chat</s></span><span class="ct"><i style="width:48.1%"></i></span><span class="cv">125.6 s<s> 1.2x</s></span></div><div class="crow"><span class="cl">JSON, 4-field schema<s>System One</s></span><span class="ct"><i style="width:39.8%"></i></span><span class="cv">103.8 s</span></div><div class="crow"><span class="cl"><s>chat</s></span><span class="ct"><i style="width:94.2%"></i></span><span class="cv">246.0 s<s> 2.4x</s></span></div><div class="crow"><span class="cl">4 items, shared instructions<s>System One</s></span><span class="ct"><i style="width:17.5%"></i></span><span class="cv">45.7 s</span></div><div class="crow"><span class="cl"><s>chat</s></span><span class="ct"><i style="width:100.0%"></i></span><span class="cv">261.1 s<s> 5.7x</s></span></div></div>+ <div class="chart"><div class="crow"><span class="cl">one question, 10 options<s>System One</s></span><span class="ct"><i style="width:38.8%"></i></span><span class="cv">101.2 s</span></div><div class="crow"><span class="cl"><s>chat</s></span><span class="ct"><i style="width:48.1%"></i></span><span class="cv">125.6 s<s> 1.2x</s></span></div><div class="crow"><span class="cl">4 items, shared instructions<s>System One</s></span><span class="ct"><i style="width:17.5%"></i></span><span class="cv">45.7 s</span></div><div class="crow"><span class="cl"><s>chat</s></span><span class="ct"><i style="width:100.0%"></i></span><span class="cv">261.1 s<s> 5.7x</s></span></div></div><p class="src">Measured on qwen36 (22 GB), same engine, separate processes. Time from theprompt to the answer.</p>@@ -457,11 +457,11 @@ footer{border-top:1px solid var(--line)}a message to a policy.</p><div class="io"><b>question</b> what should the reviewer do?<br><b>options</b> merge · request changes · close</div></div>- <div class="ex"><h3>Filling a schema</h3>- <p>Braces, quotes and field names are data. The engine fills one slot at a time, so- the JSON is valid by construction.</p>- <div class="io"><b>System One</b> every value is one you allowed<br>- <b>chat</b> invented no_tests and track</div></div>+ <div class="ex"><h3>A decision model</h3>+ <p>Laya answers the same request natively: one forward pass, probabilities its+ authors calibrated, no prompt and nothing generated.</p>+ <div class="io"><b>same API</b> POST /v1/systemone<br>+ <b>Laya</b> 219 ms for one question on a laptop CPU</div></div><div class="ex"><h3>Many questions, one document</h3><p>Read the contract once, then ask it twenty things. The first question pays for thereading, the rest cost their own words.</p>@@ -470,28 +470,31 @@ footer{border-top:1px solid var(--line)}</div><div class="split2">- <div class="code"><span class="lbl">POST /v1/brio</span><pre>{- <span class="k">"model"</span>: <span class="s">"qwen36"</span>,+ <div class="code"><span class="lbl">POST /v1/systemone</span><pre>{<span class="k">"state"</span>: <span class="s">"340 lines, 8 files, no tests."</span>,- <span class="k">"question"</span>: <span class="s">"What should the reviewer do?"</span>,- <span class="k">"options"</span>: [<span class="s">"merge"</span>, <span class="s">"request changes"</span>, <span class="s">"close"</span>]+ <span class="k">"questions"</span>: {<span class="k">"review"</span>: {+ <span class="k">"type"</span>: <span class="s">"choice"</span>,+ <span class="k">"instructions"</span>: <span class="s">"What should the reviewer do?"</span>,+ <span class="k">"criteria"</span>: {<span class="k">"merge"</span>: <span class="n">null</span>, <span class="k">"request changes"</span>: <span class="n">null</span>, <span class="k">"close"</span>: <span class="n">null</span>}+ }}}</pre></div><div class="code"><span class="lbl">the reply</span><pre>{- <span class="k">"answer"</span>: <span class="s">"request changes"</span>,- <span class="k">"entropy"</span>: <span class="n">0.121</span>,- <span class="k">"choices"</span>: [- {<span class="k">"option"</span>: <span class="s">"request changes"</span>, <span class="k">"p"</span>: <span class="n">0.974</span>},- {<span class="k">"option"</span>: <span class="s">"merge"</span>, <span class="k">"p"</span>: <span class="n">0.023</span>},- {<span class="k">"option"</span>: <span class="s">"close"</span>, <span class="k">"p"</span>: <span class="n">0.004</span>}- ],- <span class="k">"usage"</span>: {<span class="k">"completion_tokens"</span>: <span class="n">0</span>}+ <span class="k">"answers"</span>: {<span class="k">"review"</span>: {+ <span class="k">"choice"</span>: <span class="s">"request changes"</span>,+ <span class="k">"probabilities"</span>: {+ <span class="k">"merge"</span>: <span class="n">0.023</span>, <span class="k">"request changes"</span>: <span class="n">0.974</span>, <span class="k">"close"</span>: <span class="n">0.004</span>+ },+ <span class="k">"confidence"</span>: <span class="n">0.961</span>+ }},+ <span class="k">"usage"</span>: {<span class="k">"output_tokens"</span>: <span class="n">4</span>, <span class="k">"cost"</span>: <span class="n">0</span>}}</pre></div></div><h3 style="font-size:1.3rem;font-weight:500;margin:3rem 0 .6rem;letter-spacing:-.02em">And the thing generation cannot give</h3>- <p class="sub" style="margin-bottom:1.6rem">Same request, same model, three fields of one- JSON schema. On <b>area</b> it is sure and it is right. On the other two the entropy is+ <p class="sub" style="margin-bottom:1.6rem">Same document, same model, three closed+ questions about it (measured when they were the fields of one JSON object, filled one+ at a time). On <b>area</b> it is sure and it is right. On the other two the entropy isnear the maximum: it does not know, and it says so. The chat arm wrote<code style="font:400 14px var(--mono);background:var(--soft);padding:1px 6px;border-radius:4px">"risk": "high"</code>with exactly the same face.</p>diff --git a/web/src/App.tsx b/web/src/App.tsxindex b3f6847c..cac7b719 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -31,7 +31,7 @@ import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Textarea } from "@/components/ui/textarea"import {- decidesOnly, generateImage, generatesImages, getHealth, listModelInfo, streamChat,+ generateImage, generatesImages, getHealth, listModelInfo, streamChat,type ChatMessage, type GeneratedImage, type HealthResponse, type StreamChatResult,} from "@/lib/api"import {@@ -73,7 +73,6 @@ export default function App() {/* Models the server marks with the image_generation capability. With one ofthem selected the conversation generates pictures instead of text. */const [imageModels, setImageModels] = useState<string[]>([])- const [decisionModels, setDecisionModels] = useState<string[]>([])const [model, setModel] = useState(() => stored(localStorage, "colibri.model", "glm-5.2-colibri"))const [temperature, setTemperature] = useState(0.7)const [maxTokens, setMaxTokens] = useState(4096)@@ -192,7 +191,6 @@ export default function App() {const found = info.map((item) => item.id)setModels(found)setImageModels(info.filter(generatesImages).map((item) => item.id))- setDecisionModels(info.filter(decidesOnly).map((item) => item.id))if (found.length && !found.includes(model)) setModel(found[0])setConnected(true)try {@@ -607,8 +605,7 @@ export default function App() {</section>}<section className="brio-workspace" hidden={view !== "brio"}><header className="page-heading"><span>COLIBRI / SYSTEM ONE</span><h1>{t("nav.brio")}</h1></header>- <Brio baseUrl={baseUrl} apiKey={apiKey} model={model} connected={connected}- decision={decisionModels.includes(model)} />+ <Brio baseUrl={baseUrl} apiKey={apiKey} model={model} connected={connected} /></section></main><NavigationDock view={view} onNavigate={setView} loading={loading} />diff --git a/web/src/Brio.tsx b/web/src/Brio.tsxindex e3c8b089..5041637e 100644--- a/web/src/Brio.tsx+++ b/web/src/Brio.tsx@@ -1,7 +1,7 @@import { useEffect, useRef, useState } from "react"import { FileUp, ListChecks, LoaderCircle, Plus, X } from "lucide-react"-import { askBrio, askSystemOne, type BrioResponse } from "@/lib/api"+import { askSystemOne, type DecisionResponse } from "@/lib/api"import { useLocale } from "./i18n"/* System One mode (the page is still Brio in the code).@@ -29,7 +29,7 @@ interface Row {id: numbertext: stringoptions: string /* vuoto = usa le opzioni comuni */- result?: BrioResponse+ result?: DecisionResponseseconds?: numbererror?: string}@@ -38,10 +38,8 @@ let nextId = 1const blank = (): Row => ({ id: nextId++, text: "", options: "" })const first = (): Row => ({ id: nextId++, text: "", options: "yes\nno" })-export default function Brio({ baseUrl, apiKey, model, connected, decision = false }: {+export default function Brio({ baseUrl, apiKey, model, connected }: {baseUrl: string; apiKey: string; model: string; connected: boolean- /* a decision model (Laya): it answers only POST /v1/systemone */- decision?: boolean}) {const { t } = useLocale()const [state, setState] = useState("")@@ -86,8 +84,7 @@ export default function Brio({ baseUrl, apiKey, model, connected, decision = falsetRunning(row.id)const started = performance.now()try {- const ask = decision ? askSystemOne : askBrio- const result = await ask(baseUrl, apiKey, model, state, row.text, lines(row.options), controller.signal)+ const result = await askSystemOne(baseUrl, apiKey, model, state, row.text, lines(row.options), controller.signal)patch(row.id, { result, seconds: (performance.now() - started) / 1000 })} catch (cause) {if (controller.signal.aborted) break /* fermato apposta: le domande dopo restano intatte */@@ -168,8 +165,8 @@ export default function Brio({ baseUrl, apiKey, model, connected, decision = fal<div className="brio-foot" data-level={level}><strong>{row.result.answer}</strong><span>{t("brio.entropy")} {row.result.entropy.toFixed(3)} · {t(`brio.${level}`)}</span>- <em>{row.seconds?.toFixed(1)}s · {row.result.usage.read_tokens} {t("brio.readTokens")} ·{" "}- <b>{row.result.usage.completion_tokens} {t("brio.generatedTokens")}</b></em>+ <em>{row.seconds?.toFixed(1)}s · {row.result.usage.input_tokens + row.result.usage.output_tokens} {t("brio.readTokens")} ·{" "}+ <b>0 {t("brio.generatedTokens")}</b></em></div></div>) : null}diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.tsindex 61370f95..bc1f07b5 100644--- a/web/src/lib/api.test.ts+++ b/web/src/lib/api.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest"import {- askBrio, askSystemOne, decidesOnly, extractSSE, extractSSEEvents, generateImage, generatesImages, getHealth, getProfile,+ askSystemOne, extractSSE, extractSSEEvents, generateImage, generatesImages, getHealth, getProfile,listModelInfo, serverEndpoint, streamChat, type GenerateImageOptions, type ImageProgress,} from "./api"@@ -119,62 +119,38 @@ describe("reasoning stream", () => {})})-describe("askBrio", () => {- /* The options must travel as a field, never folded into the prompt: keeping- them out of the text is half of what the mode saves, and a refactor that- "helpfully" appended them would be invisible in the answer. */- it("sends the options as data and posts to the brio endpoint", async () => {- const seen: { url?: string; body?: unknown } = {}- vi.stubGlobal("fetch", vi.fn(async (url: string, init: RequestInit) => {- seen.url = url- seen.body = JSON.parse(String(init.body))- return new Response(JSON.stringify({- answer: "b", entropy: 0.5, normalize: "mean",- choices: [{ option: "b", p: 0.7, logprob: -1, mean_logprob: -1, tokens: 1 }],- usage: { prompt_tokens: 9, completion_tokens: 0, read_tokens: 2, total_tokens: 11 },- }), { status: 200, headers: { "Content-Type": "application/json" } })- }))- const out = await askBrio("http://x/v1", "", "m", "state", "q?", ["a", "b"])- expect(seen.url).toBe("http://x/v1/brio")- expect(seen.body).toMatchObject({ model: "m", state: "state", question: "q?", options: ["a", "b"] })- expect(out.answer).toBe("b")- expect(out.usage.completion_tokens).toBe(0)- })-- it("surfaces the server's own message instead of a bare status", async () => {- vi.stubGlobal("fetch", vi.fn(async () => new Response(- JSON.stringify({ error: { message: "options must be a non-empty array" } }),- { status: 400, headers: { "Content-Type": "application/json" } })))- await expect(askBrio("http://x/v1", "", "m", "s", "q", ["a"]))- .rejects.toThrow("options must be a non-empty array")- })-})-describe("askSystemOne", () => {- it("asks a decision model one choice question and draws it like a brio answer", async () => {- const seen: { url?: string; body?: { questions: { q: { type: string; criteria: object } } } } = {}+ /* The options must travel as the labels of a `choice`, never folded into the+ state: the gateway reads each one as the answer's continuation, and a+ refactor that "helpfully" appended them to the text would be invisible in+ the answer. */+ it("asks one choice question on /v1/systemone and draws its probabilities", async () => {+ const seen: { url?: string; body?: { state: string; questions: { q: { type: string; criteria: object } } } } = {}vi.stubGlobal("fetch", vi.fn(async (url: string, init: RequestInit) => {seen.url = urlseen.body = JSON.parse(String(init.body))return new Response(JSON.stringify({id: "req_1", model: "laya", provider: "colibri",answers: { q: { type: "choice", choice: "b", probabilities: { a: 0.25, b: 0.75 }, confidence: 0.5 } },- usage: { input_tokens: 40, output_tokens: 0, cost: 0 },+ usage: { input_tokens: 40, output_tokens: 3, cost: 0 },}), { status: 200, headers: { "Content-Type": "application/json" } })}))const out = await askSystemOne("http://x/v1", "", "laya", "state", "q?", ["a", "b"])expect(seen.url).toBe("http://x/v1/systemone")+ expect(seen.body?.state).toBe("state")expect(seen.body?.questions.q).toEqual({ type: "choice", instructions: "q?", criteria: { a: null, b: null } })expect(out.answer).toBe("b")expect(out.choices.map((c) => c.option)).toEqual(["b", "a"])expect(out.entropy).toBeCloseTo(-(0.25 * Math.log(0.25) + 0.75 * Math.log(0.75)) / Math.log(2), 6)- expect(out.usage).toEqual({ prompt_tokens: 40, completion_tokens: 0, read_tokens: 40, total_tokens: 40 })+ expect(out.usage).toEqual({ input_tokens: 40, output_tokens: 3 })})- it("knows a decision model from its capabilities", () => {- expect(decidesOnly({ id: "laya", capabilities: ["systemone", "decision"] })).toBe(true)- expect(decidesOnly({ id: "qwen36", capabilities: ["chat", "systemone"] })).toBe(false)- expect(decidesOnly(undefined)).toBe(false)+ it("surfaces the server's own message instead of a bare status", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(+ JSON.stringify({ error: { message: "`questions.q.criteria` must be a non-empty object" } }),+ { status: 422, headers: { "Content-Type": "application/json" } })))+ await expect(askSystemOne("http://x/v1", "", "m", "s", "q", []))+ .rejects.toThrow("must be a non-empty object")})})diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex d09e3016..f130669d 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -286,50 +286,27 @@ export async function streamChat(options: StreamChatOptions): Promise<StreamChat}}-/* Modalita brio: il modello non genera, assegna una probabilita a ogni opzione- * ammessa. Il ciclo (fotografia del prefisso condiviso, una lettura per- * opzione, normalizzazione per lunghezza) sta nel gateway: qui si manda una- * richiesta e si riceve una distribuzione. */-export interface BrioChoice {+/* System One mode: the model does not generate, it gives a probability to+ * every allowed option. The loop (photographing the shared prefix, one read per+ * option, the normalisation) lives in the gateway, behind POST /v1/systemone,+ * the one decision API for language models and decision models alike: the+ * page's question goes as one `choice` whose labels are the options, and the+ * reply is drawn as bars. The entropy, normalised over the options, is+ * computed here from the probabilities. */+export interface DecisionChoice {option: stringp: number- logprob: number- mean_logprob: number- tokens: number}-export interface BrioResponse {+export interface DecisionResponse {answer: stringentropy: number- normalize: "mean" | "sum"- choices: BrioChoice[]- usage: { prompt_tokens: number; completion_tokens: number; read_tokens: number; total_tokens: number }+ choices: DecisionChoice[]+ /* input_tokens: the prompt read; output_tokens: the option tokens a language+ model read (a decision model reads everything as input); nothing is generated */+ usage: { input_tokens: number; output_tokens: number }}-export async function askBrio(- baseUrl: string,- apiKey: string,- model: string,- state: string,- question: string,- options: string[],- signal?: AbortSignal,-): Promise<BrioResponse> {- const response = await fetch(endpoint(baseUrl, "brio"), {- method: "POST",- headers: headers(apiKey),- body: JSON.stringify({ model, state, question, options }),- signal,- })- if (!response.ok) throw new Error(await responseError(response))- return (await response.json()) as BrioResponse-}--/* A decision engine (Laya) answers only POST /v1/systemone: there the page's- * question is one `choice` with the options as labels, and the reply is shaped- * like askBrio's so the page draws it the same way. The engine reads every- * token and generates none; its probabilities are calibrated, not log-probs,- * so `logprob` is the log of the probability and `tokens` is 0. */export async function askSystemOne(baseUrl: string,apiKey: string,@@ -338,7 +315,7 @@ export async function askSystemOne(question: string,options: string[],signal?: AbortSignal,-): Promise<BrioResponse> {+): Promise<DecisionResponse> {const response = await fetch(endpoint(baseUrl, "systemone"), {method: "POST",headers: headers(apiKey),@@ -355,27 +332,19 @@ export async function askSystemOne(}const probabilities = body.answers?.q?.probabilities ?? {}const choices = options- .map((option) => ({ option, p: probabilities[option] ?? 0, tokens: 0 }))- .map((c) => ({ ...c, logprob: Math.log(Math.max(c.p, 1e-12)), mean_logprob: Math.log(Math.max(c.p, 1e-12)) }))+ .map((option) => ({ option, p: probabilities[option] ?? 0 })).sort((a, b) => b.p - a.p)const entropy = choices.length > 1? -choices.reduce((sum, c) => sum + (c.p > 0 ? c.p * Math.log(c.p) : 0), 0) / Math.log(choices.length): 0- const read = body.usage?.input_tokens ?? 0return {answer: body.answers?.q?.choice ?? choices[0]?.option ?? "",entropy,- normalize: "sum",choices,- usage: { prompt_tokens: read, completion_tokens: 0, read_tokens: read, total_tokens: read },+ usage: { input_tokens: body.usage?.input_tokens ?? 0, output_tokens: body.usage?.output_tokens ?? 0 },}}-/* A model that only decides: colibri marks it "decision" in /v1/models. */-export function decidesOnly(model: ModelInfo | undefined) {- return !!model?.capabilities?.includes("decision")-}-/* ---- text-to-image ----------------------------------------------------------* POST /v1/images/generations, in the OpenAI shape plus colibri's `steps`,* `seed` and the `colibri` block of the answer. With `stream: true` the gatewaydiff --git a/web/tests/brio_ui.py b/web/tests/brio_ui.pyindex 12b262e6..cc355efb 100644--- a/web/tests/brio_ui.py+++ b/web/tests/brio_ui.py@@ -11,10 +11,11 @@ class H(SimpleHTTPRequestHandler):def log_message(self, *a): passdef do_POST(self):n = int(self.headers.get("Content-Length", 0)); self.rfile.read(n)- body = json.dumps({"answer":"request changes","entropy":0.121,"normalize":"mean",- "choices":[{"option":"request changes","p":0.974,"logprob":-0.25,"mean_logprob":-0.12,"tokens":2},- {"option":"merge","p":0.023,"logprob":-4.0,"mean_logprob":-4.0,"tokens":1}],- "usage":{"prompt_tokens":88,"completion_tokens":0,"read_tokens":4,"total_tokens":92}}).encode()+ assert self.path == "/v1/systemone", self.path+ body = json.dumps({"id":"req_1","model":"m","provider":"colibri",+ "answers":{"q":{"type":"choice","choice":"request changes",+ "probabilities":{"merge":0.023,"request changes":0.977},"confidence":0.954}},+ "usage":{"input_tokens":88,"output_tokens":4,"cost":0}}).encode()self.send_response(200); self.send_header("Content-Type","application/json")self.send_header("Content-Length",str(len(body))); self.end_headers(); self.wfile.write(body)def do_GET(self):