---
title: MS Decisions Model Use Case & Lessons Learned
summary: How BookWorm applies Microsoft-Decision-1 (System 1) for single-pass chat routing, safety gating, and dynamic tool selection, and the engineering lessons learned.
owners:
  - architecture-enabling-team
badges:
  - content: AI Architecture
    backgroundColor: purple
    textColor: purple
  - content: Lessons Learned
    backgroundColor: teal
    textColor: teal
---

BookWorm's [[service|chat-api]] 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 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:

<MermaidFileLoader file="mermaids/001-ms-decisions-model-use-case-and-lessons-learned-diagram-1.mmd" />

### 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`:

<MermaidFileLoader file="mermaids/001-ms-decisions-model-use-case-and-lessons-learned-diagram-2.mmd" />

### 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 [[agent|book-agent]]—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

| 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

- [[doc|development/001-developer-onboarding]] — How Chat API, MCP Tools, and Rating API fit into BookWorm's bounded contexts.
- [[doc|arc42/09-architecture-decisions]] — Formal decision records for Chat orchestration, System 1 routing, and per-agent tool governance.
- [[doc|platform/003-data-ai-and-messaging-resources]] — Microsoft Foundry deployments (`ModelRouter`, `MicrosoftDecision1`, `EmbedV40`) and Presidio configuration.
- [[doc|operational/003-incident-response-and-runbooks]] — Diagnosing AI chat throttling, Presidio sidecar errors, and Entra Agent Identity failures.
