Storefront has been decoupled into micro-frontends with a dedicated commerce app and shared shell.

Read the architecture guide →

MS Decisions Model Use Case & Lessons Learned

How BookWorm applies Microsoft-Decision-1 (System 1) for single-pass chat routing, safety gating, and dynamic tool selection, and the engineering lessons learned.

AI ArchitectureLessons Learned

BookWorm’s Chat APIServicev1.0.0Chat APIInternal HTTP host for BookWorm's interactive multi-agent chat workflow, agent discovery, and session persistence. Ownerai-capabilities-teamDiagramRepositoryOpen docs uses Microsoft Foundry’s Microsoft-Decision-1 (“System 1”) model to evaluate safety, language, scope, specialist routing, and per-turn tool relevance in single-pass classification calls before invoking a generative chat model (ModelRouter). Replacing generative LLM router prompts with calibrated classification decisions cuts latency, lowers token spend, and enforces deterministic confidence thresholds (0.5 for guardrails and tool selection; 0.6 for direct specialist routing before human-in-the-loop disambiguation).

Context and motivation

Before a specialist AI agent answers a customer message on /ag-ui, Chat API must solve two high-frequency classification problems:

  1. Request screening and specialist routing: Decide whether the message is safe, written in English, and relevant to BookWorm (books, orders, or store policies), then select the right specialist agent (Book, QA, or Rating).
  2. Per-turn tool filtering: Choose which optional tools are relevant to the current conversation turn rather than sending every registered tool definition in every prompt.

Both problems are binary (Yes/No) or multiple-choice classification tasks rather than open-ended generation. Solving them with a full generative LLM adds round-trip latency, consumes prompt tokens on every turn, and risks malformed structured JSON outputs.

How it works

BookWorm deploys FoundryModel.Microsoft.MicrosoftDecision1 alongside FoundryModel.Microsoft.ModelRouter in BookWorm.AppHost and accesses it through a provider-agnostic IDecisionClient contract (BookWorm.Chassis.AI.Decisions), implemented by FoundrySystemOneDecisionClient (/providers/microsoft/v1/systemone).

Use case 1: Single-pass screening and specialist routing

After deterministic rule-based validation (InputValidationExecutor), DecisionRouterExecutor evaluates four decision questions in a single Microsoft-Decision-1 request:

Question IDDecision typeWhat it evaluatesDecision rule
is_safeBinary (Yes/No)Detects prompt-injection, jailbreak, or instruction-override attemptsConfidence < 0.5 stops the request (UnsafeInput)
is_englishBinary (Yes/No)Verifies the message is written in EnglishConfidence < 0.5 stops the request (NonEnglish)
is_in_scopeBinary (Yes/No)Checks relevance to BookWorm books, orders, and store policiesConfidence < 0.5 stops the request (OutOfScope)
routeChoiceSelects book-agent, qa-agent, or rating-agent (selected only when a specific book catalog ID is present)Confidence >= 0.6 routes directly; < 0.6 triggers human-in-the-loop disambiguation via RouteDisambiguationPort

End-to-end single-pass screening, partial-response fallback, and specialist routing flow in Chat API:

Loading graph...

Use case 2: Dynamic per-turn tool selection

DecisionToolSelectionMiddleware (UseDecisionToolSelection) filters optional tools before each specialist LLM invocation:

  1. If ChatOptions.Tools is empty or NoneChatToolMode is active, it forwards the request unchanged.
  2. Otherwise, it captures up to the last 6 messages (MaxContextMessages = 6) as context and separates mandatory tools (AlwaysIncludedToolNames and RequiredChatToolMode) from optional candidate tools.
  3. It sends one binary decision question per candidate tool to IDecisionClient.GetDecisionAsync.
  4. Only candidate tools scoring >= 0.5 (ProbabilityThreshold = 0.5) are merged with mandatory tools and passed to the inner IChatClient.
  5. If the decision call fails, times out, or returns zero tools, the middleware fails open, logs the error, and retains all original tools so the customer still receives a response.

Per-turn tool filtering and fail-open recovery inside DecisionToolSelectionMiddleware:

Loading graph...

Key engineering lessons

  • Isolate vendor wire formats behind an internal contract: Keeping IDecisionClient (DecisionRequest, DecisionResponse, DecisionDefinition<T>) decoupled from SystemOneProtocolMapper lets Chat API workflows remain independent of Microsoft Foundry protocol changes.
  • Handle partial answers explicitly: When Microsoft-Decision-1 leaves route unanswered (DecisionUnansweredException), HandlePartialResponse still enforces any answered is_safe, is_english, or is_in_scope rejections and defaults the route to Book AgentAgentv1.0.0Book AgentPrimary conversational book discovery and recommendation specialist that grounds catalog answers in read-only MCP lookup...PublishesAnalyzeText, AnonymizeTextOwnerai-capabilities-teamDiagramRepositoryOpen docs—preventing both safety bypasses and avoidable chat crashes.
  • Protect mandatory tools before filtering: Partitioning always-included and explicitly required tools before invoking the decision model ensures required workflow tools are never pruned.
  • Use AOT-safe source-generated JSON serialization: DecisionSerializationContext, ChatRoutingSerializationContext, and SystemOneSerializationContext use compile-time System.Text.Json source generation (UseStringEnumConverter = true) to eliminate reflection overhead and preserve strict analyzer compliance.
  • Layer probabilistic screening with deterministic controls: Microsoft-Decision-1 complements—never replaces—InputValidationExecutor, Presidio PIIMiddleware, and Agent Governance GuardrailMiddleware.
  • Test cutoffs deterministically: Unit tests (DecisionRouterExecutorTests, WorkflowRegistrationTests) inject simulated IDecisionClient stubs to verify boundary thresholds (0.5 and 0.6), partial responses, and fail-open paths offline without live Foundry calls.

SystemOneProtocolMapper, ChatRoutingDecisionService, DecisionUnansweredException, and HandlePartialResponse exist in the referenced source trees. No symbol named DecisionSerializationContext exists there.

Design trade-offs

DecisionBenefitsCosts and limits
Single-pass System 1 classification vs. generative routerLower routing latency, lower token usage, and calibrated 0.0-1.0 scoresRequires maintaining explicit question definitions and tuning 0.5/0.6 thresholds as prompts evolve
Fail-open tool filteringPreserves chat availability if the decision model times out or drops all optional toolsTemporarily increases prompt token size during fallback turns
HITL disambiguation below 0.6 route confidenceAvoids misrouting ambiguous customer questions to the wrong specialist agentAdds an extra interactive user turn when intent is unclear
Layered deterministic + AI safety checksFast rejection of empty/malformed inputs plus PII redaction even if AI screening misses an edge caseRequires testing and maintaining three distinct middleware/executor layers

Alternatives considered

  • Full generative LLM router (ModelRouter): Supports nuanced reasoning for ambiguous prompts, but adds multi-second latency and higher token cost on every turn and relies on brittle JSON prompt formatting.
  • Regex and keyword routing only: Runs in microseconds with zero model cost, but fails on natural-language book queries, paraphrased intent, and subtle prompt injections.
  • Passing every tool unconditionally on every turn: Eliminates tool-filtering middleware, but bloats prompt tokens and increases tool-selection errors as the tool catalog grows.