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.
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:
- 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).
- 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 ID | Decision type | What it evaluates | Decision rule |
|---|---|---|---|
is_safe | Binary (Yes/No) | Detects prompt-injection, jailbreak, or instruction-override attempts | Confidence < 0.5 stops the request (UnsafeInput) |
is_english | Binary (Yes/No) | Verifies the message is written in English | Confidence < 0.5 stops the request (NonEnglish) |
is_in_scope | Binary (Yes/No) | Checks relevance to BookWorm books, orders, and store policies | Confidence < 0.5 stops the request (OutOfScope) |
route | Choice | Selects 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:
- If
ChatOptions.Toolsis empty orNoneChatToolModeis active, it forwards the request unchanged. - Otherwise, it captures up to the last 6 messages (
MaxContextMessages = 6) as context and separates mandatory tools (AlwaysIncludedToolNamesandRequiredChatToolMode) from optional candidate tools. - It sends one binary decision question per candidate tool to
IDecisionClient.GetDecisionAsync. - Only candidate tools scoring
>= 0.5(ProbabilityThreshold = 0.5) are merged with mandatory tools and passed to the innerIChatClient. - 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 fromSystemOneProtocolMapperlets Chat API workflows remain independent of Microsoft Foundry protocol changes. - Handle partial answers explicitly: When
Microsoft-Decision-1leavesrouteunanswered (DecisionUnansweredException),HandlePartialResponsestill enforces any answeredis_safe,is_english, oris_in_scoperejections 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, andSystemOneSerializationContextuse compile-timeSystem.Text.Jsonsource generation (UseStringEnumConverter = true) to eliminate reflection overhead and preserve strict analyzer compliance. - Layer probabilistic screening with deterministic controls:
Microsoft-Decision-1complements—never replaces—InputValidationExecutor, PresidioPIIMiddleware, and Agent GovernanceGuardrailMiddleware. - Test cutoffs deterministically: Unit tests (
DecisionRouterExecutorTests,WorkflowRegistrationTests) inject simulatedIDecisionClientstubs to verify boundary thresholds (0.5and0.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
| Decision | Benefits | Costs and limits |
|---|---|---|
| Single-pass System 1 classification vs. generative router | Lower routing latency, lower token usage, and calibrated 0.0-1.0 scores | Requires maintaining explicit question definitions and tuning 0.5/0.6 thresholds as prompts evolve |
| Fail-open tool filtering | Preserves chat availability if the decision model times out or drops all optional tools | Temporarily increases prompt token size during fallback turns |
HITL disambiguation below 0.6 route confidence | Avoids misrouting ambiguous customer questions to the wrong specialist agent | Adds an extra interactive user turn when intent is unclear |
| Layered deterministic + AI safety checks | Fast rejection of empty/malformed inputs plus PII redaction even if AI screening misses an edge case | Requires 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.
Related documentation
- Developer OnboardingCustom DocDeveloper OnboardingA Day 1 and Week 1 roadmap for understanding BookWorm, verifying a workspace, and making a first contribution.Ownerarchitecture-enabling-teamOpen doc — How Chat API, MCP Tools, and Rating API fit into BookWorm’s bounded contexts.
- Architecture DecisionsCustom DocArchitecture DecisionsNavigable register of whole-system and capability-specific architecture decisions.Ownerarchitecture-enabling-teamOpen doc — Formal decision records for Chat orchestration, System 1 routing, and per-agent tool governance.
- Stateful Data, AI & Messaging InfrastructureCustom DocStateful Data, AI & Messaging InfrastructureTechnical reference for Azure-managed databases, caches, storage, Durable Task Scheduler, Microsoft Foundry, and externa...Ownerplatform-engineering-teamOpen doc — Microsoft Foundry deployments (
ModelRouter,MicrosoftDecision1,EmbedV40) and Presidio configuration. - Incident Triage & Health Check RunbookCustom DocIncident Triage & Health Check RunbookFirst-5-minutes triage commands and symptom-first recovery playbooks for Container Apps, passwordless RBAC, order orches...Ownerplatform-engineering-teamOpen doc — Diagnosing AI chat throttling, Presidio sidecar errors, and Entra Agent Identity failures.