### Install and run sokudan serve Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Installs the sokudan package with the serve extra and starts the /v1/systemone compatible server on port 8000. The server accepts requests in the same format as TypeSafe's public API reference and returns responses in the same shape, so clients only need to change the base URL to http://127.0.0.1:8000. ```bash pip install "sokudan[serve]" sokudan serve --port 8000 ``` -------------------------------- ### Set up development environment and run tests Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Sets up a Python 3.11 virtual environment with uv, installs the dev and bench extras, copies the environment template, then runs the test suite and the ruff linter. The dev extra includes the train extra, so data generation, training, and evaluation dependencies are installed by default. ```bash uv venv --python 3.11 uv sync --extra dev --extra bench cp .env.example .env # ローカルLLM等のキーはすべて環境変数 uv run pytest uv run ruff check . ``` -------------------------------- ### Install sokudan from GitHub Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/model_card.md Install the sokudan package directly from the GitHub repository since it is not published on PyPI. ```bash pip install git+https://github.com/hiroki-abe-58/sokudan.git ``` -------------------------------- ### Verify TestPyPI installation Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_pypi.md Creates a fresh virtual environment, installs the package from TestPyPI with the serve extra, and verifies the version and CLI help. Dependencies are pulled from the real PyPI. ```powershell uv venv --python 3.11 $env:TEMP\sokudan-testpypi uv pip install --python $env:TEMP\sokudan-testpypi\Scripts\python.exe ` --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ ` --index-strategy unsafe-best-match "sokudan[serve]" & $env:TEMP\sokudan-testpypi\Scripts\python.exe -c "import sokudan; print(sokudan.__version__)" & $env:TEMP\sokudan-testpypi\Scripts\python.exe -m sokudan.cli serve --help ``` -------------------------------- ### Install sokudan with pip Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Installs the sokudan package from PyPI. The installed array library depends on the platform: Apple Silicon with macOS 14+ gets MLX (without torch), while Linux, Windows, Intel Mac, and Apple Silicon on macOS 13 get torch. ```bash pip install sokudan ``` -------------------------------- ### Install development version of sokudan serve Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Installs the development version of sokudan with the serve extra directly from the GitHub repository. Use this when you want the latest unreleased changes. ```bash pip install "sokudan[serve] @ git+https://github.com/hiroki-abe-58/sokudan.git" ``` -------------------------------- ### Load model with backend and dtype options Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Shows how to load a model with different backends and dtypes. The default backend="auto" tries MLX (on Apple Silicon with mlx installed), then torch's mps, cuda, and cpu, testing each with a short request and falling back with a warning on failure. Explicit backend/device settings disable fallback; specifying a missing library raises an ImportError suggesting extras like "sokudan[torch]". ```python agent = sokudan.load("GeneLab/sokudan-ja-310m") # backend="auto" agent = sokudan.load("GeneLab/sokudan-ja-310m", backend="mlx", dtype="float32") agent = sokudan.load("GeneLab/sokudan-ja-310m", backend="torch", device="cpu") print(agent.backend) # 使われているバックエンド ``` -------------------------------- ### flash-attn build failure: missing psutil Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/gate_a.md First failure when running `uv pip install flash-attn --no-build-isolation`: missing build dependency psutil. ```text ModuleNotFoundError: No module named 'psutil' hint: flash-attn@2.8.3.post1 depends on psutil, but doesn't declare it as a build dependency ``` -------------------------------- ### flash-attn build failure: CUDA version mismatch Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/gate_a.md Second failure after installing psutil: CUDA version mismatch between system toolkit (13.1) and PyTorch build (12.8). ```text File ".venv/Lib/site-packages/torch/utils/cpp_extension.py", line 545, in _check_cuda_version raise RuntimeError(CUDA_MISMATCH_MESSAGE, cuda_str_version, torch.version.cuda) RuntimeError: ('The detected CUDA version (%s) mismatches the version that was used to compilePyTorch (%s). Please make sure to use the same CUDA versions.', '13.1', '12.8') ``` -------------------------------- ### GET /health Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md Returns service health information including loaded model, calibration status, temperature settings, state rendering format, and confidence definition. Returns 503 if no model is loaded. ```APIDOC ## GET /health ### Description Returns service health information including loaded model, calibration status, temperature settings, state rendering format, and confidence definition. Returns 503 if no model is loaded. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **model** (string) - The name of the loaded model. - **calibrated** (boolean) - Whether calibration is enabled. - **calibration.temperatures** (object) - Temperature settings for calibration. - **state_format** (string) - How the state is rendered (e.g., text). - **confidence** (string) - Definition of confidence. - **limit** (number) - Upper limit for something (unspecified). #### Error Response (503) - Returned when no model is loaded. #### Response Example ```json { "model": "sokudan-ja-310m", "calibrated": true, "calibration": { "temperatures": {} }, "state_format": "text", "confidence": "...", "limit": 0 } ``` ``` -------------------------------- ### Run lev and sokudan benchmarks with lev_bench.py, lev_position_probe.py, sokudan_bench.py Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/baseline_lev.md Reproduction commands for the latency and VRAM benchmarks. Run from C:\Users\hirok\jev-oss\lev-eval\ with the appropriate venv (lev for lev, sokudan-v02 for sokudan v0.2). The files must be LF versions matching the pin hash; bench_ja/bench_en are CC BY 4.0 evaluation data and the author requests they not be used for training. ```bash # lev(較正あり / なし) python lev_bench.py --lang ja --checkpoint interfaze-ai/lev --bench --out results/lev_bench_ja.json python lev_bench.py --lang en --checkpoint interfaze-ai/lev --bench --out results/lev_bench_en.json python lev_bench.py --lang ja --checkpoint interfaze-ai/lev --bench --out results/lev_bench_ja_uncal.json --uncalibrated python lev_bench.py --lang en --checkpoint interfaze-ai/lev --bench --out results/lev_bench_en_uncal.json --uncalibrated # score の位置感度(較正あり / なし) python lev_position_probe.py --lang en --checkpoint interfaze-ai/lev --bench --out results/lev_bench_en_position.json python lev_position_probe.py --lang ja --checkpoint interfaze-ai/lev --bench --out results/lev_bench_ja_position.json python lev_position_probe.py --lang en ... --out results/lev_bench_en_position_uncal.json --uncalibrated python lev_position_probe.py --lang ja ... --out results/lev_bench_ja_position_uncal.json --uncalibrated # sokudan v0.2(同じハーネス、較正なし) python sokudan_bench.py --lang ja --checkpoint GeneLab/sokudan-ja-310m --bench --out results/sokudan_v02_bench_ja.json python sokudan_bench.py --lang en --checkpoint GeneLab/sokudan-ja-310m --bench --out results/sokudan_v02_bench_en.json ``` -------------------------------- ### Reproduce bench_en baseline and position bias probes Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/baseline_en.md Commands to build the English benchmark, run the baseline, and probe position bias for both laya-multilingual and laya models. Requires uv and the scripts in the repository. ```bash uv run python scripts/build_bench_en.py --n 300 uv run python scripts/run_baseline_en.py --bench data/bench_en.jsonl --out runs/baseline_en for m in laya-multilingual laya; do uv run python scripts/probe_position_bias.py --model "laya:convaiinnovations/$m" \ --lang en --bench data/bench_en.jsonl --out "runs/position_bias_en_$m.json" done ``` -------------------------------- ### 再現コマンド: probe_option_rendering.py の実行 Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/baseline_en.md 選択肢の接頭辞を変えた条件 A/C/D の実験を再現するコマンド。--device cpu と --benches bench_en を指定して実行する。 ```bash uv run python scripts/probe_option_rendering.py --device cpu --benches bench_en ``` -------------------------------- ### sokudan serve のインストールと起動 Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md sokudan を /v1/systemone 互換サーバーとして起動するためのコマンド。既定では GeneLab/sokudan-ja-310m(HF の main、重みは v0.2 と同じ)を 127.0.0.1:8000 で起動します。 ```bash pip install "sokudan[serve]" sokudan serve # GeneLab/sokudan-ja-310m(HF の main。重みは v0.2 と同じ)を 127.0.0.1:8000 で ``` -------------------------------- ### MLX バックエンドの基本的な使い方 Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/mlx_ja.md sokudan.load でモデルをロードし、backend と dtype を指定する例です。backend='auto' では MLX が優先されます。 ```python import sokudan agent = sokudan.load("GeneLab/sokudan-ja-310m") # backend="auto" print(agent.backend) # agent = sokudan.load("GeneLab/sokudan-ja-310m", backend="mlx", dtype="float32") agent = sokudan.load("GeneLab/sokudan-ja-310m", backend="torch") # PyTorch のモデル ``` -------------------------------- ### Build and check distribution Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_pypi.md Builds the package and checks the distribution files with twine. Run from the project directory before uploading. ```powershell cd C:\Users\hirok\sokudan-public Remove-Item -Recurse -Force dist -ErrorAction SilentlyContinue .venv\Scripts\python.exe -m build .venv\Scripts\python.exe -m twine check dist\* ``` -------------------------------- ### Reproduce v0.1 benchmark with seed loop Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/benchmarks.md Reproduce the v0.1 benchmark results for seeds 0, 1, and 2. Runs training, calibration, and baseline evaluation for each seed, then aggregates the results with report_bench_seeds.py. ```bash for s in 0 1 2; do uv run python scripts/train.py --train data/train_v2b.jsonl --val data/val_v2.jsonl \ --run-id v01_seed$s --seed $s --epochs 2 --batch-size 24 --head-lr 2e-4 \ --encoding joint --save uv run python scripts/calibrate.py --checkpoint runs/v01_seed$s/model.pt --val data/val_v2.jsonl uv run python scripts/run_baseline_ja.py --out runs/bench_seed$s --skip-laya \ --sokudan-checkpoint runs/v01_seed$s/model.pt \ --sokudan-temperatures runs/v01_seed$s/temperatures.json done uv run python scripts/report_bench_seeds.py --runs runs/bench_seed0 runs/bench_seed1 runs/bench_seed2 ``` -------------------------------- ### POST /v1/systemone Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md システムワン推論を実行するエンドポイントです。state と questions を送信し、回答を取得します。 ```APIDOC ## [POST] /v1/systemone ### Description システムワン推論を実行するエンドポイントです。state と questions を送信し、回答を取得します。 ### Method POST ### Endpoint /v1/systemone ### Parameters #### Request Body - **state** (string) - Required - 推論の対象となる状態(例: ログインが断続的に切れる問題) - **questions** (object) - Required - 質問のオブジェクト。キーは質問の識別子、値は質問の設定。 - **urgent** (object) - Required - 質問の設定。 - **type** (string) - Required - 質問のタイプ(例: "noul") - **instructions** (string) - Required - 質問の指示 ### Request Example { "state": "ログインが数日前から断続的に切れます。業務が止まっています。", "questions": { "urgent": { "type": "noul", "instructions": "至急の対応が必要か" } } } ### Response #### Success Response (200) - **answers** (object) - 質問ごとの回答。キーは質問の識別子、値は回答オブジェクト。 - **answers..noul** (string) - 質問の回答(例: 緊急度の判定) #### Response Example { "answers": { "urgent": { "noul": "yes" } } } ### Error Handling - **422**: 質問が読めない(型が不明、criteria の形が違う、水準の数、空の instructions、`state: null` など)。本文の `detail` に理由 - **413**: state が 100,000 文字を超える - **429**: 推論待ちがいっぱい。`Retry-After: 1` - **503**: モデルが読み込まれていない ``` -------------------------------- ### 素の HTTP で sokudan サーバーに POST する (httpx) Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md sokudan サーバーの base URL を `http://127.0.0.1:8000` に設定し、`/v1/systemone` エンドポイントに POST する例。API キーは必須ですが、サーバーは `Authorization` を検査しません。レスポンスの `answers.urgent.noul` を出力します。 ```python import httpx BASE_URL = "http://127.0.0.1:8000" # 以前は別のサービスの URL だったところ response = httpx.post(f"{BASE_URL}/v1/systemone", json={ "state": "ログインが数日前から断続的に切れます。業務が止まっています。", "questions": {"urgent": {"type": "noul", "instructions": "至急の対応が必要か"}}, }, headers={"Authorization": "Bearer local"}, timeout=60) print(response.json()["answers"]["urgent"]["noul"]) ``` -------------------------------- ### systemone エンドポイントへのリクエスト Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md POST /v1/systemone に JSON を送り、state と questions を渡します。questions には department(choice)、urgency(score)、churn(noul)の各タイプを指定します。レスポンスは model 名と数値の形で返ります。 ```bash curl -s localhost:8000/v1/systemone -H 'content-type: application/json' -d '{ "state": "先月の請求で同じ金額が二回引き落とされています。至急ご確認ください。", "questions": { "department": {"type": "choice", "instructions": "この問い合わせはどの部署が担当すべきか", "criteria": {"請求": "支払い・返金", "技術": "不具合・障害", "営業": "料金・新規契約", "その他": null}}, "urgency": {"type": "score", "instructions": "この依頼の緊急度は", "criteria": ["急がない", "早めに", "業務が止まっている"]}, "churn": {"type": "noul", "instructions": "解約を示唆しているか"} } }' ``` ``` -------------------------------- ### ベンチマーク再現コマンド (bash) Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/baseline_ja.md 依存関係の同期、環境変数の設定、ベンチマークデータの生成、ベースライン実行、分析、診断プローブを順に実行する一連のコマンド。 ```bash uv sync --extra dev --extra bench cp .env.example .env # SOKUDAN_LOCAL_LLM_* を設定 uv run python scripts/build_bench_ja.py --n 300 --out data/bench_ja.jsonl uv run python scripts/run_baseline_ja.py --bench data/bench_ja.jsonl --out runs/baseline_ja uv run python scripts/analyze_baseline_ja.py uv run python scripts/probe_laya_diagnostics.py ``` -------------------------------- ### Training command with --input-order state_first Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/input_order.md Training command for v0.1 with the addition of --input-order state_first. The base command uses --train data/train_v2b.jsonl --val data/val_v2.jsonl --encoding joint --epochs 2 --batch-size 24 --lr 2e-5 --head-lr 2e-4 --seed {0,1,2} --save. The --local-attention flag is not used (window remains 128). VRAM limits are set with --max-vram-fraction 0.88 and the environment variable PYTORCH_CUDA_ALLOC_CONF=garbage_collection_threshold:0.8,max_split_size_mb:256. ```bash --train data/train_v2b.jsonl --val data/val_v2.jsonl --encoding joint --epochs 2 --batch-size 24 --lr 2e-5 --head-lr 2e-4 --seed {0,1,2} --save ``` ```bash --input-order state_first ``` ```bash --max-vram-fraction 0.88 ``` ```bash PYTORCH_CUDA_ALLOC_CONF=garbage_collection_threshold:0.8,max_split_size_mb:256 ``` -------------------------------- ### HF Space 作成コマンドのエラー出力 Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_v0.2.1.md 2026-09-28 に create_repo を実行した際に返された HfHubHTTPError の出力。402 Payment Required で拒否されたことを示します。 ```text HfHubHTTPError Client error '402 Payment Required' for url 'https://huggingface.co/api/repos/create' ``` -------------------------------- ### Upload to PyPI Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_pypi.md Uploads the built distributions to PyPI using a token stored only in the session environment variable. The token is read securely and removed after upload. ```powershell $env:TWINE_USERNAME = "__token__" $env:TWINE_PASSWORD = Read-Host -AsSecureString "PyPI token" | ConvertFrom-SecureString -AsPlainText .venv\Scripts\python.exe -m twine upload dist\* Remove-Item Env:TWINE_PASSWORD ``` -------------------------------- ### Upload to PyPI with twine Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_v0.2.1.md Uploads the built distribution files to PyPI using twine. Sets the TWINE_USERNAME to the token placeholder and prompts for the PyPI token as a secure string, converting it to plain text for the password. After upload, removes the TWINE_PASSWORD environment variable. ```powershell cd C:\Users\hirok\sokudan-release $env:TWINE_USERNAME = "__token__"; $env:TWINE_PASSWORD = Read-Host -AsSecureString "PyPI token" | ConvertFrom-SecureString -AsPlainText uvx twine upload dist\*; Remove-Item Env:TWINE_PASSWORD ``` -------------------------------- ### Run gate_a_attention.py benchmark Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/gate_a.md Runs the attention benchmark script that produced all numbers in this document. Output is written to docs/data/gate_a.json. ```bash uv run python scripts/gate_a_attention.py --json docs/data/gate_a.json ``` -------------------------------- ### Upload to TestPyPI Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/release_pypi.md Uploads the built distributions to TestPyPI using a token stored only in the session environment variable. The token is read securely and removed after upload. ```powershell $env:TWINE_USERNAME = "__token__" $env:TWINE_PASSWORD = Read-Host -AsSecureString "TestPyPI token" | ConvertFrom-SecureString -AsPlainText .venv\Scripts\python.exe -m twine upload --repository testpypi dist\* Remove-Item Env:TWINE_PASSWORD ``` -------------------------------- ### POST /v1/systemone Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/systemone_wire_format.md The main endpoint for submitting questions to the sokudan system. It accepts a JSON payload with state, model, and questions, and returns responses for each question. ```APIDOC ## POST /v1/systemone ### Description Submits a set of questions to the sokudan system for processing. The request includes a state, an optional model identifier, and a map of questions. The server processes all questions in a single call and returns responses for each. ### Method POST ### Endpoint /v1/systemone ### Headers - **Content-Type** (string) - Required - Must be `application/json`. - **Authorization** (string) - Optional - Bearer token. sokudan accepts but does not validate it (local use). Missing or invalid tokens are not rejected. ### Request Body - **state** (string | object | array) - Required - The state to process. Strings are used as-is. Objects and arrays are passed unchanged to the prediction model and rendered as key-value lines or one element per line. `null` is rejected with 422. - **model** (string) - Optional - Model identifier (e.g., `"jev-latest"`). sokudan ignores this and always uses its loaded model. The response `model` is always `sokudan-ja-310m`. - **questions** (map) - Required - A map of question keys to question objects. Keys are user-defined and not passed to the model. Must contain 1 to 64 questions (SOKUDAN_MAX_QUESTIONS). Empty keys are rejected with 422. - **questions.*.type** (string) - Required - Must be `"noul"`, `"choice"`, or `"score"`. sokudan also accepts `"bool"` as an alias for `"noul"`. Other values are rejected with 422. - **questions.*.instructions** (string | object | array) - Required - Instructions for the question. Objects are rendered as key-value lines, arrays as one element per line (nested values as JSON). Empty instructions are rejected with 422. - **questions.*.criteria** (object) - Optional for `noul`, required for `choice` and `score` - Criteria for the question. See specific types below. - **questions.*.unknown keys** - Ignored - Unknown keys are ignored to avoid breaking with client-specific fields. #### Noul Criteria - **true** (string | object | array) - Optional - Description for the true case. Added as a marker: `はい: `. - **false** (string | object | array) - Optional - Description for the false case. Added as a marker: `いいえ: `. Keys other than `true`/`false` are rejected with 422. #### Choice Criteria - **choice criteria** (map) - Required - Map of choice names to descriptions. Descriptions can be null (rendered as empty string, resulting in a marker with just the choice name). Maximum 255 choices. Order is preserved. Choice names must be non-empty and non-whitespace (422 otherwise). #### Score Criteria - **score criteria** (array) - Required - Ordered array of level texts from lowest to highest. Must contain 2 to 10 levels. `null` or empty levels are rejected with 422. Levels that render to the same string are rejected by the parser with 422. ### Request Example ```json { "state": "some state", "model": "jev-latest", "questions": { "q1": { "type": "choice", "instructions": "Choose one", "criteria": { "A": "Option A", "B": null } } } } ``` ### Response #### Success Response (200) - **model** (string) - Always `sokudan-ja-310m`. - **sokudan.state_format** (string) - Indicates the format of the state (e.g., string, object, array). - **questions** (map) - Responses for each question, keyed by the original question key. #### Response Example ```json { "model": "sokudan-ja-310m", "sokudan": { "state_format": "string" }, "questions": { "q1": { "type": "choice", "answer": "A" } } } ``` ### Error Handling - **401** - Missing or invalid Authorization header (though sokudan does not validate it, the API reference specifies this). - **422** - Validation errors: `null` state, empty question keys, invalid question type, empty instructions, invalid criteria (e.g., non-true/false keys for noul, empty choice names, invalid score levels). ``` -------------------------------- ### Load model with or without calibration Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Shows how to control calibration. By default, load applies the bool temperature from calibration.json; passing temperatures=None disables calibration (same as v0.2). The response's calibrated field indicates whether a temperature was applied, and calibrated_answers lists the question IDs. ```python agent = sokudan.load("GeneLab/sokudan-ja-310m") # bool だけ較正(既定) agent = sokudan.load("GeneLab/sokudan-ja-310m", temperatures=None) # 較正なし(v0.2 と同じ) ``` -------------------------------- ### Load and predict with sokudan Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/model_card.md Load the model with optional temperatures for calibration and predict typed answers for a Japanese text with a custom question schema. Question types are choice, score, and bool (noul is an alias). The schema is free-form per request and does not require retraining. ```python import sokudan # リポジトリ ID を渡せば重みと temperatures.json を取得します。 # 未較正で使う場合は temperatures を渡さないでください(下の Limits)。 agent = sokudan.load("GeneLab/sokudan-ja-310m", temperatures="temperatures.json") result = agent.predict( {"body": "先月の請求で同じ金額が二回引き落とされています。至急ご確認ください。"}, { "department": {"type": "choice", "instructions": "この問い合わせはどの部署が担当すべきか", "criteria": {"請求": "支払い・返金", "技術": "不具合・障害", "営業": "料金・新規契約", "その他": "上記以外"}}, "urgency": {"type": "score", "instructions": "この依頼の緊急度は", "criteria": ["急がない", "早めに", "業務が止まっている"]}, "churn": {"type": "noul", "instructions": "解約を示唆しているか"}, }, ) ``` -------------------------------- ### choice プリミティブのスキーマ例 Source: https://github.com/hiroki-abe-58/sokudan/blob/main/SOKUDAN_SPEC.md 排他的な選択肢を表す choice 型の質問プリミティブ。criteria に選択肢と説明の対応を渡す。選択肢数は 2〜20 を想定し、それを超える場合は「粗い choice → 細かい choice」の2段構成を docstring に明記する。 ```python {"type": "choice", "instructions": "この問い合わせはどの部署が担当すべきか", "criteria": {"請求": "支払い・返金・請求書", "技術": "不具合・障害", "営業": "料金・新規契約"}} ``` -------------------------------- ### Predict with custom schema using sokudan.load and agent.predict Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Demonstrates a full prediction call with a custom schema. The state must be passed as a string; passing a dict (e.g., {"body": ...}) formats it into key: value lines, which changes the output (e.g., P(true) dropped from 0.318 to 0.145 in one held-out case). Question types are choice, score, and bool (noul is an alias). ```python import sokudan agent = sokudan.load("GeneLab/sokudan-ja-310m") # または手元の runs/.../model.pt result = agent.predict( "先月の請求で同じ金額が二回引き落とされています。至急ご確認ください。", # state は文字列で渡す { "department": {"type": "choice", "instructions": "この問い合わせはどの部署が担当すべきか", "criteria": {"請求": "支払い・返金", "技術": "不具合・障害", "営業": "料金・新規契約", "その他": "上記以外"}}, "urgency": {"type": "score", "instructions": "この依頼の緊急度は", "criteria": ["急がない", "早めに", "業務が止まっている"]}, "churn": {"type": "noul", "instructions": "解約を示唆しているか"}, }, ) print(result["answers"]["department"]["choice"]) ``` -------------------------------- ### bool 型の質問プリミティブ Source: https://github.com/hiroki-abe-58/sokudan/blob/main/SOKUDAN_SPEC.md P(true) の較正済み確率を表す。Jev の noul に相当し、エイリアス noul も受け付ける。 ```python {"type": "bool", "instructions": "解約を示唆しているか"} ``` -------------------------------- ### POST /v1/systemone Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md Classifies a given state string according to specified questions, returning answers with probabilities and confidence scores. The model name in the request is ignored; the actual model name is returned in the response. ```APIDOC ## POST /v1/systemone ### Description Classifies a given state string according to specified questions, returning answers with probabilities and confidence scores. The model name in the request is ignored; the actual model name is returned in the response. ### Method POST ### Endpoint /v1/systemone ### Parameters #### Request Body - **state** (string) - Required - The input state text to classify. - **questions** (object) - Required - A map of question names to question definitions. - **question_name** (object) - Each question has a type and instructions. - **type** (string) - Required - The type of question: "choice", "score", or "noul". - **instructions** (string) - Required - Instructions for the question. - **criteria** (object or array) - Optional - For choice: a map of option to label; for score: an array of labels; for noul: not present. ### Request Example ```json { "state": "先月の請求で同じ金額が二回引き落とされています。至急ご確認ください。", "questions": { "department": { "type": "choice", "instructions": "この問い合わせはどの部署が担当すべきか", "criteria": { "請求": "支払い・返金", "技術": "不具合・障害", "営業": "料金・新規契約", "その他": null } }, "urgency": { "type": "score", "instructions": "この依頼の緊急度は", "criteria": ["急がない", "早めに", "業務が止まっている"] }, "churn": { "type": "noul", "instructions": "解約を示唆しているか" } } } ``` ### Response #### Success Response (200) - **model** (string) - The name of the model that answered. - **answers** (object) - A map of question names to answer objects. - For choice: **type** (string), **choice** (string), **probabilities** (object), **confidence** (number). - For score: **type** (string), **score** (number), **legend** (object), **probabilities** (object), **confidence** (number). - For noul: **type** (string), **noul** (number) - Probability of "yes". - **usage** (object) - Token usage: **input_tokens** (number), **output_tokens** (number) - always 0. - **sokudan** (object) - Service-specific info: **state_format** (string), **state_tokens** (number), **state_truncated** (boolean), **backbone_passes** (number), **calibrated** (boolean), **calibrated_answers** (array of strings), **latency_ms** (number). #### Response Example ```json { "model": "sokudan-ja-310m", "answers": { "department": { "type": "choice", "choice": "請求", "probabilities": { "請求": 0.5, "技術": 0.2, "営業": 0.2, "その他": 0.1 }, "confidence": 0.8 }, "urgency": { "type": "score", "score": 1, "legend": { "0": "急がない", "1": "早めに", "2": "業務が止まっている" }, "probabilities": { "0": 0.1, "1": 0.7, "2": 0.2 }, "confidence": 0.7 }, "churn": { "type": "noul", "noul": 0.3 } }, "usage": { "input_tokens": 100, "output_tokens": 0 }, "sokudan": { "state_format": "text", "state_tokens": 50, "state_truncated": false, "backbone_passes": 3, "calibrated": true, "calibrated_answers": ["churn"], "latency_ms": 120 } } ``` ``` -------------------------------- ### Teacher Protocol definition Source: https://github.com/hiroki-abe-58/sokudan/blob/main/SOKUDAN_SPEC.md Defines the Teacher protocol with an async label method that returns a Distribution. This contract allows swapping between different label generation strategies (gold labels, sampling, logit reading). ```python class Teacher(Protocol): async def label(self, state: str, question: Question) -> Distribution: ... ``` -------------------------------- ### ヘルスチェック: curl localhost:8000/health Source: https://github.com/hiroki-abe-58/sokudan/blob/main/docs/serving.md モデルが読み込まれているか、較正の有無と温度、state の描画のしかた、confidence の定義と上限を返します。モデルが無いときは HTTP 503 を返します。 ```bash curl -s localhost:8000/health ``` -------------------------------- ### Load model from a seed revision Source: https://github.com/hiroki-abe-58/sokudan/blob/main/README_ja.md Loads a model from a specific seed revision. Other seed weights are available via revision tags. ```python agent = sokudan.load("GeneLab/sokudan-ja-310m@seed1") ``` -------------------------------- ### score 型の質問プリミティブ Source: https://github.com/hiroki-abe-58/sokudan/blob/main/SOKUDAN_SPEC.md 順序尺度の質問を表す。単なる多クラス分類ではない(§6.3 参照)。 ```python {"type": "score", "instructions": "この依頼の緊急度は", "criteria": ["急がない", "早めに", "業務が止まっている"]} ```