Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

docs(dotnet): add routing sample

kevin-gatimudfcbf678f2e1
diff --git a/laya-dotnet/samples/Laya.Routing/DemoHashingEmbedder.cs b/laya-dotnet/samples/Laya.Routing/DemoHashingEmbedder.cs
new file mode 100644
index 00000000..3fab6040
--- /dev/null
+++ b/laya-dotnet/samples/Laya.Routing/DemoHashingEmbedder.cs
@@ -0,0 +1,95 @@
+using System.Text;
+
+namespace Laya.Routing.Sample;
+
+/// <summary>
+/// Deterministic, dependency-free demo embedder — <b>demo only, replace with a real embedding
+/// model</b>. It is a straight copy of <c>laya-dotnet/tools/hashing_embedder.py</c> (also reimplemented in
+/// <c>laya-dotnet/tests/Laya.Tests/HashingEmbedder.cs</c>), kept here so this sample does not take
+/// a test-project dependency. It exists solely so the shortlist section produces a fixed,
+/// reproducible result without a real bi-encoder or a model download: a hashed
+/// character-trigram bag-of-features vector, chosen because it is a pure function of the input
+/// text and is trivial to reimplement bit-for-bit in C# with nothing but a string,
+/// UTF-8 encoding and 32-bit integer arithmetic.
+/// </summary>
+/// <remarks>
+/// Algorithm (mirrors the Python docstring precisely):
+/// <list type="number">
+/// <item>Lowercase with full Unicode case mapping — <see cref="LanguageDetection.PythonLower"/>,
+/// not <see cref="string.ToLowerInvariant()"/> directly, because this project builds with
+/// <c>InvariantGlobalization</c> enabled, under which plain <c>ToLowerInvariant</c> leaves U+0130
+/// (Turkish capital I with dot above) untouched instead of expanding it to "i" + combining dot,
+/// as Python's <c>str.lower()</c> does.</item>
+/// <item>Pad with two ASCII spaces on each side.</item>
+/// <item>Slide a window of exactly 3 Unicode code points (via <see cref="System.Text.Rune"/>,
+/// never UTF-16 code units) across the padded text, one code point at a time.</item>
+/// <item>UTF-8-encode each window's own 3 code points (re-encoded fresh each time, not sliced
+/// from the whole padded text's byte buffer).</item>
+/// <item>Hash those bytes with 32-bit FNV-1a (unsigned, wrapping multiply).</item>
+/// <item><c>bucket = hash % 64</c>.</item>
+/// <item><c>sign = +1</c> when the hash's top bit is 0, else <c>-1</c>.</item>
+/// <item>Accumulate <c>sign</c> into <c>vector[bucket]</c> for every window (float64 throughout).</item>
+/// <item>No normalisation.</item>
+/// </list>
+/// </remarks>
+internal static class DemoHashingEmbedder
+{
+ /// <summary>Vector width, matching Python's <c>DIM</c>.</summary>
+ public const int Dimension = 64;
+
+ private const uint FnvOffsetBasis = 0x811c9dc5;
+ private const uint FnvPrime = 0x01000193;
+
+ /// <summary>Embed a batch of texts, one <see cref="Dimension"/>-length vector per input, in order.</summary>
+ public static double[][] Embed(IReadOnlyList<string> texts)
+ {
+ ArgumentNullException.ThrowIfNull(texts);
+ var result = new double[texts.Count][];
+ for (var i = 0; i < texts.Count; i++) result[i] = EmbedOne(texts[i]);
+ return result;
+ }
+
+ /// <summary>Embed a single text into a <see cref="Dimension"/>-length vector.</summary>
+ public static double[] EmbedOne(string? text)
+ {
+ var vector = new double[Dimension];
+ var padded = " " + PythonLower(text ?? string.Empty) + " ";
+ var runes = padded.EnumerateRunes().ToArray();
+ var windowCount = runes.Length - 2; // always >= 2: padding guarantees at least 4 code points
+
+ for (var i = 0; i < windowCount; i++)
+ {
+ var window = string.Concat(runes[i].ToString(), runes[i + 1].ToString(), runes[i + 2].ToString());
+ var hash = Fnv1a32(Encoding.UTF8.GetBytes(window));
+ var bucket = (int)(hash % Dimension);
+ var sign = (hash >> 31 & 1) == 0 ? 1.0 : -1.0;
+ vector[bucket] += sign;
+ }
+ return vector;
+ }
+
+ /// <summary>32-bit FNV-1a over raw bytes, wrapping like an unsigned 32-bit integer.</summary>
+ private static uint Fnv1a32(byte[] data)
+ {
+ var hash = FnvOffsetBasis;
+ foreach (var b in data)
+ {
+ hash ^= b;
+ hash *= FnvPrime; // uint * uint wraps silently (unchecked) by default in C#
+ }
+ return hash;
+ }
+
+ /// <summary>
+ /// Python's <c>str.lower()</c>: full Unicode lowercasing, including the one unconditional
+ /// 1-to-2-code-point special case, U+0130 → U+0069 U+0307. A local copy of
+ /// <c>LanguageDetection.PythonLower</c> (internal to the Laya assembly, not visible here) —
+ /// see that method's remarks for why plain <see cref="string.ToLowerInvariant()"/> alone is
+ /// not enough under <c>InvariantGlobalization</c>.
+ /// </summary>
+ private static string PythonLower(string text)
+ {
+ var lowered = text.ToLowerInvariant();
+ return lowered.Contains('İ') ? lowered.Replace("İ", "i̇") : lowered;
+ }
+}
diff --git a/laya-dotnet/samples/Laya.Routing/Laya.Routing.csproj b/laya-dotnet/samples/Laya.Routing/Laya.Routing.csproj
new file mode 100644
index 00000000..aca3b93d
--- /dev/null
+++ b/laya-dotnet/samples/Laya.Routing/Laya.Routing.csproj
@@ -0,0 +1,14 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\src\Laya\Laya.csproj" />
+ </ItemGroup>
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+
+</Project>
diff --git a/laya-dotnet/samples/Laya.Routing/Program.cs b/laya-dotnet/samples/Laya.Routing/Program.cs
new file mode 100644
index 00000000..14d9c1d2
--- /dev/null
+++ b/laya-dotnet/samples/Laya.Routing/Program.cs
@@ -0,0 +1,388 @@
+using System.Globalization;
+using System.Diagnostics;
+using Laya;
+using Laya.Routing.Sample;
+
+// Combined sample for LanguageDetection, LayaRouter, LayaEmail and LayaShortlist.
+//
+// OUTPUT CONTRACT (see README.md for the full spec — its stdout is checked against the
+// Python-recorded goldens (tools/routing_cases.py), apart from timings, which only ever go to stderr):
+//
+// --model-root <dir> Sets LAYA_ONNX_ROOT for this process (default: the LAYA_ONNX_ROOT
+// already in the environment). Each checkpoint is then resolved as
+// <dir>/<subfolder>, same as LayaRouter always does.
+// --download Allow the router to fetch a missing checkpoint from Hugging Face.
+// --preload Build every checkpoint up front instead of lazily.
+// -h, --help Print usage and exit 0.
+//
+// Exit codes: 0 ok, 1 runtime/artifact error, 2 bad usage.
+
+const string Usage = """
+ Usage: dotnet run --project samples/Laya.Routing [options]
+
+ --model-root <dir> Root directory holding one subdirectory per checkpoint
+ (english/, multilingual/, typed-decisions/). Sets LAYA_ONNX_ROOT
+ for this process; overrides any LAYA_ONNX_ROOT already set.
+ --download Allow fetching a missing checkpoint from Hugging Face.
+ --preload Build every checkpoint up front instead of lazily.
+ -h, --help Print this message.
+
+ With no --model-root the artifact root is resolved from LAYA_ONNX_ROOT.
+ """;
+
+var allowDownload = false;
+var preload = false;
+string? modelRoot = null;
+
+for (var i = 0; i < args.Length; i++)
+{
+ switch (args[i])
+ {
+ case "--model-root":
+ if (i + 1 >= args.Length)
+ {
+ Console.Error.WriteLine("--model-root needs a directory.");
+ Console.Error.WriteLine(Usage);
+ return 2;
+ }
+ modelRoot = args[++i];
+ break;
+
+ case "--download":
+ allowDownload = true;
+ break;
+
+ case "--preload":
+ preload = true;
+ break;
+
+ case "-h":
+ case "--help":
+ Console.WriteLine(Usage);
+ return 0;
+
+ default:
+ Console.Error.WriteLine($"Unrecognised argument: {args[i]}");
+ Console.Error.WriteLine(Usage);
+ return 2;
+ }
+}
+
+// LayaOptions has no "model root" concept of its own -- LayaRouter always resolves each
+// checkpoint independently via LAYA_ONNX_ROOT/<subfolder>, cache, or download (see
+// ModelArtifacts.ResolveAsync). Setting the environment variable for this process is therefore
+// the direct equivalent of --model-dir on Laya.Sample for a router that manages several
+// checkpoints rather than one fixed directory.
+if (modelRoot is not null)
+ Environment.SetEnvironmentVariable("LAYA_ONNX_ROOT", modelRoot);
+
+// ── Section 1: language detection ──────────────────────────────────────────
+
+Console.WriteLine("== 1. Language detection ==");
+foreach (var (name, state) in DetectionStates())
+{
+ var analysis = LanguageDetection.Analyse(state);
+ var languageDisplay = analysis.Language ?? "-";
+ var isEnglish = analysis.IsEnglish ? "true" : "false";
+ Console.WriteLine(
+ $"{name,-22} script={analysis.Script,-10} language={languageDisplay,-4} is_english={isEnglish}");
+}
+
+Console.WriteLine();
+
+// ── Section 2: routing decisions (Route only, nothing loaded) ──────────────
+
+Console.WriteLine("== 2. Routing decisions ==");
+using (var plainRouter = new LayaRouter())
+using (var autoTaskRouter = new LayaRouter(new LayaRouterOptions { AutoTaskDetection = true }))
+{
+ RouteAndPrint(plainRouter, "auto_english",
+ "Please refund the duplicate charge on invoice 4411 today.");
+ RouteAndPrint(plainRouter, "auto_hindi",
+ "मुझसे दो बार शुल्क लिया गया, कृपया रिफंड करें।");
+ RouteAndPrint(plainRouter, "auto_unknown_latin_romanian",
+ "Gătește-mi o rețetă de sarmale de post pentru mâine.");
+ RouteAndPrint(plainRouter, "explicit_model_multilingual",
+ "anything at all", model: "multilingual");
+ RouteAndPrint(plainRouter, "explicit_lang_de", "hello there", lang: "de");
+
+ var typedDecisionQuestions = TypedDecisionStubQuestions();
+ RouteAndPrint(autoTaskRouter, "workflow_opt_in_customer_service",
+ new Dictionary<string, object?> { ["body"] = "I was charged twice" }, typedDecisionQuestions);
+ RouteAndPrint(plainRouter, "workflow_opt_in_off_by_default",
+ new Dictionary<string, object?> { ["body"] = "I was charged twice" }, typedDecisionQuestions);
+}
+
+Console.WriteLine();
+
+// ── Sections 3-5: everything that needs a real checkpoint ───────────────────
+
+var routerOptions = new LayaRouterOptions
+{
+ MaxLoaded = 2,
+ Preload = preload,
+ EngineOptions = new LayaOptions
+ {
+ AllowDownload = allowDownload,
+ DownloadProgress = allowDownload
+ ? new Progress<ArtifactDownloadProgress>(p => Console.Error.WriteLine($" {p}"))
+ : null,
+ },
+};
+
+LayaRouter router;
+try
+{
+ var buildClock = Stopwatch.StartNew();
+ router = new LayaRouter(routerOptions);
+ buildClock.Stop();
+ Console.Error.WriteLine($"router construction: {buildClock.Elapsed.TotalMilliseconds:F0} ms");
+}
+catch (Exception error) when (error is DirectoryNotFoundException or FileNotFoundException)
+{
+ Console.Error.WriteLine(error.Message);
+ if (!allowDownload)
+ {
+ Console.Error.WriteLine();
+ Console.Error.WriteLine("Point --model-root or LAYA_ONNX_ROOT at a local ONNX export tree.");
+ }
+ return 1;
+}
+
+try
+{
+ using (router)
+ {
+ // ── Section 3: router predict over an English and a Hindi support email ─────
+
+ Console.WriteLine("== 3. Router predict ==");
+ var supportQuestions = SupportQuestions();
+
+ var englishEmail = new Dictionary<string, object?>
+ {
+ ["from"] = "[email protected]",
+ ["subject"] = "Duplicate charge on invoice #4411",
+ ["body"] = "Hi, we were billed twice for March. Please refund the duplicate today "
+ + "or we will cancel our plan.",
+ };
+ PredictAndPrint(router, "en", englishEmail, supportQuestions);
+
+ var hindiEmail = new Dictionary<string, object?>
+ {
+ ["from"] = "[email protected]",
+ ["subject"] = "चालान में दोहरा शुल्क",
+ ["body"] = "मार्च का बिल दो बार लिया गया, कृपया रिफंड करें।",
+ };
+ PredictAndPrint(router, "hi", hindiEmail, supportQuestions);
+
+ Console.WriteLine();
+
+ // ── Section 4: email cleaning ────────────────────────────────────────────────
+
+ Console.WriteLine("== 4. Email cleaning ==");
+ const string rawBody =
+ "Hi team,\n\n"
+ + "I was charged twice for the Pro plan this month and the second charge still has "
+ + "not been refunded. This is the third time I have written about it -- please "
+ + "resolve this today or I will need to cancel the account.\n\n"
+ + "Best regards,\n"
+ + "Priya Sharma\n"
+ + "Sent from my iPhone\n\n"
+ + "This email and any files transmitted with it are confidential and intended "
+ + "solely for the use of the individual or entity to whom they are addressed. If "
+ + "you have received this email in error please notify the sender.\n\n"
+ + "On Tue, Sep 22, 2026 at 9:14 AM, Support <[email protected]> wrote:\n"
+ + "> Hi Priya, thanks for reaching out, we are looking into it.\n"
+ + "> - Support Team\n";
+
+ var cleaned = LayaEmail.CleanBody(rawBody);
+ Console.WriteLine("--- cleaned ---");
+ Console.WriteLine(cleaned);
+ Console.WriteLine("--- end ---");
+
+ var emailState = LayaEmail.State(
+ subject: "Re: Refund for invoice 4411", body: rawBody, sender: "[email protected]");
+ var emailQuestions = LayaPresets.Email();
+ PredictAndPrint(router, "en", emailState, emailQuestions);
+
+ Console.WriteLine();
+
+ // ── Section 5: shortlist ─────────────────────────────────────────────────────
+
+ Console.WriteLine("== 5. Shortlist ==");
+ const string bankingState =
+ "I tried to withdraw cash from the ATM but it kept the card and gave me no money.";
+ const string bankingInstructions = "What is the customer's banking intent?";
+
+ var shortlistQuestions = new QuestionSet
+ {
+ ["intent"] = Question.Choice(bankingInstructions, BankingCriteria()),
+ };
+
+ var shortlistClock = Stopwatch.StartNew();
+ var shortlistResult = LayaShortlist.Predict(
+ router, bankingState, shortlistQuestions, DemoHashingEmbedder.Embed);
+ shortlistClock.Stop();
+ Console.Error.WriteLine($"shortlist predict: {shortlistClock.Elapsed.TotalMilliseconds:F0} ms");
+
+ var info = shortlistResult.Shortlist!["intent"];
+ Console.WriteLine($"kept {info.K} of {info.N}:");
+ for (var i = 0; i < info.Labels.Count; i++)
+ {
+ var score = info.Scores![i];
+ Console.WriteLine($" {info.Labels[i],-28} {score.ToString("0.0000", CultureInfo.InvariantCulture)}");
+ }
+
+ var intentAnswer = shortlistResult["intent"].AsChoice();
+ var probability = intentAnswer[intentAnswer.Choice];
+ Console.WriteLine(
+ $"answer: {intentAnswer.Choice} ({probability.ToString("0.0000", CultureInfo.InvariantCulture)})");
+ }
+}
+catch (Exception error) when (error is DirectoryNotFoundException or FileNotFoundException)
+{
+ Console.Error.WriteLine(error.Message);
+ if (!allowDownload)
+ {
+ Console.Error.WriteLine();
+ Console.Error.WriteLine("Point --model-root or LAYA_ONNX_ROOT at a local ONNX export tree.");
+ }
+ return 1;
+}
+
+return 0;
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+static IEnumerable<(string Name, object State)> DetectionStates()
+{
+ yield return ("english", "The customer was charged twice this month and wants a refund.");
+ yield return ("spanish_accent_stripped",
+ "El cliente fue cobrado dos veces y quiere que le devuelvan el dinero");
+ yield return ("french", "Le client a été facturé deux fois et demande un remboursement.");
+ yield return ("romanian", "Am fost taxat de două ori pentru factura din luna martie și vreau banii");
+ yield return ("hindi", "ग्राहक से दो बार शुल्क लिया गया और वह धनवापसी चाहता है।");
+ yield return ("arabic", "تم خصم المبلغ مرتين من العميل ويريد استرداد الأموال");
+ yield return ("japanese", "お客様は二重に請求されたため返金を希望しています。");
+ yield return ("dict_state", new Dictionary<string, object?>
+ {
+ ["subject"] = "Double charge",
+ ["body"] = "मुझसे दो बार शुल्क लिया गया",
+ });
+}
+
+static void RouteAndPrint(
+ LayaRouter router, string name, object? state, QuestionSet? questions = null,
+ string? model = null, string? lang = null)
+{
+ var decision = router.Route(state, questions, model: model, lang: lang);
+ Console.WriteLine($"{name,-26} -> {Subdir(decision.Model)} ({decision.Reason})");
+}
+
+static QuestionSet TypedDecisionStubQuestions()
+{
+ var questions = new QuestionSet();
+ foreach (var id in new[] { "action", "category", "churn_risk", "needs_human", "urgency" })
+ questions[id] = Question.Noul("x");
+ return questions;
+}
+
+static QuestionSet SupportQuestions() => new()
+{
+ ["department"] = Question.Choice(
+ "Which department should handle this request?",
+ ("billing", "invoices, payments, refunds"),
+ ("technical", "bugs, outages, system errors"),
+ ("sales", "pricing, new contracts"),
+ ("other", "everything else")),
+ ["urgency"] = Question.Score(
+ "How urgent is this request?",
+ "not urgent", "soon", "critical deadline or blocking issue"),
+ ["churn_risk"] = Question.Noul("Does the user threaten to cancel or leave?"),
+ ["refund_requested"] = Question.Noul("Does the user explicitly request a refund?"),
+};
+
+static void PredictAndPrint(LayaRouter router, string label, object? state, QuestionSet questions)
+{
+ var clock = Stopwatch.StartNew();
+ var result = router.Predict(state, questions);
+ clock.Stop();
+ Console.Error.WriteLine($"{label} predict: {clock.Elapsed.TotalMilliseconds:F0} ms");
+
+ var decision = result.Routing!;
+ Console.WriteLine($"[{label}] routed to {Subdir(decision.Model)}: {decision.Reason}");
+ PrintAnswers(result, questions);
+}
+
+static void PrintAnswers(LayaResult result, QuestionSet questions)
+{
+ foreach (var id in result.Ids)
+ {
+ var answer = result[id];
+ var value = answer switch
+ {
+ ChoiceAnswer choice => choice.Choice,
+ ScoreAnswer score => score.Score.ToString("0.0000", CultureInfo.InvariantCulture),
+ NoulAnswer noul => noul.Probability.ToString("0.0000", CultureInfo.InvariantCulture),
+ _ => "?",
+ };
+ Console.WriteLine($" {id,-18} {value}");
+ }
+}
+
+static string Subdir(LayaCheckpoint checkpoint) => checkpoint switch
+{
+ LayaCheckpoint.English => "english",
+ LayaCheckpoint.Multilingual => "multilingual",
+ LayaCheckpoint.TypedDecisions => "typed-decisions",
+ _ => throw new ArgumentOutOfRangeException(nameof(checkpoint), checkpoint, null),
+};
+
+static IEnumerable<KeyValuePair<string, object?>> BankingCriteria()
+{
+ (string, string)[] entries =
+ [
+ ("activate_my_card", "turn on a newly received card"),
+ ("age_limit", "minimum or maximum age to use the service"),
+ ("apple_pay_or_google_pay", "adding the card to a mobile wallet"),
+ ("atm_support", "which ATMs the card works at"),
+ ("automatic_top_up", "automatically topping up the balance"),
+ ("balance_not_updated_after_bank_transfer", "a bank transfer is missing from the balance"),
+ ("balance_not_updated_after_cheque_or_cash_deposit", "a deposit is missing from the balance"),
+ ("beneficiary_not_allowed", "cannot add a payment recipient"),
+ ("cancel_transfer", "wants to cancel a transfer already sent"),
+ ("card_about_to_expire", "the card is close to its expiry date"),
+ ("card_acceptance", "where the card is accepted"),
+ ("card_arrival", "asking when a new card will arrive"),
+ ("card_delivery_estimate", "asking how long delivery will take"),
+ ("card_linking", "linking a card to the account"),
+ ("card_not_working", "the card is declined or not working"),
+ ("card_payment_fee_charged", "an unexpected fee was charged on a card payment"),
+ ("card_payment_not_recognised", "a card payment the customer does not recognise"),
+ ("card_payment_wrong_exchange_rate", "the exchange rate used was wrong"),
+ ("card_swallowed", "the ATM kept the card"),
+ ("cash_withdrawal_charge", "an unexpected charge for a cash withdrawal"),
+ ("cash_withdrawal_not_recognised", "a cash withdrawal the customer does not recognise"),
+ ("change_pin", "wants to change the PIN"),
+ ("compromised_card", "the card may have been compromised"),
+ ("contactless_not_working", "contactless payment is not working"),
+ ("country_support", "which countries the service supports"),
+ ("declined_card_payment", "a card payment was declined"),
+ ("declined_cash_withdrawal", "a cash withdrawal was declined"),
+ ("declined_transfer", "a transfer was declined"),
+ ("direct_debit_payment_not_recognised", "a direct debit the customer does not recognise"),
+ ("disposable_card_limits", "limits on a disposable virtual card"),
+ ("edit_personal_details", "wants to edit name, address or other personal details"),
+ ("exchange_charge", "a fee charged for currency exchange"),
+ ("exchange_rate", "asking what the current exchange rate is"),
+ ("exchange_via_app", "exchanging currency inside the app"),
+ ("extra_charge_on_statement", "an unexplained extra charge on the statement"),
+ ("failed_transfer", "a transfer failed"),
+ ("fiat_currency_support", "which regular currencies are supported"),
+ ("get_disposable_virtual_card", "wants a disposable virtual card"),
+ ("get_physical_card", "wants a physical card"),
+ ("getting_spare_card", "wants a spare or backup card"),
+ ];
+ foreach (var (label, description) in entries)
+ yield return new KeyValuePair<string, object?>(label, description);
+}
diff --git a/laya-dotnet/samples/Laya.Routing/README.md b/laya-dotnet/samples/Laya.Routing/README.md
new file mode 100644
index 00000000..bb64b284
--- /dev/null
+++ b/laya-dotnet/samples/Laya.Routing/README.md
@@ -0,0 +1,290 @@
+# Laya.Routing
+
+**The combined sample for `LanguageDetection`, `LayaRouter`, `LayaEmail` and `LayaShortlist`.**
+Its stdout follows a fixed output contract, so two runs can be diffed line for line (timings
+excepted).
+
+For the full library API, see the [SDK README](../../README.md). For the single-checkpoint
+quickstart, see [`Laya.Sample`](../Laya.Sample/README.md).
+
+---
+
+## Output contract
+
+This is the normative spec both language samples must match byte-for-byte (apart from timings,
+which only ever go to stderr — never build a diff that depends on them).
+
+**Flags:** `--model-root <dir>` (defaults to the `LAYA_ONNX_ROOT` environment variable already
+set for the process), `--download`, `--preload`, `-h`/`--help`.
+
+**Exit codes:** `0` everything printed; `1` a runtime/artifact error (a checkpoint could not be
+resolved); `2` bad usage (missing option value or an unrecognised argument).
+
+**Section headers**, one per section, printed exactly as:
+
+```text
+== 1. Language detection ==
+== 2. Routing decisions ==
+== 3. Router predict ==
+== 4. Email cleaning ==
+== 5. Shortlist ==
+```
+
+A single blank line separates each section's output from the next section's header (no blank
+line after the last section).
+
+**Number formatting:** every probability, confidence and score is formatted with exactly 4
+decimal places under the invariant culture, e.g. `0.1234`, `1.0000`, `-0.0000`. Percentages
+(only ever inside a routing `reason` string, formatted by `LayaRouter` itself) carry no `%`
+decoration beyond the literal `%` character Python's `%.0f%%` already produces.
+
+### Section 1 — Language detection
+
+One line per state, in this exact field order and spacing:
+
+```text
+{name,-22} script={script,-10} language={language ?? "-",-4} is_english={true|false}
+```
+
+`is_english` is lowercase `true`/`false` (not C#'s `True`/`False`). The 8 states are, in order:
+`english`, `spanish_accent_stripped`, `french`, `romanian`, `hindi`, `arabic`, `japanese`,
+`dict_state` (a two-key dictionary state) — the exact literals in
+`laya-dotnet/tools/routing_cases.py`'s `SAMPLE_DETECTION_STATES`, copied verbatim (also recorded in
+`laya-dotnet/tests/Laya.Tests/golden/routing/sample_inputs.json` under `detection_states`).
+
+### Section 2 — Routing decisions
+
+`LayaRouter.Route` only — no checkpoint is loaded. One line per decision:
+
+```text
+{name,-26} -> {model subdir} ({reason})
+```
+
+Note the double space before the parenthesized reason. `{model subdir}` is one of `english`,
+`multilingual`, `typed-decisions` (never the C# enum name). The reason string is whatever
+`RouteDecision.Reason` produced — it must be byte-identical to Python's, including `%r`-style
+quoting and half-even `%.0f%%` rounding; this sample does not reformat it. Seven decisions, in
+order: `auto_english`, `auto_hindi`, `auto_unknown_latin_romanian`,
+`explicit_model_multilingual`, `explicit_lang_de`, `workflow_opt_in_customer_service` (routed
+through a router built with `AutoTaskDetection = true`), `workflow_opt_in_off_by_default`
+(routed through the default router, so the same question ids do **not** trigger the workflow).
+
+### Section 3 — Router predict
+
+For each of the two support emails (English, then Hindi), sharing one `LayaRouter` with
+`MaxLoaded = 2` so both checkpoints stay resident:
+
+```text
+[{lang}] routed to {model subdir}: {reason}
+ {id,-18} {value}
+ {id,-18} {value}
+ ...
+```
+
+`{lang}` is the sample's own case label for the email — `English` or `Hindi` — **not** the
+detected ISO language code (the Hindi state's detected `language` is `null`, since its script
+is Devanagari, not Latin, so an ISO-code label would not exist for it). `{value}` is: the choice
+label as-is for a `ChoiceQuestion`; the score at 4 decimals for a `ScoreQuestion`; the raw
+probability at 4 decimals for a `NoulQuestion` (not `yes`/`no`, and not rounded to a boolean).
+No confidence or action-probability line is printed for any answer — the per-answer output is
+exactly the one line above, nothing more.
+
+### Section 4 — Email cleaning
+
+```text
+--- cleaned ---
+{LayaEmail.CleanBody output, verbatim, including internal blank lines between paragraphs}
+--- end ---
+[{lang}] routed to {model subdir}: {reason}
+ {id,-18} {value}
+ ...
+```
+
+The cleaned body is printed with `Console.WriteLine`, so it ends with exactly one trailing
+newline before `--- end ---`. The routed-to header line and the per-answer lines that follow use
+the **same** format as section 3 (see above), over `LayaPresets.Email()` answered by the same
+shared router on `LayaEmail.State(subject, cleaned-body-input, sender)`. `{lang}` is `"en"` for
+this sample's email.
+
+### Section 5 — Shortlist
+
+A single 40-option choice question run through `LayaShortlist.Predict` (over the same shared
+router) with the demo hashing embedder and `k = LayaShortlist.DefaultShortlistK` (20):
+
+```text
+kept {k} of {n}:
+ {label,-28} {score:0.0000}
+ {label,-28} {score:0.0000}
+ ...
+answer: {choice} ({probability:0.0000})
+```
+
+Labels are printed in the order `ShortlistInfo.Labels` returns them — descending cosine
+similarity, ties keeping the earlier label. `{probability}` is the winning choice's own
+probability from the final (reduced-criteria) forward pass, i.e. `answer[answer.Choice]`, not
+the shortlist's cosine score.
+
+### Timings
+
+Every timing (router construction, each `Predict` call, the shortlist call) is written to
+**stderr only**, never stdout, so `diff`ing the stdout of two runs is never affected by them.
+
+### Verified output
+
+Run against the three exported checkpoints, this sample's stdout is:
+
+```text
+== 1. Language detection ==
+english script=latin language=en is_english=true
+spanish_accent_stripped script=latin language=es is_english=false
+french script=latin language=fr is_english=false
+romanian script=latin language=ro is_english=false
+hindi script=devanagari language=- is_english=false
+arabic script=arabic language=- is_english=false
+japanese script=kana language=- is_english=false
+dict_state script=devanagari language=- is_english=false
+
+== 2. Routing decisions ==
+auto_english -> english (English Latin text)
+auto_hindi -> multilingual (non-Latin script (devanagari, 100% of letters); the English checkpoint cannot read it)
+auto_unknown_latin_romanian -> multilingual (Latin script but language looks like 'ro', not English)
+explicit_model_multilingual -> multilingual (explicit model='multilingual')
+explicit_lang_de -> multilingual (explicit lang='de')
+workflow_opt_in_customer_service -> typed-decisions (question ids match the 'customer_service' typed-decisions workflow)
+workflow_opt_in_off_by_default -> english (English Latin text)
+
+== 3. Router predict ==
+[en] routed to english: English Latin text
+ department billing
+ urgency 1.4400
+ churn_risk 0.8248
+ refund_requested 0.8430
+[hi] routed to multilingual: non-Latin script (devanagari, 74% of letters); the English checkpoint cannot read it
+ department billing
+ urgency 1.9072
+ churn_risk 0.1489
+ refund_requested 0.9966
+
+== 4. Email cleaning ==
+--- cleaned ---
+Hi team,
+
+I was charged twice for the Pro plan this month and the second charge still has not been refunded. This is the third time I have written about it -- please resolve this today or I will need to cancel the account.
+--- end ---
+[en] routed to english: English Latin text
+ category billing
+ is_spam 0.1318
+ is_phishing 0.1345
+ urgency 1.4932
+ needs_reply 0.1545
+
+== 5. Shortlist ==
+kept 20 of 40:
+ card_swallowed 0.5369
+ compromised_card 0.5229
+ cash_withdrawal_not_recognised 0.4926
+ card_payment_not_recognised 0.4672
+ automatic_top_up 0.4631
+ card_linking 0.4371
+ atm_support 0.3783
+ direct_debit_payment_not_recognised 0.3643
+ card_payment_wrong_exchange_rate 0.3472
+ balance_not_updated_after_bank_transfer 0.3320
+ card_not_working 0.3301
+ declined_card_payment 0.3205
+ card_payment_fee_charged 0.3154
+ card_acceptance 0.2983
+ exchange_rate 0.2915
+ card_delivery_estimate 0.2862
+ activate_my_card 0.2751
+ balance_not_updated_after_cheque_or_cash_deposit 0.2737
+ card_about_to_expire 0.2668
+ country_support 0.2631
+answer: card_swallowed (0.7885)
+```
+
+---
+
+## Run it
+
+> **`--model-root` takes the export root, not one checkpoint's folder.** Point it at the
+> directory that *contains* `english/`, `multilingual/` and `typed-decisions/` (for example
+> `onnx/`), not at `onnx/multilingual`. This is the opposite of [`Laya.Sample`](../Laya.Sample/README.md)
+> and `Laya.Benchmark`, which take a single checkpoint's folder with `--model-dir` and reject
+> `--model-root`.
+
+Everything after the bare `--` is passed to the app; without it, `dotnet run` tries to read
+`--model-root` itself. From the repository root:
+
+```bash
+dotnet run --project laya-dotnet/samples/Laya.Routing -- --model-root /path/to/onnx
+```
+
+Or from this sample's own directory (`laya-dotnet/samples/Laya.Routing`):
+
+```powershell
+dotnet run -- --model-root C:/path/to/onnx
+dotnet run -- --model-root C:/path/to/onnx --preload
+```
+
+or set `LAYA_ONNX_ROOT` once and drop the flag — the resolution behaviour is exactly
+`LayaRouter`'s own (`LAYA_ONNX_ROOT/<subfolder>`, then cache, then optional download; see
+`ModelArtifacts.ResolveAsync`). The directory must contain one subdirectory per checkpoint
+actually exercised by this sample: `english/`, `multilingual/`, and `typed-decisions/` is
+resolved only far enough to decide it *would* route there in Section 2 (nothing under
+`typed-decisions/` is ever loaded by this sample — no request routes there in Sections 3-5).
+
+| Option | Effect |
+|---|---|
+| `--model-root <dir>` | Sets `LAYA_ONNX_ROOT` for this process only. Takes priority over an `LAYA_ONNX_ROOT` already in the environment. |
+| `--download` | Allow the router to fetch a missing checkpoint from Hugging Face (`LayaOptions.AllowDownload`), with per-file progress on stderr. Inherits the same "no ONNX export published yet" limitation as `Laya.Sample`. |
+| `--preload` | Build every checkpoint up front (`LayaRouterOptions.Preload`) instead of loading each lazily on first use. |
+| `-h`, `--help` | Print usage and exit 0. |
+
+| Exit code | Meaning |
+|---|---|
+| `0` | All five sections printed. |
+| `1` | A checkpoint could not be resolved (bad `--model-root`/`LAYA_ONNX_ROOT`, or a genuinely missing artifact file). The resolver's own message, which lists every location it tried, is printed to stderr. |
+| `2` | Bad arguments: `--model-root` with no value, or an unrecognised argument. |
+
+## What this sample demonstrates, beyond `Laya.Sample`
+
+| Part | API | Section |
+|---|---|---|
+| Script/language detection with no model at all | `LanguageDetection.Analyse` | 1 |
+| Pure routing decisions, explicit and automatic | `LayaRouter.Route` | 2 |
+| Multi-checkpoint routing with a shared LRU cache (`MaxLoaded=2`) | `LayaRouter.Predict` | 3 |
+| Turning a raw email into a clean, structured state | `LayaEmail.CleanBody`, `LayaEmail.State` | 4 |
+| A ready-made question set, run through the router | `LayaPresets.Email()` | 4 |
+| Reducing a high-cardinality choice question before inference | `LayaShortlist.Predict` | 5 |
+
+## The demo embedder
+
+Section 5 needs *some* `LayaEmbedFunction` to rank 40 labels by similarity to the state. This
+sample uses [`DemoHashingEmbedder.cs`](DemoHashingEmbedder.cs) — **demo only, replace with a
+real embedding model.** It is a hashed character-trigram bag-of-features vector: deterministic,
+dependency-free, and a pure function of its input, chosen only because it can be reimplemented
+bit-for-bit with nothing but a string, UTF-8 bytes and 32-bit FNV-1a. It is a
+direct copy of `laya-dotnet/tools/hashing_embedder.py` (also ported once more, for the test suite, at
+`laya-dotnet/tests/Laya.Tests/HashingEmbedder.cs`) — this sample keeps its own copy rather than
+referencing the test project, so it has no test-only dependency. Do not use it for anything but
+this demo; pass a real bi-encoder (or Python's `embed_fn_from_agent`, which this SDK does not
+port) in production.
+
+## Parity fixture
+
+Like `Laya.Sample`, this sample's exact inputs are recorded as golden data —
+[`sample_inputs.json`](../../tests/Laya.Tests/golden/routing/sample_inputs.json) — generated
+from `laya-dotnet/tools/routing_cases.py`'s `SAMPLE_*` constants by `laya-dotnet/tools/dump_routing_golden.py`. If you
+change a state, question, or the banking criteria list in `Program.cs`, update
+`laya-dotnet/tools/routing_cases.py` to match and regenerate, the same way `Laya.Sample`'s golden cases are
+kept in sync (see that sample's README, "If you change the sample").
+
+Section 3's English support email and question set are, byte-for-byte, the same inputs
+`Laya.Sample` uses for `case_sample_app_english.json`, so its four answers (`billing`, `1.4400`,
+`0.8248`, `0.8430`) and the shortlist's answer (`card_swallowed`, `0.7885`, matching
+`case_shortlist_many_options.json` for the `english` checkpoint) can be checked directly against
+those existing goldens. The Hindi email in this sample is intentionally **not** the same input as
+`case_sample_app_hindi.json` — it carries a `subject` and `from` in addition to `body`, to
+exercise the router's non-Latin path on a fuller state — so its answers are not expected to match
+that golden and are not asserted anywhere; they are illustrative output only.