diff --git a/.github/issue-routing-owners.yaml b/.github/issue-routing-owners.yaml
index dfa1e9c1b97..225e8f83d8b 100644
--- a/.github/issue-routing-owners.yaml
+++ b/.github/issue-routing-owners.yaml
@@ -82,6 +82,7 @@ routes:
- { path: dotnet/src/Microsoft.Agents.AI.OpenAI/, owner: rogerbarreto, labels: [agents] }
- { path: dotnet/src/Microsoft.Agents.AI.Purview/, owner: westey-m, labels: [security] }
- { path: dotnet/src/Microsoft.Agents.AI.Tools.Shell/, owner: westey-m, labels: [agents] }
+ - { path: dotnet/src/Microsoft.Agents.AI.TypeSafe/, owner: rogerbarreto, labels: [agents] }
- { path: dotnet/src/Microsoft.Agents.AI.Valkey/, owner: westey-m, labels: [] }
- { path: dotnet/src/Microsoft.Agents.AI.Workflows/, owner: baywet, labels: [] }
- { path: dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/, owner: baywet, labels: [] }
diff --git a/.github/workflows/dotnet-verify-samples.yml b/.github/workflows/dotnet-verify-samples.yml
index 1f1b40e9f4a..1f3ffc703c2 100644
--- a/.github/workflows/dotnet-verify-samples.yml
+++ b/.github/workflows/dotnet-verify-samples.yml
@@ -109,6 +109,8 @@ jobs:
FOUNDRY_PROJECT_ENDPOINT: ${{ vars.FOUNDRY_PROJECT_ENDPOINT }}
FOUNDRY_MODEL: ${{ vars.FOUNDRY_MODEL }}
AZURE_AI_BING_CONNECTION_ID: ${{ vars.AZURE_AI_BING_CONNECTION_ID }}
+ # TypeSafe (Jev)
+ TYPESAFE_API_KEY: ${{ secrets.TYPESAFE_API_KEY }}
- name: Write Job Summary
if: always()
diff --git a/dotnet/agent-framework-dotnet.slnx b/dotnet/agent-framework-dotnet.slnx
index e2a8083dc9e..84d443c28da 100644
--- a/dotnet/agent-framework-dotnet.slnx
+++ b/dotnet/agent-framework-dotnet.slnx
@@ -37,6 +37,9 @@
+
+
+
@@ -70,6 +73,7 @@
+
@@ -640,6 +644,7 @@
+
@@ -697,6 +702,7 @@
+
diff --git a/dotnet/agent-framework-src-and-tests.slnf b/dotnet/agent-framework-src-and-tests.slnf
index 0f74c86ec68..8a6c9451fcc 100644
--- a/dotnet/agent-framework-src-and-tests.slnf
+++ b/dotnet/agent-framework-src-and-tests.slnf
@@ -30,6 +30,7 @@
"src\\Microsoft.Agents.AI.OpenAI\\Microsoft.Agents.AI.OpenAI.csproj",
"src\\Microsoft.Agents.AI.Purview\\Microsoft.Agents.AI.Purview.csproj",
"src\\Microsoft.Agents.AI.Tools.Shell\\Microsoft.Agents.AI.Tools.Shell.csproj",
+ "src\\Microsoft.Agents.AI.TypeSafe\\Microsoft.Agents.AI.TypeSafe.csproj",
"src\\Microsoft.Agents.AI.Valkey\\Microsoft.Agents.AI.Valkey.csproj",
"src\\Microsoft.Agents.AI.Workflows.Declarative.Foundry\\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj",
"src\\Microsoft.Agents.AI.Workflows.Declarative.Mcp\\Microsoft.Agents.AI.Workflows.Declarative.Mcp.csproj",
@@ -65,6 +66,7 @@
"tests\\Microsoft.Agents.AI.OpenAI.UnitTests\\Microsoft.Agents.AI.OpenAI.UnitTests.csproj",
"tests\\Microsoft.Agents.AI.Purview.UnitTests\\Microsoft.Agents.AI.Purview.UnitTests.csproj",
"tests\\Microsoft.Agents.AI.Tools.Shell.UnitTests\\Microsoft.Agents.AI.Tools.Shell.UnitTests.csproj",
+ "tests\\Microsoft.Agents.AI.TypeSafe.UnitTests\\Microsoft.Agents.AI.TypeSafe.UnitTests.csproj",
"tests\\Microsoft.Agents.AI.UnitTests\\Microsoft.Agents.AI.UnitTests.csproj",
"tests\\Microsoft.Agents.AI.Valkey.UnitTests\\Microsoft.Agents.AI.Valkey.UnitTests.csproj",
"tests\\Microsoft.Agents.AI.Workflows.Declarative.Mcp.UnitTests\\Microsoft.Agents.AI.Workflows.Declarative.Mcp.UnitTests.csproj",
diff --git a/dotnet/eng/verify-samples/AgentsSamples.cs b/dotnet/eng/verify-samples/AgentsSamples.cs
index a4c32d13d50..3f8504d5980 100644
--- a/dotnet/eng/verify-samples/AgentsSamples.cs
+++ b/dotnet/eng/verify-samples/AgentsSamples.cs
@@ -90,6 +90,55 @@ internal static class AgentsSamples
],
},
+ new SampleDefinition
+ {
+ Name = "Agent_TypeSafe_Step01_LoopJudge",
+ ProjectPath = "samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge",
+ RequiredEnvironmentVariables = ["FOUNDRY_PROJECT_ENDPOINT", "TYPESAFE_API_KEY"],
+ OptionalEnvironmentVariables = ["FOUNDRY_MODEL"],
+ MustContain = ["Answer 1:", "Judge:", "red_sunsets:", "Final answer:"],
+ ExpectedOutputDescription =
+ [
+ "The first answer should explain only why the sky is blue, and the judge should mark red_sunsets as missing with a low probability.",
+ "A later answer should also explain why sunsets are red, and the judge should mark red_sunsets as met for it.",
+ "Every numbered answer (Answer 1, Answer 2, and so on) should be followed by a Judge block with probabilities. The Final answer section repeats the last judged answer and has no Judge block of its own.",
+ "The final answer should explain both why the sky is blue and why sunsets are red.",
+ "The output should not contain error messages or stack traces.",
+ ],
+ },
+
+ new SampleDefinition
+ {
+ Name = "Agent_TypeSafe_Step02_DecisionTool",
+ ProjectPath = "samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool",
+ RequiredEnvironmentVariables = ["FOUNDRY_PROJECT_ENDPOINT", "TYPESAFE_API_KEY"],
+ OptionalEnvironmentVariables = ["FOUNDRY_MODEL"],
+ MustContain = ["Ticket:", "Tool result:", "department", "The same tool, answered by a local keyword decision client:"],
+ ExpectedOutputDescription =
+ [
+ "Each ticket should show a tool result with department, urgentProbability, and frustration values, followed by a one-line agent reply.",
+ "The failing Stripe integration ticket should be routed to Technical with a high urgent probability, and the invoice request should be routed to Billing with a low urgent probability.",
+ "The last part should show a tool result from the local keyword decision client for the invoice ticket, routed to Billing, followed by an agent reply.",
+ "The output should not contain error messages or stack traces.",
+ ],
+ },
+
+ new SampleDefinition
+ {
+ Name = "Agent_TypeSafe_Step03_DecisionRouting",
+ ProjectPath = "samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting",
+ RequiredEnvironmentVariables = ["FOUNDRY_PROJECT_ENDPOINT", "TYPESAFE_API_KEY"],
+ OptionalEnvironmentVariables = ["FOUNDRY_MODEL", "FOUNDRY_REASONING_MODEL"],
+ MustContain = ["User:", "Route: Fast", "Route: Reasoning", "Agent:"],
+ ExpectedOutputDescription =
+ [
+ "The question about the capital of France should be routed to Fast and answered with Paris.",
+ "The demand forecasting request should be routed to Reasoning and answered with a comparison of three methods and a recommendation.",
+ "Each route line should show the probabilities of both routes and the model that answered.",
+ "The output should not contain error messages or stack traces.",
+ ],
+ },
+
// ── Agents ──────────────────────────────────────────────────────────
new SampleDefinition
@@ -416,6 +465,29 @@ internal static class AgentsSamples
],
},
+ new SampleDefinition
+ {
+ Name = "Agent_Step25_ClassificationWithJev",
+ ProjectPath = "samples/02-agents/Agents/Agent_Step25_ClassificationWithJev",
+ RequiredEnvironmentVariables = ["FOUNDRY_PROJECT_ENDPOINT", "TYPESAFE_API_KEY"],
+ OptionalEnvironmentVariables = ["FOUNDRY_MODEL"],
+ MustContain =
+ [
+ "Ticket:",
+ "Tool result:",
+ "The same tool, answered by a local keyword classifier:",
+ "local-keyword-classifier",
+ ],
+ ExpectedOutputDescription =
+ [
+ "Each of the three tickets should show a tool result with department, urgent, and frustration answers from a jev model, followed by a one-line agent reply.",
+ "The failing Stripe integration ticket should be routed to technical and marked urgent, and the invoice request should be routed to billing and not urgent.",
+ "The vague account ticket may be sent to human review when the department confidence is low.",
+ "The last part should show a tool result from the local-keyword-classifier model for the invoice ticket, followed by an agent reply.",
+ "The output should not contain error messages or stack traces.",
+ ],
+ },
+
// ── AgentSkills ─────────────────────────────────────────────────────
new SampleDefinition
diff --git a/dotnet/samples/02-agents/AgentProviders/README.md b/dotnet/samples/02-agents/AgentProviders/README.md
index 32c0afb1025..ebd09d35646 100644
--- a/dotnet/samples/02-agents/AgentProviders/README.md
+++ b/dotnet/samples/02-agents/AgentProviders/README.md
@@ -94,6 +94,14 @@ covering basics, function tools, structured output, middleware, MCP, code interp
| [Conversation](./openai/Agent_OpenAI_Step05_Conversation/) | Multi-turn conversations with OpenAI |
| [Code Interpreter](./openai/Agent_OpenAI_Step06_CodeInterpreterFileDownload/) | Code interpreter with file downloads |
+### [TypeSafe](./typesafe/)
+
+| Sample | Description |
+| --- | --- |
+| [Loop judge](./typesafe/Agent_TypeSafe_Step01_LoopJudge/) | Use Jev as the judge of a LoopAgent, through an IDecisionClient and a typed decision definition |
+| [Decision tool](./typesafe/Agent_TypeSafe_Step02_DecisionTool/) | Give an agent a decision as a tool with `DecisionDefinition.AsAIFunction`, and answer it with Jev or a local decision client |
+| [Decision routing](./typesafe/Agent_TypeSafe_Step03_DecisionRouting/) | Route each request of an agent to a fast or a reasoning model, with Jev choosing the route through `RoutingChatClient` |
+
## Running the samples
Navigate to a sample directory and run:
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Agent_TypeSafe_Step01_LoopJudge.csproj b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Agent_TypeSafe_Step01_LoopJudge.csproj
new file mode 100644
index 00000000000..48a53996f27
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Agent_TypeSafe_Step01_LoopJudge.csproj
@@ -0,0 +1,20 @@
+
+
+
+ Exe
+ net10.0
+
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Program.cs b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Program.cs
new file mode 100644
index 00000000000..fd303db594e
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/Program.cs
@@ -0,0 +1,120 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+// This sample uses Jev, the TypeSafe System One model, as the judge of a LoopAgent. A Foundry agent writes the
+// answer. After each answer, Jev checks every criterion with its own yes or no question, and the loop sends the agent
+// the criteria that are still missing, until the answer meets all of them. The judge uses the decision API proposed
+// for Microsoft.Extensions.AI: an IDecisionClient and a typed DecisionDefinition.
+
+#pragma warning disable MAAI001 // LoopAgent and DelegateLoopEvaluator are experimental.
+#pragma warning disable MEAI001 // The decision API is experimental.
+
+using System.ClientModel;
+using Azure.AI.Projects;
+using Azure.Identity;
+using Microsoft.Agents.AI;
+using Microsoft.Agents.AI.TypeSafe;
+using Microsoft.Extensions.AI;
+
+var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
+var deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
+var typeSafeApiKey = Environment.GetEnvironmentVariable("TYPESAFE_API_KEY") ?? throw new InvalidOperationException("TYPESAFE_API_KEY is not set.");
+
+// 1. The criteria, as a typed verdict. Each property is a Binary question, whose answer is the probability that the
+// answer meets the criterion, so the judge reports exactly which criteria are missing instead of a single verdict. The
+// questions describe what a good answer contains; wording that steers the judge, such as "only say yes if", tends to
+// push every answer one way.
+DecisionDefinition criteria = DecisionDefinition.Create(builder =>
+{
+ builder.BinaryProbability(verdict => verdict.BlueSky, "Does `answer` explain why the daytime sky appears blue?");
+ builder.BinaryProbability(verdict => verdict.RedSunsets, "Does `answer` explain why sunsets appear red or orange?");
+ builder.BinaryProbability(verdict => verdict.PlainLanguage, "Does `answer` use clear language suitable for a general audience?");
+});
+
+// A criterion is met when its probability is above this threshold. 0.5 is not calibrated for any task: a higher value
+// accepts fewer answers that still miss a criterion, at the cost of more loop runs. Choose it on labeled examples of
+// your own answers.
+const double CriterionThreshold = 0.5;
+
+// 2. The agent that writes the answers. Its instructions hold back part of the first answer, so the judge has a gap
+// to find and the loop runs more than once.
+// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
+// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
+// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
+AIAgent answerer = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential()).AsAIAgent(
+ model: deploymentName,
+ name: "Answerer",
+ instructions: """
+ You answer science questions for a general audience in one short paragraph.
+ Your first answer is a single sentence about why the daytime sky is blue. It does not mention sunsets, even
+ if the user asks about them.
+ When feedback lists missing points, rewrite the whole answer so that it covers them too.
+ """);
+
+// 3. The judge. AIJudgeLoopEvaluator asks a chat client for JSON structured output, which a decision model does not
+// write, so a DelegateLoopEvaluator asks the decision client the criteria questions instead. The state is the request
+// and the latest answer.
+using IDecisionClient judge = new JevDecisionClient(new ApiKeyCredential(typeSafeApiKey));
+bool accepted = false;
+var evaluator = new DelegateLoopEvaluator(async (context, cancellationToken) =>
+{
+ Console.WriteLine($"\nAnswer {context.Iteration}:\n{context.LastResponse.Text}");
+ string request = string.Join("\n", context.InitialMessages.Select(message => message.Text));
+ List missing = await JudgeAsync(request, context.LastResponse.Text, cancellationToken);
+ accepted = missing.Count == 0;
+
+ // The feedback names the missing criteria, which is the gap analysis that a generative judge would write.
+ return accepted
+ ? LoopEvaluation.Stop()
+ : LoopEvaluation.Continue($"Your answer does not yet: {string.Join("; ", missing)}. Rewrite the whole answer so that it does.");
+});
+
+// 4. The loop re-runs the agent until the judge stops it. MaxIterations bounds the cost if the answer never passes.
+const int MaxIterations = 3;
+const string Request = "Explain why the sky is blue and why sunsets are red.";
+AIAgent loop = new LoopAgent(answerer, evaluator, new LoopAgentOptions { MaxIterations = MaxIterations, NonStreamingReturnsLastResponseOnly = true });
+AgentResponse response = await loop.RunAsync(Request);
+
+// LoopAgent stops at MaxIterations before it calls the evaluator, so an answer from the last allowed run has not been
+// judged yet. Judging it here keeps the final answer from being presented as accepted when it may miss a criterion.
+if (!accepted)
+{
+ Console.WriteLine($"\nAnswer {MaxIterations} (the last run the loop allows):\n{response.Text}");
+ accepted = (await JudgeAsync(Request, response.Text, CancellationToken.None)).Count == 0;
+}
+
+Console.WriteLine(accepted ? "\nFinal answer:" : "\nFinal answer (some criteria are still missing):");
+Console.WriteLine(response.Text);
+
+// Asks the judge whether the answer meets each criterion, prints the probabilities, and returns the missing criteria.
+async Task> JudgeAsync(string request, string answer, CancellationToken cancellationToken)
+{
+ DecisionResponse decision = await judge.GetResponseAsync(new JudgedAnswer(request, answer), criteria, cancellationToken: cancellationToken);
+ Verdict verdict = decision.Result;
+
+ Console.WriteLine("Judge:");
+ List missing = [];
+ foreach ((string name, string description, double probability) in new[]
+ {
+ ("blue_sky", "explain why the daytime sky appears blue", verdict.BlueSky),
+ ("red_sunsets", "explain why sunsets appear red or orange", verdict.RedSunsets),
+ ("plain_language", "use clear language suitable for a general audience", verdict.PlainLanguage),
+ })
+ {
+ bool met = probability > CriterionThreshold;
+ Console.WriteLine($" {name}: {(met ? "met" : "missing")} (probability {probability:F2})");
+ if (!met)
+ {
+ missing.Add(description);
+ }
+ }
+
+ return missing;
+}
+
+/// The state the judge reads: the user's request and the answer to judge.
+internal sealed record JudgedAnswer(string Request, string Answer);
+
+/// The probability that the answer meets each criterion.
+#pragma warning disable CA1812 // Instantiated by the decision definition, which creates the result from the answers.
+internal sealed record Verdict(double BlueSky, double RedSunsets, double PlainLanguage);
+#pragma warning restore CA1812
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/README.md b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/README.md
new file mode 100644
index 00000000000..897b4d105f1
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step01_LoopJudge/README.md
@@ -0,0 +1,109 @@
+# Jev as the judge of a loop
+
+This sample uses Jev, the TypeSafe System One model, as the judge of a `LoopAgent`. A Foundry agent writes the
+answer, and Jev decides whether the answer is complete. The judge uses the decision API proposed for
+Microsoft.Extensions.AI ([dotnet/extensions#7795](https://github.com/dotnet/extensions/pull/7795)), which
+`Microsoft.Agents.AI.Abstractions` carries until it ships: `JevDecisionClient` is an `IDecisionClient`, and the criteria
+are a typed `DecisionDefinition`. Any other `IDecisionClient` can be the judge without changing the loop.
+
+A generative judge writes a verdict and a gap analysis. A decision model writes no text, so the sample asks one Binary
+question per criterion instead. Each answer is the probability, from 0 to 1, that the answer meets that criterion, so
+the judge reports exactly which criteria are missing:
+
+```text
+Judge:
+ blue_sky: met (probability 0.99)
+ red_sunsets: missing (probability 0.02)
+ plain_language: met (probability 0.92)
+```
+
+The loop turns the missing criteria into the feedback for the next run, and stops when every criterion is met or after
+three runs. The agent's instructions hold back part of the first answer on purpose, so the loop visibly runs twice.
+
+`LoopAgent` checks `MaxIterations` before it calls the evaluator, so when the loop reaches its limit, the answer of the
+last run has not been judged. The sample judges that answer after the loop and labels the final answer when some
+criteria are still missing, instead of presenting it as accepted.
+
+## The criteria as a typed definition
+
+Each criterion is a `double` property of `Verdict`, declared as a Binary probability with its question:
+
+```csharp
+DecisionDefinition criteria = DecisionDefinition.Create(builder =>
+{
+ builder.BinaryProbability(verdict => verdict.BlueSky, "Does `answer` explain why the daytime sky appears blue?");
+ builder.BinaryProbability(verdict => verdict.RedSunsets, "Does `answer` explain why sunsets appear red or orange?");
+ builder.BinaryProbability(verdict => verdict.PlainLanguage, "Does `answer` use clear language suitable for a general audience?");
+});
+```
+
+The state is a `JudgedAnswer(Request, Answer)` record, so the questions can refer to its fields in backticks. One call
+answers every criterion and returns a `Verdict` with the probabilities, plus the complete decision response as
+`Evidence`:
+
+```csharp
+DecisionResponse decision = await judge.GetResponseAsync(new JudgedAnswer(request, answer), criteria);
+```
+
+The same pattern works with `builder.Score` for a graded rubric, or `builder.Choice` with an enum to classify what kind
+of revision is needed.
+
+## Why a delegate evaluator
+
+`AIJudgeLoopEvaluator` asks a chat client for a `JudgeVerdict` as JSON structured output, which a decision model does
+not write. The sample wraps the decision client in a `DelegateLoopEvaluator` instead:
+
+```csharp
+var evaluator = new DelegateLoopEvaluator(async (context, cancellationToken) =>
+{
+ string request = string.Join("\n", context.InitialMessages.Select(message => message.Text));
+ List missing = await JudgeAsync(request, context.LastResponse.Text, cancellationToken);
+ accepted = missing.Count == 0;
+ return accepted
+ ? LoopEvaluation.Stop()
+ : LoopEvaluation.Continue($"Your answer does not yet: {string.Join("; ", missing)}. ...");
+});
+```
+
+`JudgeAsync` returns the criteria whose probability is at or below `CriterionThreshold`.
+
+## Writing criteria for a judge
+
+- **Choose the threshold on your own data.** The sample treats a criterion as met when its probability is above
+ `CriterionThreshold`, which is 0.5. That value is not calibrated for any task. The threshold trades two errors
+ against each other: a higher value accepts fewer answers that still miss a criterion, and costs more loop runs, while
+ a lower value stops sooner and lets more incomplete answers through. Pick it from labeled examples of the answers your
+ agent writes, based on which error costs you more.
+- **Describe the criterion, do not steer the judge.** Ask what a good answer contains, as the sample does ("Does
+ `answer` explain why sunsets appear red or orange?"). Directional wording such as "only say yes if" or
+ "lean towards yes" tends to push every answer the same way instead of making the judge more accurate. When a
+ criterion is hard to judge, a neutral description of what is being judged helps more than stronger wording.
+- **Ask about the response, not the topic.** When the conversation contains harmful or sensitive content, a question
+ such as "Is this safe?" can be read as a question about that content rather than about the answer. A correct
+ refusal could then look like a missing criterion, and the loop would keep revising an answer that was already right.
+ Ask how the response handles the request, for example "Does `answer` decline to give dangerous instructions?", and
+ check such criteria on labeled examples, including refusals, before relying on them.
+
+## Prerequisites
+
+- .NET 10 SDK or later
+- A Microsoft Foundry project with a deployed chat model
+- Azure CLI installed and authenticated (`az login`)
+- A TypeSafe API key
+
+Set the environment variables:
+
+```powershell
+$env:FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
+$env:FOUNDRY_MODEL="gpt-5.4-mini" # Optional, defaults to gpt-5.4-mini
+$env:TYPESAFE_API_KEY="your-typesafe-api-key"
+```
+
+## Running the sample
+
+```powershell
+dotnet run
+```
+
+The sample prints each answer with the judge's probabilities, then the final answer, labeled when some criteria are
+still missing. The wording of the answers and the exact probabilities vary between runs.
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Agent_TypeSafe_Step02_DecisionTool.csproj b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Agent_TypeSafe_Step02_DecisionTool.csproj
new file mode 100644
index 00000000000..48a53996f27
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Agent_TypeSafe_Step02_DecisionTool.csproj
@@ -0,0 +1,20 @@
+
+
+
+ Exe
+ net10.0
+
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/KeywordDecisionClient.cs b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/KeywordDecisionClient.cs
new file mode 100644
index 00000000000..9242e06e73c
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/KeywordDecisionClient.cs
@@ -0,0 +1,78 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+#pragma warning disable MEAI001 // The decision API is experimental.
+
+using System.Text.RegularExpressions;
+using Microsoft.Extensions.AI;
+
+///
+/// A local that answers by matching words, as a stand-in for another decision model.
+///
+///
+/// It knows only this sample's questions: a Choice picks the candidate whose description shares the most words with the
+/// ticket, a Binary question looks for urgent words, and a Score counts frustrated words. Like any decision client, it
+/// answers every question with a complete distribution.
+///
+internal sealed partial class KeywordDecisionClient : IDecisionClient
+{
+ private static readonly string[] s_urgentWords = ["asap", "urgent", "immediately", "losing", "down", "blocked"];
+ private static readonly string[] s_frustratedWords = ["still", "keeps", "again", "losing", "days", "failing"];
+
+ public Task GetResponseAsync(DecisionRequest request, DecisionOptions? options = null, CancellationToken cancellationToken = default)
+ {
+ HashSet words = Stems(request.State.GetRawText());
+ List answers = [.. request.Questions.Select(question => Answer(question, words))];
+ return Task.FromResult(new DecisionResponse(request, answers, new DecisionProvenance(providerName: "local", modelId: "local-keyword-matcher")));
+ }
+
+ public object? GetService(Type serviceType, object? serviceKey = null) =>
+ serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null;
+
+ public void Dispose()
+ {
+ }
+
+ private static DecisionAnswer Answer(DecisionQuestion question, HashSet words) =>
+ question switch
+ {
+ ChoiceDecisionQuestion choice => Choose(choice, words),
+ BinaryDecisionQuestion binary => new BinaryDecisionAnswer(binary.Id, s_urgentWords.Any(word => words.Contains(Stem(word))) ? 0.9 : 0.1),
+ ScoreDecisionQuestion score => Rate(score, words),
+ _ => throw new NotSupportedException($"The keyword client does not answer {question.Kind} questions."),
+ };
+
+ // Each candidate scores one plus the number of its description words in the ticket, and the scores become the
+ // probabilities.
+ private static ChoiceDecisionAnswer Choose(ChoiceDecisionQuestion choice, HashSet words)
+ {
+ double[] scores = [.. choice.Candidates.Select(candidate => 1.0 + Stems(candidate.Description).Count(words.Contains))];
+ double total = scores.Sum();
+ int selected = Array.IndexOf(scores, scores.Max());
+ return new ChoiceDecisionAnswer(
+ choice.Id,
+ choice.Candidates[selected].Id,
+ [.. choice.Candidates.Select((candidate, index) => new DecisionProbability(candidate.Id, scores[index] / total))]);
+ }
+
+ // The level is the number of frustrated words, at most the top level, with most of the probability on it.
+ private static ScoreDecisionAnswer Rate(ScoreDecisionQuestion score, HashSet words)
+ {
+ int top = score.Levels.Count - 1;
+ int level = Math.Min(top, s_frustratedWords.Count(word => words.Contains(Stem(word))) / 2);
+ double[] probabilities = [.. score.Levels.Select((_, index) => index == level ? 0.8 : 0.2 / top)];
+ double expected = Math.Round(probabilities.Select((probability, index) => probability * index).Sum(), 10);
+ return new ScoreDecisionAnswer(
+ score.Id,
+ expected,
+ [.. score.Levels.Select((level, index) => new DecisionProbability(level.Id, probabilities[index]))]);
+ }
+
+ // Words are compared by their first five letters, ignoring case, so "Invoice" matches "invoices".
+ private static HashSet Stems(string text) =>
+ new(WordPattern().Matches(text).Select(match => Stem(match.Value)), StringComparer.OrdinalIgnoreCase);
+
+ private static string Stem(string word) => word.Length > 5 ? word[..5] : word;
+
+ [GeneratedRegex("[a-z]+", RegexOptions.IgnoreCase)]
+ private static partial Regex WordPattern();
+}
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Program.cs b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Program.cs
new file mode 100644
index 00000000000..18ab00d6c7e
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/Program.cs
@@ -0,0 +1,122 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+// This sample gives a Foundry agent a decision as a tool, with the decision API proposed for Microsoft.Extensions.AI.
+// The application fixes the questions in a typed DecisionDefinition, and the agent only passes the ticket: Jev, the
+// TypeSafe System One model, answers the questions, and the agent replies from the typed result. The same tool is then
+// answered by a local IDecisionClient, without changing the agent.
+
+#pragma warning disable MEAI001 // The decision API is experimental.
+
+using System.ClientModel;
+using System.ComponentModel;
+using Azure.AI.Projects;
+using Azure.Identity;
+using Microsoft.Agents.AI;
+using Microsoft.Agents.AI.TypeSafe;
+using Microsoft.Extensions.AI;
+
+var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
+var deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
+var typeSafeApiKey = Environment.GetEnvironmentVariable("TYPESAFE_API_KEY") ?? throw new InvalidOperationException("TYPESAFE_API_KEY is not set.");
+
+//
+// 1. The questions, as a typed result. The enum property is a Choice among its values, the probability is a Binary
+// question, and the frustration is a Score on an ordered rubric. The [Description] attributes on TicketAnalysis and
+// Department, at the end of this file, are the question instructions and the choice descriptions.
+DecisionDefinition analysis = DecisionDefinition.Create(builder =>
+{
+ builder.Choice(result => result.Department);
+ builder.BinaryProbability(result => result.UrgentProbability);
+ builder.Score(result => result.Frustration, [new("calm", "The customer is calm."), new("annoyed", "The customer is annoyed."), new("angry", "The customer is angry.")]);
+});
+//
+
+//
+// 2. The tool. Its only argument is the ticket. The questions and the decision client belong to the application, so
+// the model cannot change what is asked, and the result is the typed TicketAnalysis.
+var toolOptions = new AIFunctionFactoryOptions
+{
+ Name = "analyze_ticket",
+ Description = "Classifies a support ticket: the department that should handle it, the probability that it is urgent, and how frustrated the customer is.",
+};
+
+using IDecisionClient jev = new JevDecisionClient(new ApiKeyCredential(typeSafeApiKey));
+AIFunction analyzeTicket = analysis.AsAIFunction(jev, toolOptions);
+//
+
+const string Instructions = """
+ You triage customer support tickets. For each ticket, call analyze_ticket with the ticket text, then reply in one
+ line with the department, whether the ticket is urgent (when the urgent probability is above 0.5), and the
+ frustration level (0 is calm, 1 annoyed, 2 angry).
+ """;
+
+// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
+// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
+// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
+var projectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());
+AIAgent agent = projectClient.AsAIAgent(model: deploymentName, instructions: Instructions, name: "TicketTriage", tools: [analyzeTicket]);
+
+string[] tickets =
+[
+ "I've been trying to connect my Stripe account for 3 days and the integration keeps failing. I'm losing sales. Please help ASAP.",
+ "Hi, could you send me a copy of last month's invoice when you get a chance? Thanks!",
+];
+
+foreach (string ticket in tickets)
+{
+ await TriageAsync(agent, ticket);
+}
+
+//
+// 3. The same definition and agent instructions, answered by another decision client. Any IDecisionClient works,
+// such as another decision model or, here, a local keyword matcher.
+using IDecisionClient keywords = new KeywordDecisionClient();
+AIAgent localAgent = projectClient.AsAIAgent(
+ model: deploymentName,
+ instructions: Instructions,
+ name: "LocalTicketTriage",
+ tools: [analysis.AsAIFunction(keywords, toolOptions)]);
+//
+
+Console.WriteLine("The same tool, answered by a local keyword decision client:");
+Console.WriteLine();
+await TriageAsync(localAgent, tickets[1]);
+
+static async Task TriageAsync(AIAgent agent, string ticket)
+{
+ AgentResponse response = await agent.RunAsync(ticket);
+
+ Console.WriteLine($"Ticket: {ticket}");
+ foreach (FunctionResultContent result in response.Messages.SelectMany(static m => m.Contents).OfType())
+ {
+ Console.WriteLine($"Tool result: {result.Result}");
+ }
+
+ Console.WriteLine($"Agent: {response.Text}");
+ Console.WriteLine();
+}
+
+#pragma warning disable CA1812 // SupportTicket is the tool argument, and TicketAnalysis is created from the answers.
+
+/// The tool's input: the ticket that the agent passes.
+internal sealed record SupportTicket([Description("The ticket text, as the customer wrote it.")] string Text);
+
+/// The teams that handle tickets. Each description tells the decision model what belongs to the team.
+internal enum Department
+{
+ [Description("Payments, invoices, refunds, and charges.")]
+ Billing,
+
+ [Description("Bugs, outages, errors, and integrations.")]
+ Technical,
+
+ [Description("Plans, pricing, upgrades, and new purchases.")]
+ Sales,
+}
+
+/// The tool's result. Each description is the instruction of the question that fills the property.
+internal sealed record TicketAnalysis(
+ [Description("Which team should handle the ticket?")] Department Department,
+ [Description("Does the ticket need urgent attention?")] double UrgentProbability,
+ [Description("How frustrated is the customer who wrote the ticket?")] double Frustration);
+#pragma warning restore CA1812
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/README.md b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/README.md
new file mode 100644
index 00000000000..58de761fc9e
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/README.md
@@ -0,0 +1,65 @@
+# A decision as an agent tool
+
+This sample gives a Foundry agent a decision as a tool, with the decision API proposed for Microsoft.Extensions.AI
+([dotnet/extensions#7795](https://github.com/dotnet/extensions/pull/7795) and
+[#7796](https://github.com/dotnet/extensions/pull/7796)), which `Microsoft.Agents.AI.Abstractions` carries until it ships.
+The agent triages support tickets: it calls the tool with the ticket, and replies from the typed result.
+
+## How it works
+
+The application declares the questions once, as a typed result:
+
+```csharp
+DecisionDefinition analysis = DecisionDefinition.Create(builder =>
+{
+ builder.Choice(result => result.Department);
+ builder.BinaryProbability(result => result.UrgentProbability);
+ builder.Score(result => result.Frustration, [new("calm", "..."), new("annoyed", "..."), new("angry", "...")]);
+});
+```
+
+`Department` is an enum, so its question is a Choice among its values, and the `[Description]` of each value tells the
+decision model what belongs to it. The `[Description]` of each `TicketAnalysis` parameter is the instruction of its
+question.
+
+`AsAIFunction` turns the definition into the agent's tool:
+
+```csharp
+using IDecisionClient jev = new JevDecisionClient(new ApiKeyCredential(typeSafeApiKey));
+AIFunction analyzeTicket = analysis.AsAIFunction(jev, new AIFunctionFactoryOptions { Name = "analyze_ticket", ... });
+```
+
+The tool's only argument is the `SupportTicket`. The questions and the decision client belong to the application, so
+the model cannot change what is asked or which labels exist, and the result is a `TicketAnalysis` rather than raw
+answers. Jev, the TypeSafe System One model, answers all three questions in one call.
+
+The last part answers the same tool with `KeywordDecisionClient`, a local `IDecisionClient` that matches words. The
+agent and the definition do not change, which is how another decision model, such as Azure OpenAI Decisions, would be
+used.
+
+Compare with [Agent_Step25_ClassificationWithJev](../../../Agents/Agent_Step25_ClassificationWithJev/), where the
+agent's model writes the questions on every call through `JevAIToolBuilder`.
+
+## Prerequisites
+
+- .NET 10 SDK or later
+- A Microsoft Foundry project with a deployed chat model
+- Azure CLI installed and authenticated (`az login`)
+- A TypeSafe API key
+
+Set the environment variables:
+
+```powershell
+$env:FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
+$env:FOUNDRY_MODEL="gpt-5.4-mini" # Optional, defaults to gpt-5.4-mini
+$env:TYPESAFE_API_KEY="your-typesafe-api-key"
+```
+
+## Running the sample
+
+```powershell
+dotnet run
+```
+
+For each ticket, the sample prints the tool result and the agent's one-line reply. The exact probabilities vary between
+runs.
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Agent_TypeSafe_Step03_DecisionRouting.csproj b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Agent_TypeSafe_Step03_DecisionRouting.csproj
new file mode 100644
index 00000000000..48a53996f27
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Agent_TypeSafe_Step03_DecisionRouting.csproj
@@ -0,0 +1,20 @@
+
+
+
+ Exe
+ net10.0
+
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Program.cs b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Program.cs
new file mode 100644
index 00000000000..6657b491a47
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/Program.cs
@@ -0,0 +1,92 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+// This sample routes each request of an agent to a fast model or a reasoning model, and a decision model chooses the
+// route. RoutingChatClient from Microsoft.Extensions.AI asks a selector which chat client handles each call, and the
+// selector asks Jev, the TypeSafe System One model, a Choice question through the decision API proposed for
+// Microsoft.Extensions.AI. The agent itself is an ordinary agent over the router.
+
+#pragma warning disable MEAI001 // RoutingChatClient and the decision API are experimental.
+
+using System.ClientModel;
+using System.ComponentModel;
+using Azure.AI.Extensions.OpenAI;
+using Azure.AI.Projects;
+using Azure.Identity;
+using Microsoft.Agents.AI;
+using Microsoft.Agents.AI.TypeSafe;
+using Microsoft.Extensions.AI;
+
+var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
+var fastModel = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
+var reasoningModel = Environment.GetEnvironmentVariable("FOUNDRY_REASONING_MODEL") ?? fastModel;
+var typeSafeApiKey = Environment.GetEnvironmentVariable("TYPESAFE_API_KEY") ?? throw new InvalidOperationException("TYPESAFE_API_KEY is not set.");
+
+// 1. The route question: a Choice among the values of Route, whose descriptions tell the decision model when to pick
+// each one.
+DecisionDefinition routing = DecisionDefinition.Create(builder => builder.Choice(decision => decision.Route));
+
+// 2. One chat client per route. Each one is bound to its own deployment.
+// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
+// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
+// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
+var projectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());
+using IChatClient fast = projectClient.GetProjectOpenAIClient().GetProjectResponsesClientForModel(fastModel).AsIChatClientWithStoredOutputDisabled(fastModel);
+using IChatClient reasoning = projectClient.GetProjectOpenAIClient().GetProjectResponsesClientForModel(reasoningModel).AsIChatClientWithStoredOutputDisabled(reasoningModel);
+Dictionary clients = new() { [Route.Fast] = fast, [Route.Reasoning] = reasoning };
+
+//
+// 3. The router. Before each call, the selector sends the conversation to the decision client and forwards the call to
+// the chat client of the chosen route. The decision returns the whole distribution, so the route's certainty is
+// visible, and the application could, for example, prefer the reasoning model when the choice is close.
+using IDecisionClient jev = new JevDecisionClient(new ApiKeyCredential(typeSafeApiKey));
+using RoutingChatClient router = RoutingChatClient.Create(async (context, cancellationToken) =>
+{
+ var state = new RoutingState([.. context.Messages.Select(message => new RoutingMessage(message.Role.Value, message.Text))]);
+ DecisionResponse decision = await jev.GetResponseAsync(state, routing, cancellationToken: cancellationToken);
+ IReadOnlyDictionary distribution = decision.GetDistribution(result => result.Route);
+
+ Route route = decision.Result.Route;
+ Console.WriteLine($"Route: {route} (fast {distribution[Route.Fast]:F2}, reasoning {distribution[Route.Reasoning]:F2}), model {(route == Route.Fast ? fastModel : reasoningModel)}");
+ return clients[route];
+});
+//
+
+// 4. The agent. It knows nothing about the routing; every model call goes through the router.
+AIAgent agent = router.AsAIAgent(name: "Assistant", instructions: "You are a helpful assistant. Answer in at most three sentences.");
+
+string[] requests =
+[
+ "What is the capital of France?",
+ "We are launching a product with no sales history. Compare three ways to forecast its first-year demand, and recommend one with its main risk.",
+];
+
+foreach (string request in requests)
+{
+ Console.WriteLine($"User: {request}");
+ AgentResponse response = await agent.RunAsync(request);
+ Console.WriteLine($"Agent: {response.Text}");
+ Console.WriteLine();
+}
+
+/// The routes. Each description tells the decision model when to pick the route.
+internal enum Route
+{
+ [Description("Short, routine requests where a quick answer is enough.")]
+ Fast,
+
+ [Description("Requests that need multi-step analysis, comparisons, or careful planning.")]
+ Reasoning,
+}
+
+#pragma warning disable CA1812 // RouteDecision is created from the answers.
+
+/// The decision: the route of the latest request.
+internal sealed record RouteDecision([Description("Which model should answer the latest user request?")] Route Route);
+
+#pragma warning restore CA1812
+
+/// The state the decision model reads: the conversation, as role and text.
+internal sealed record RoutingState(IReadOnlyList Messages);
+
+/// One message of the conversation.
+internal sealed record RoutingMessage(string Role, string Text);
diff --git a/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/README.md b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/README.md
new file mode 100644
index 00000000000..e06eeeda0ae
--- /dev/null
+++ b/dotnet/samples/02-agents/AgentProviders/typesafe/Agent_TypeSafe_Step03_DecisionRouting/README.md
@@ -0,0 +1,69 @@
+# Routing an agent's requests with a decision model
+
+This sample routes each request of an agent to a fast model or a reasoning model, and a decision model chooses the
+route. It combines `RoutingChatClient` from Microsoft.Extensions.AI with the decision API proposed for
+Microsoft.Extensions.AI ([dotnet/extensions#7795](https://github.com/dotnet/extensions/pull/7795) and
+[#7796](https://github.com/dotnet/extensions/pull/7796)), which `Microsoft.Agents.AI.Abstractions` carries until it ships.
+
+## How it works
+
+The route is a Choice among the values of an enum, whose descriptions say when to pick each one:
+
+```csharp
+internal enum Route
+{
+ [Description("Short, routine requests where a quick answer is enough.")]
+ Fast,
+
+ [Description("Requests that need multi-step analysis, comparisons, or careful planning.")]
+ Reasoning,
+}
+
+DecisionDefinition routing = DecisionDefinition.Create(builder => builder.Choice(decision => decision.Route));
+```
+
+`RoutingChatClient.Create` calls a selector before every model call. The selector sends the conversation to the
+decision client, and returns the chat client of the chosen route:
+
+```csharp
+RoutingChatClient router = RoutingChatClient.Create(async (context, cancellationToken) =>
+{
+ var state = new RoutingState([.. context.Messages.Select(message => new RoutingMessage(message.Role.Value, message.Text))]);
+ DecisionResponse decision = await jev.GetResponseAsync(state, routing, cancellationToken: cancellationToken);
+ return clients[decision.Result.Route];
+});
+
+AIAgent agent = router.AsAIAgent(name: "Assistant", instructions: "...");
+```
+
+The agent knows nothing about the routing. The decision also returns the whole distribution (`GetDistribution`), so
+the application can see how certain the route is, and could, for example, prefer the reasoning model when the choice
+is close.
+
+Each chat client is bound to its own deployment. `RoutingChatClient` forwards the caller's `ChatOptions`, so if your
+agent sets `ChatOptions.ModelId`, make each routed client ignore or reject a model that is not its own.
+
+## Prerequisites
+
+- .NET 10 SDK or later
+- A Microsoft Foundry project with two deployed chat models: a fast one and a reasoning one
+- Azure CLI installed and authenticated (`az login`)
+- A TypeSafe API key
+
+Set the environment variables:
+
+```powershell
+$env:FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
+$env:FOUNDRY_MODEL="gpt-5.4-mini" # Optional fast model, defaults to gpt-5.4-mini
+$env:FOUNDRY_REASONING_MODEL="your-reasoning-model" # Optional, defaults to FOUNDRY_MODEL
+$env:TYPESAFE_API_KEY="your-typesafe-api-key"
+```
+
+## Running the sample
+
+```powershell
+dotnet run
+```
+
+For each request, the sample prints the route with both probabilities and the model that answered, followed by the
+agent's answer. A short factual question goes to the fast model, and a planning question to the reasoning model.
diff --git a/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Agent_Step25_ClassificationWithJev.csproj b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Agent_Step25_ClassificationWithJev.csproj
new file mode 100644
index 00000000000..1c976a48330
--- /dev/null
+++ b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Agent_Step25_ClassificationWithJev.csproj
@@ -0,0 +1,21 @@
+
+
+
+ Exe
+ net10.0
+
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/KeywordClassifier.cs b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/KeywordClassifier.cs
new file mode 100644
index 00000000000..338dd1e7dc6
--- /dev/null
+++ b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/KeywordClassifier.cs
@@ -0,0 +1,60 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+using System.Diagnostics.CodeAnalysis;
+
+///
+/// A local classifier that stands in for another classification client. It has its own request and response types,
+/// knows nothing about Jev, and needs no network: it scores each option by the words it shares with the text.
+///
+[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated by the service provider")]
+internal sealed class KeywordClassifier
+{
+ private static readonly char[] s_separators = [' ', ',', '.', '!', '?', ';', ':', '\'', '"', '(', ')', '-', '\n', '\r', '\t'];
+
+ public Task ClassifyAsync(ClassificationRequest request, CancellationToken cancellationToken)
+ {
+ HashSet words = Words(request.Text);
+ var results = new Dictionary();
+ foreach (ClassificationTask task in request.Tasks)
+ {
+ // One point per shared word, plus one so that every option keeps some probability.
+ double[] points = [.. task.Options.Select(option => Words(option.Description).Count(words.Contains) + 1.0)];
+ double total = points.Sum();
+ results[task.Id] = new ClassificationResult(
+ task.Kind,
+ [.. task.Options.Select((option, index) => new ScoredOption(option.Key, option.Description, points[index] / total))]);
+ }
+
+ return Task.FromResult(new ClassificationResponse(results));
+ }
+
+ // Words are compared in upper case and without a plural "S", so "invoice" matches "invoices".
+ private static HashSet Words(string text) =>
+ [.. text.ToUpperInvariant().Split(s_separators, StringSplitOptions.RemoveEmptyEntries).Where(word => word.Length > 3).Select(word => word.TrimEnd('S'))];
+}
+
+/// What the classifier decides for one task.
+internal enum ClassificationKind
+{
+ PickOne,
+ Rate,
+ YesNo,
+}
+
+/// The classifier's request: the text and the tasks to decide about it.
+internal sealed record ClassificationRequest(string Text, IReadOnlyList Tasks);
+
+/// One task: pick one option, rate on ordered options, or decide yes or no.
+internal sealed record ClassificationTask(string Id, ClassificationKind Kind, IReadOnlyList Options);
+
+/// An option of a task and the words that describe it.
+internal sealed record ClassificationOption(string Key, string Description);
+
+/// The classifier's response: one result per task, by task ID.
+internal sealed record ClassificationResponse(IReadOnlyDictionary Results);
+
+/// The result of one task: every option with its probability.
+internal sealed record ClassificationResult(ClassificationKind Kind, IReadOnlyList Options);
+
+/// An option with the probability that the classifier gives it.
+internal sealed record ScoredOption(string Key, string Description, double Probability);
diff --git a/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Program.cs b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Program.cs
new file mode 100644
index 00000000000..a228d7573d2
--- /dev/null
+++ b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/Program.cs
@@ -0,0 +1,147 @@
+// Copyright (c) Microsoft. All rights reserved.
+
+// Classification with Jev — Give an agent a fast, calibrated classifier as a tool
+//
+// Jev, the TypeSafe System One model, does not write text: it answers typed questions
+// (choice, score, noul) about a state and returns calibrated probabilities. This sample gives
+// a support agent a Jev tool built with JevAIToolBuilder. The agent's model decides which
+// questions to ask, Jev answers them, and the model writes the routing decision, sending
+// uncertain tickets to a human. The second part answers the same tool with another client.
+
+using System.ClientModel;
+using System.Globalization;
+using Azure.AI.Projects;
+using Azure.Identity;
+using Microsoft.Agents.AI;
+using Microsoft.Agents.AI.TypeSafe;
+using Microsoft.Extensions.AI;
+using Microsoft.Extensions.DependencyInjection;
+
+var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
+var deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
+var typeSafeApiKey = Environment.GetEnvironmentVariable("TYPESAFE_API_KEY") ?? throw new InvalidOperationException("TYPESAFE_API_KEY is not set.");
+
+//
+// The tool's arguments are a Jev request (the state plus typed questions) and its result is the Jev response.
+AIFunction jev = new JevAIToolBuilder(new ApiKeyCredential(typeSafeApiKey)).Build();
+//
+
+const string Instructions = """
+ You triage customer support tickets. For every ticket, call ask_system_one once with the ticket text as the
+ state and these questions:
+ - "department": a choice between billing (payments, invoices, refunds), technical (bugs, outages, integrations),
+ and sales (pricing, upgrades, new accounts).
+ - "urgent": a noul asking whether the customer needs help urgently.
+ - "frustration": a score with the rubric calm, annoyed, and angry.
+ Then reply in one line with the department, whether it is urgent, and the frustration level. When the department
+ confidence is below 0.6, say the ticket needs human review instead of naming a department.
+ """;
+
+// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
+// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
+// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
+var projectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());
+AIAgent agent = projectClient.AsAIAgent(model: deploymentName, instructions: Instructions, name: "TicketTriage", tools: [jev]);
+
+string[] tickets =
+[
+ "I've been trying to connect my Stripe account for 3 days and the integration keeps failing. I'm losing sales. Please help ASAP.",
+ "Hi, could you send me a copy of last month's invoice when you get a chance? Thanks!",
+ "I'd like to talk to someone about my account.",
+];
+
+foreach (string ticket in tickets)
+{
+ await TriageAsync(agent, ticket);
+}
+
+//
+// The same tool can be answered by another client. UseClient takes the client's operation and two mappers: one from
+// the JevRequest that the model writes to the client's request, and one from the client's response to a JevResult.
+// The tool resolves the client from the agent's services, in a new scope on every call, and checks the mapped result
+// against the request before the model sees it.
+AIFunction localJev = new JevAIToolBuilder()
+ .UseClient(
+ (classifier, request, cancellationToken) => classifier.ClassifyAsync(request, cancellationToken),
+ inputMapper: ToClassificationRequest,
+ outputMapper: ToJevResult)
+ .Build();
+
+using ServiceProvider services = new ServiceCollection()
+ .AddSingleton()
+ .BuildServiceProvider();
+AIAgent localAgent = projectClient.AsAIAgent(
+ model: deploymentName,
+ instructions: Instructions,
+ name: "LocalTicketTriage",
+ tools: [localJev],
+ services: services);
+//
+
+Console.WriteLine("The same tool, answered by a local keyword classifier:");
+Console.WriteLine();
+await TriageAsync(localAgent, tickets[1]);
+
+static async Task TriageAsync(AIAgent agent, string ticket)
+{
+ AgentResponse response = await agent.RunAsync(ticket);
+
+ Console.WriteLine($"Ticket: {ticket}");
+ foreach (FunctionResultContent result in response.Messages.SelectMany(static m => m.Contents).OfType())
+ {
+ Console.WriteLine($"Tool result: {result.Result}");
+ }
+
+ Console.WriteLine($"Agent: {response.Text}");
+ Console.WriteLine();
+}
+
+//
+// Converts each Jev question into a classifier task. The options carry the words the classifier matches.
+static ClassificationRequest ToClassificationRequest(JevRequest request) =>
+ new(
+ request.State.ToString(),
+ [.. request.Questions.Select(question => question.Value switch
+ {
+ JevChoiceQuestion choice => new ClassificationTask(
+ question.Key,
+ ClassificationKind.PickOne,
+ [.. choice.Criteria.Select(criterion => new ClassificationOption(criterion.Key, $"{criterion.Key} {criterion.Value}"))]),
+ JevScoreQuestion score => new ClassificationTask(
+ question.Key,
+ ClassificationKind.Rate,
+ [.. score.Criteria.Select((level, index) => new ClassificationOption(index.ToString(CultureInfo.InvariantCulture), level.ToString()))]),
+ JevNoulQuestion noul => new ClassificationTask(
+ question.Key,
+ ClassificationKind.YesNo,
+ [new ClassificationOption("yes", $"{noul.Instructions} {noul.Criteria?.True}"), new ClassificationOption("no", $"{noul.Criteria?.False}")]),
+ _ => throw new NotSupportedException($"Question '{question.Key}' has an unknown type."),
+ })]);
+
+// Converts each classifier result back into the Jev answer of the same kind.
+static JevResult ToJevResult(ClassificationResponse response) => new()
+{
+ Model = "local-keyword-classifier",
+ Answers = response.Results.ToDictionary(result => result.Key, result => ToJevResponse(result.Value)),
+ Usage = new JevUsage { InputTokens = 0, OutputTokens = 0 },
+};
+
+static JevResponse ToJevResponse(ClassificationResult result)
+{
+ ScoredOption best = result.Options.MaxBy(option => option.Probability)!;
+ Dictionary probabilities = result.Options.ToDictionary(option => option.Key, option => option.Probability);
+ return result.Kind switch
+ {
+ ClassificationKind.PickOne => new JevChoiceResponse { Choice = best.Key, Confidence = best.Probability, Probabilities = probabilities },
+ ClassificationKind.Rate => new JevScoreResponse
+ {
+ // Like Jev, the score is the expected value over the rubric, so it can fall between levels.
+ Score = result.Options.Sum(option => int.Parse(option.Key, CultureInfo.InvariantCulture) * option.Probability),
+ Confidence = best.Probability,
+ Legend = result.Options.ToDictionary(option => option.Key, option => (JevEntry)option.Description),
+ Probabilities = probabilities,
+ },
+ _ => new JevNoulResponse { Noul = probabilities["yes"] },
+ };
+}
+//
diff --git a/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/README.md b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/README.md
new file mode 100644
index 00000000000..f088f05d5df
--- /dev/null
+++ b/dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev/README.md
@@ -0,0 +1,129 @@
+# Classification with Jev
+
+This sample gives an agent a classifier tool built with `JevAIToolBuilder` from `Microsoft.Agents.AI.TypeSafe`.
+
+Jev, the TypeSafe System One model, does not write text. It answers typed questions about a state and returns
+calibrated probabilities. An agent's model writes the replies; Jev makes the fast, structured decisions:
+
+1. The agent's model calls `ask_system_one` with a Jev request: the `state` and the `questions` to
+ answer about it.
+2. Jev answers each question:
+
+ | Question type | What it answers | Answer |
+ | --- | --- | --- |
+ | `choice` | Which of these named alternatives? | The selected label, the probability of each label, and a confidence |
+ | `score` | Which score on an ordered rubric (2 to 10 entries)? | An expected score that can fall between rubric entries, the probability of each score, and a confidence |
+ | `noul` | Yes or no? | The probability, from 0 to 1, of yes |
+
+ The state, the instructions, and every criterion can be text or JSON, like `EntryType` in the official TypeSafe SDK
+ ([`@typesafe-ai/sdk`](https://github.com/typesafe-ai/typesafe-sdk-js)). The Jev contract types mirror the SDK's type
+ names: `JevRequest`, `JevChoiceQuestion`, `JevResult`, `JevChoiceResponse`, and so on.
+
+3. The model reads the answers and writes the reply. Here it routes each support ticket and sends uncertain tickets to
+ human review.
+4. The same tool is answered by a local keyword classifier instead of the TypeSafe API, through `UseClient` and the
+ agent's services (see [Using another client](#using-another-client)).
+
+When the application, rather than the model, decides the questions, give the agent a
+`DecisionDefinition.AsAIFunction` tool over `JevDecisionClient` instead, as in
+[Decision tool](../../AgentProviders/typesafe/Agent_TypeSafe_Step02_DecisionTool/).
+
+## Configuring the client
+
+`JevAIToolBuilder` hides the HTTP client. The API key is an `ApiKeyCredential`, and `JevAIToolOptions` follows the
+`ClientPipelineOptions` pattern of the OpenAI and Azure AI client libraries:
+
+```csharp
+var options = new JevAIToolOptions
+{
+ ModelId = "jev-latest", // default
+ Transport = new HttpClientPipelineTransport(httpClient), // for example from IHttpClientFactory
+ NetworkTimeout = TimeSpan.FromSeconds(30),
+};
+options.AddPolicy(myPolicy, PipelinePosition.PerCall); // custom pipeline policies
+
+AIFunction jev = new JevAIToolBuilder(new ApiKeyCredential(apiKey), options).Build();
+```
+
+Unset pipeline settings get the defaults of the official SDK: two retries on 408, 429, and 5xx responses (529 means
+overloaded), honoring `retry-after-ms` or `Retry-After` up to one minute and otherwise backing off from half a second
+to five seconds, and a 10-second timeout per attempt. `Name` and `Description` set what the agent's model sees.
+
+## Using another client
+
+Any other client can answer the requests instead of the TypeSafe API. The second part of the sample shows it with
+`KeywordClassifier`, a local classifier in [KeywordClassifier.cs](./KeywordClassifier.cs) that has its own request and
+response types, knows nothing about Jev, and needs no network. `UseClient` takes the client's operation and two
+mappers between the Jev types and the client's types:
+
+```csharp
+AIFunction localJev = new JevAIToolBuilder()
+ .UseClient(
+ (classifier, request, cancellationToken) => classifier.ClassifyAsync(request, cancellationToken),
+ inputMapper: ToClassificationRequest,
+ outputMapper: ToJevResult)
+ .Build();
+```
+
+`ToClassificationRequest` turns each Jev question into a classifier task, and `ToJevResult` turns each classifier
+result back into the Jev answer of the same kind (see the `mappers` region of [Program.cs](./Program.cs)). The tool
+checks the mapped result before the model sees it: every question needs an answer of the same type, and a `choice`
+answer and its probabilities may only use the labels the question offered. The output mapper receives only the
+client's response, so the client's result says which kind of answer it is.
+
+The keyword classifier is far less certain than Jev, so for the same invoice ticket the agent's confidence rule
+usually sends it to human review. Use `UseMapping` instead of `UseClient` for a mapping that is a single delegate from
+a `JevRequest` to a `JevResult`.
+
+## Dependency injection
+
+Every mapping receives the `IServiceProvider` of the agent that calls the tool. `FunctionInvokingChatClient` passes
+it in `AIFunctionArguments.Services`, from the services the agent was created with. `UseClient` resolves
+the client from a new scope on every call and disposes the scope afterwards, so scoped and disposable clients work
+even though hosted agents are singletons that receive the root provider. The sample registers the classifier in a
+`ServiceCollection` and passes the provider to the agent:
+
+```csharp
+using ServiceProvider services = new ServiceCollection()
+ .AddSingleton()
+ .BuildServiceProvider();
+AIAgent localAgent = projectClient.AsAIAgent(model: deploymentName, instructions: Instructions, tools: [localJev], services: services);
+```
+
+In a host, register the client and build the tool in the agent's tool factory:
+
+```csharp
+builder.Services.AddScoped();
+builder.Services.AddAIAgent("triage", Instructions)
+ .WithAITool(sp => new JevAIToolBuilder()
+ .UseClient(
+ (classifier, request, cancellationToken) => classifier.ClassifyAsync(request, cancellationToken),
+ inputMapper: ToClassificationRequest,
+ outputMapper: ToJevResult)
+ .Build());
+```
+
+With the TypeSafe API, build the tool in the same `WithAITool` factory and take the credential and the transport from
+the container or configuration.
+
+## Prerequisites
+
+- .NET 10 SDK or later
+- A Microsoft Foundry project with a model deployment
+- Azure CLI installed and authenticated (for Azure credential authentication)
+- A TypeSafe API key (see the [TypeSafe quickstart](https://docs.typesafe.ai/introduction/quickstart))
+
+Set the following environment variables:
+
+```powershell
+$env:FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Foundry project endpoint
+$env:FOUNDRY_MODEL="gpt-5.4-mini" # Optional, defaults to gpt-5.4-mini
+$env:TYPESAFE_API_KEY=""
+```
+
+## Run the sample
+
+```powershell
+cd dotnet/samples/02-agents/Agents/Agent_Step25_ClassificationWithJev
+dotnet run
+```
diff --git a/dotnet/samples/02-agents/Agents/README.md b/dotnet/samples/02-agents/Agents/README.md
index 487e7f269a2..356cf1116bf 100644
--- a/dotnet/samples/02-agents/Agents/README.md
+++ b/dotnet/samples/02-agents/Agents/README.md
@@ -51,6 +51,7 @@ Before you begin, ensure you have the following prerequisites:
|[Switching agent operating mode](./Agent_Step22_AgentMode/)|This sample demonstrates how to use the AgentModeProvider to track and switch an agent's operating mode at runtime, including the built-in plan/execute modes and custom modes, with a simple input loop that switches mode using a slash command.|
|[Tracking work with a todo list](./Agent_Step23_TodoList/)|This sample demonstrates how to use the TodoProvider to let an agent plan and track multi-step work using a todo list that persists across turns, printing the evolving todo list after each turn.|
|[Routing turns across multiple models](./Agent_Step24_MultiModelRouting/)|This sample demonstrates how to use the RoutePersistingRoutingChatClient to route each agent turn to one of several named chat clients, switching the active model mid-conversation while preserving the conversation history.|
+|[Classification with Jev](./Agent_Step25_ClassificationWithJev/)|This sample demonstrates how to give an agent a Jev tool built with JevAIToolBuilder, so the agent's model asks Jev typed choice, score, and noul questions and uses the calibrated answers to route support tickets.|
## Running the samples from the console
diff --git a/dotnet/samples/AGENTS.md b/dotnet/samples/AGENTS.md
index 7c56735e4c7..7b395cd6f2b 100644
--- a/dotnet/samples/AGENTS.md
+++ b/dotnet/samples/AGENTS.md
@@ -26,7 +26,8 @@ dotnet/samples/
│ │ ├── google-gemini/ # Google Gemini provider sample
│ │ ├── ollama/ # Ollama provider sample
│ │ ├── onnx/ # ONNX Runtime provider sample
-│ │ └── openai/ # OpenAI provider samples
+│ │ ├── openai/ # OpenAI provider samples
+│ │ └── typesafe/ # TypeSafe (Jev) decision API samples
│ ├── AgentOpenTelemetry/ # OpenTelemetry integration
│ ├── AgentSkills/ # Agent skills patterns
│ ├── AgentWithMemory/ # Memory providers (chat history, Mem0, Valkey, Foundry, AgentMemory)
diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/.editorconfig b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/.editorconfig
new file mode 100644
index 00000000000..3fde50f62c5
--- /dev/null
+++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/.editorconfig
@@ -0,0 +1,22 @@
+# These files are a verbatim copy of the decision API proposed for Microsoft.Extensions.AI. The rules below keep them
+# compiling unchanged, so the copy can be diffed against the upstream source and deleted when Microsoft.Extensions.AI
+# ships the API. See README.md.
+
+[*.cs]
+# The upstream code uses the upstream style and file header.
+dotnet_style_qualification_for_field = false:none
+dotnet_style_qualification_for_property = false:none
+dotnet_style_qualification_for_method = false:none
+dotnet_style_qualification_for_event = false:none
+dotnet_diagnostic.IDE0001.severity = none
+dotnet_diagnostic.IDE0009.severity = none
+dotnet_diagnostic.IDE0073.severity = none
+dotnet_diagnostic.RCS1146.severity = none
+dotnet_diagnostic.RCS1173.severity = none
+
+# Upstream marks every public type experimental, and the internal helper types that use them do not repeat the attribute.
+dotnet_diagnostic.MEAI001.severity = none
+
+# The overload shapes are the upstream API, which the MEAI API review owns.
+dotnet_diagnostic.RS0026.severity = none
+dotnet_diagnostic.RS0027.severity = none
diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionAnswers.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionAnswers.cs
new file mode 100644
index 00000000000..f4227f9b199
--- /dev/null
+++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionAnswers.cs
@@ -0,0 +1,404 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#pragma warning disable SA1402 // File may only contain a single type — decision answer types are co-located as one immutable model.
+#pragma warning disable SA1649 // File name should match first type name — decision answer types are co-located as one immutable model.
+#pragma warning disable CA1032 // Implement standard exception constructors — protocol exceptions expose the protocol-specific constructors.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text.Json.Serialization;
+using Microsoft.Shared.DiagnosticIds;
+using Microsoft.Shared.Diagnostics;
+
+namespace Microsoft.Extensions.AI;
+
+/// Identifies the precision represented by provider-reported probabilities.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public enum DecisionPrecision
+{
+ /// The provider reports values without a declared decimal rounding.
+ HighPrecision,
+
+ /// The provider reports values rounded to four decimal places.
+ FourDecimalPlaces,
+
+ /// The provider reports values rounded to two decimal places.
+ TwoDecimalPlaces,
+}
+
+/// Represents one named probability observation.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionProbability
+{
+ /// Initializes a new instance of the class.
+ /// The exact opaque candidate or level ID.
+ /// The probability value.
+ [JsonConstructor]
+ public DecisionProbability(string id, double value)
+ {
+ Id = Throw.IfNullOrWhitespace(id);
+ Value = value;
+ }
+
+ /// Gets the exact opaque candidate or level ID.
+ public string Id { get; }
+
+ /// Gets the native double probability value.
+ public double Value { get; }
+}
+
+/// Represents a provider result for one decision question.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
+[JsonDerivedType(typeof(BinaryDecisionAnswer), "binary")]
+[JsonDerivedType(typeof(ChoiceDecisionAnswer), "choice")]
+[JsonDerivedType(typeof(ScoreDecisionAnswer), "score")]
+public abstract class DecisionAnswer
+{
+ internal const double DistributionTolerance = 1e-6;
+
+ private protected DecisionAnswer(
+ string questionId,
+ DecisionKind kind,
+ DecisionPrecision precision,
+ object? rawRepresentation,
+ IReadOnlyDictionary? additionalProperties)
+ {
+ QuestionId = Throw.IfNullOrWhitespace(questionId);
+ if (!Enum.IsDefined(typeof(DecisionPrecision), precision))
+ {
+ Throw.ArgumentOutOfRangeException(nameof(precision));
+ }
+
+ Kind = kind;
+ Precision = precision;
+ RawRepresentation = rawRepresentation;
+ AdditionalProperties = DecisionSnapshots.Properties(additionalProperties);
+ }
+
+ /// Gets the exact opaque question ID this answer belongs to.
+ public string QuestionId { get; }
+
+ /// Gets the semantic kind of this answer.
+ public DecisionKind Kind { get; }
+
+ /// Gets the precision declared for the numeric observations.
+ public DecisionPrecision Precision { get; }
+
+ ///
+ /// Gets the provider-owned raw representation, if available.
+ /// This value is not cloned or used for semantic data and must be treated as diagnostic-only.
+ ///
+ [JsonIgnore]
+ public object? RawRepresentation { get; }
+
+ ///
+ /// Gets an owned read-only snapshot of provider extension data.
+ /// Values are shallow-copied references and must be independently safe to share.
+ ///
+ public IReadOnlyDictionary? AdditionalProperties { get; }
+
+ internal static void ValidateProbability(double value)
+ {
+ if (double.IsNaN(value) || double.IsInfinity(value) || value < 0 || value > 1)
+ {
+ throw new DecisionProtocolException("Probability must be finite and in the range [0, 1].");
+ }
+ }
+
+ internal static void ValidateDistribution(
+ IReadOnlyList probabilities,
+ DecisionPrecision precision)
+ {
+ double sum = 0;
+ HashSet ids = new(StringComparer.Ordinal);
+
+ foreach (DecisionProbability probability in probabilities)
+ {
+ if (probability is null)
+ {
+ throw new DecisionProtocolException("A probability distribution cannot contain null entries.");
+ }
+
+ if (!ids.Add(probability.Id))
+ {
+ throw new DecisionProtocolException("A probability distribution contains a duplicate ID.");
+ }
+
+ ValidateProbability(probability.Value);
+ sum += probability.Value;
+ }
+
+ double tolerance = GetDistributionTolerance(precision, probabilities.Count);
+ if (Math.Abs(sum - 1) > tolerance)
+ {
+ throw new DecisionProtocolException(
+ "A probability distribution must sum to 1 within the bound allowed by its declared rounding.");
+ }
+
+ double roundingHalfUnit = GetRoundingHalfUnit(precision);
+ double lowerBound = 0;
+ double upperBound = 0;
+ foreach (DecisionProbability probability in probabilities)
+ {
+ lowerBound += Math.Max(0, probability.Value - roundingHalfUnit);
+ upperBound += Math.Min(1, probability.Value + roundingHalfUnit);
+ }
+
+ if (lowerBound > 1 + DistributionTolerance || upperBound < 1 - DistributionTolerance)
+ {
+ throw new DecisionProtocolException(
+ "A probability distribution has no normalized latent values consistent with its declared rounding.");
+ }
+ }
+
+ internal static double GetDistributionTolerance(DecisionPrecision precision, int count)
+ {
+ return precision switch
+ {
+ DecisionPrecision.HighPrecision => DistributionTolerance,
+ DecisionPrecision.FourDecimalPlaces => (count * 0.00005) + DistributionTolerance,
+ DecisionPrecision.TwoDecimalPlaces => (count * 0.005) + DistributionTolerance,
+ _ => throw new ArgumentOutOfRangeException(nameof(precision)),
+ };
+ }
+
+ internal static (double Minimum, double Maximum) GetFeasibleExpectedScoreBounds(
+ IReadOnlyList probabilities,
+ DecisionPrecision precision)
+ {
+ double roundingHalfUnit = GetRoundingHalfUnit(precision);
+ double lowerMass = 0;
+ double upperMass = 0;
+ for (int i = 0; i < probabilities.Count; i++)
+ {
+ double probability = probabilities[i].Value;
+ lowerMass += Math.Max(0, probability - roundingHalfUnit);
+ upperMass += Math.Min(1, probability + roundingHalfUnit);
+ }
+
+ if (lowerMass > 1 + DistributionTolerance || upperMass < 1 - DistributionTolerance)
+ {
+ throw new DecisionProtocolException(
+ "A probability distribution has no normalized latent values consistent with its declared rounding.");
+ }
+
+ double remaining = Math.Max(0, 1 - lowerMass);
+ double minimum = 0;
+ for (int i = 0; i < probabilities.Count; i++)
+ {
+ double lower = Math.Max(0, probabilities[i].Value - roundingHalfUnit);
+ double capacity = Math.Min(1, probabilities[i].Value + roundingHalfUnit) - lower;
+ double allocated = Math.Min(remaining, capacity);
+ minimum += (lower + allocated) * i;
+ remaining -= allocated;
+ }
+
+ remaining = Math.Max(0, 1 - lowerMass);
+ double maximum = 0;
+ double[] lowerValues = new double[probabilities.Count];
+ for (int i = 0; i < probabilities.Count; i++)
+ {
+ lowerValues[i] = Math.Max(0, probabilities[i].Value - roundingHalfUnit);
+ maximum += lowerValues[i] * i;
+ }
+
+ for (int i = probabilities.Count - 1; i >= 0; i--)
+ {
+ double capacity = Math.Min(1, probabilities[i].Value + roundingHalfUnit) - lowerValues[i];
+ double allocated = Math.Min(remaining, capacity);
+ maximum += allocated * i;
+ remaining -= allocated;
+ }
+
+ if (remaining > DistributionTolerance)
+ {
+ throw new DecisionProtocolException(
+ "A probability distribution has no normalized latent values consistent with its declared rounding.");
+ }
+
+ return (minimum, maximum);
+ }
+
+ internal static double GetRoundingHalfUnit(DecisionPrecision precision) =>
+ precision switch
+ {
+ DecisionPrecision.HighPrecision => 0,
+ DecisionPrecision.FourDecimalPlaces => 0.00005,
+ DecisionPrecision.TwoDecimalPlaces => 0.005,
+ _ => throw new ArgumentOutOfRangeException(nameof(precision)),
+ };
+}
+
+/// Represents the probability that a binary proposition is true.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class BinaryDecisionAnswer : DecisionAnswer
+{
+ /// Initializes a new instance of the class.
+ [JsonConstructor]
+ public BinaryDecisionAnswer(
+ string questionId,
+ double trueProbability,
+ DecisionPrecision precision = DecisionPrecision.HighPrecision,
+ object? rawRepresentation = null,
+ IReadOnlyDictionary? additionalProperties = null)
+ : base(questionId, DecisionKind.Binary, precision, rawRepresentation, additionalProperties)
+ {
+ ValidateProbability(trueProbability);
+ TrueProbability = trueProbability;
+ }
+
+ /// Gets the probability that the proposition is true.
+ public double TrueProbability { get; }
+}
+
+/// Represents a selected candidate and its complete probability distribution.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class ChoiceDecisionAnswer : DecisionAnswer
+{
+ /// Initializes a new instance of the class.
+ [JsonConstructor]
+ public ChoiceDecisionAnswer(
+ string questionId,
+ string selectedCandidateId,
+ IReadOnlyList probabilities,
+ DecisionPrecision precision = DecisionPrecision.HighPrecision,
+ object? rawRepresentation = null,
+ IReadOnlyDictionary? additionalProperties = null)
+ : base(questionId, DecisionKind.Choice, precision, rawRepresentation, additionalProperties)
+ {
+ SelectedCandidateId = Throw.IfNullOrWhitespace(selectedCandidateId);
+ _ = Throw.IfNull(probabilities);
+
+ DecisionProbability[] copy = probabilities.ToArray();
+ if (copy.Length == 0)
+ {
+ throw new DecisionProtocolException("A choice answer requires a complete distribution.");
+ }
+
+ ValidateDistribution(copy, precision);
+ if (!Array.Exists(copy, probability => string.Equals(probability.Id, SelectedCandidateId, StringComparison.Ordinal)))
+ {
+ throw new DecisionProtocolException("The selected candidate is not present in the distribution.");
+ }
+
+ Probabilities = Array.AsReadOnly(copy);
+ }
+
+ /// Gets the exact selected candidate ID.
+ public string SelectedCandidateId { get; }
+
+ /// Gets the complete ordered candidate distribution.
+ public IReadOnlyList Probabilities { get; }
+}
+
+///
+/// Represents an ordinal score and its complete level distribution.
+/// A reported score is checked against normalized latent values within the declared clipped rounding intervals; observed probabilities and the derived expectation are never repaired.
+///
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class ScoreDecisionAnswer : DecisionAnswer
+{
+ /// Initializes a new instance of the class.
+ [JsonConstructor]
+ public ScoreDecisionAnswer(
+ string questionId,
+ double? score,
+ IReadOnlyList probabilities,
+ DecisionPrecision precision = DecisionPrecision.HighPrecision,
+ object? rawRepresentation = null,
+ IReadOnlyDictionary? additionalProperties = null)
+ : base(questionId, DecisionKind.Score, precision, rawRepresentation, additionalProperties)
+ {
+ _ = Throw.IfNull(probabilities);
+
+ DecisionProbability[] copy = probabilities.ToArray();
+ if (copy.Length < 2)
+ {
+ throw new DecisionProtocolException("A score answer requires at least two levels.");
+ }
+
+ ValidateDistribution(copy, precision);
+ if (score is double reportedScore &&
+ (double.IsNaN(reportedScore) || double.IsInfinity(reportedScore) || reportedScore < 0 || reportedScore > copy.Length - 1))
+ {
+ throw new DecisionProtocolException("A score must be finite and within the ordinal level range.");
+ }
+
+ double expectedScore = copy.Select((probability, index) => probability.Value * index).Sum();
+ if (score is double nativeScore)
+ {
+ (double minimum, double maximum) = GetFeasibleExpectedScoreBounds(copy, precision);
+ double scalarHalfUnit = GetRoundingHalfUnit(precision);
+ if (nativeScore + scalarHalfUnit + DistributionTolerance < minimum ||
+ nativeScore - scalarHalfUnit - DistributionTolerance > maximum)
+ {
+ throw new DecisionProtocolException("The score does not agree with its probability distribution.");
+ }
+ }
+
+ Score = score;
+ ExpectedScore = expectedScore;
+ Probabilities = Array.AsReadOnly(copy);
+ }
+
+ /// Gets the provider-reported score, retaining any declared rounding, or when it was not reported.
+ public double? Score { get; }
+
+ /// Gets the score derived from the observed distribution without repairing it, which may fall outside the ordinal level bounds after rounding.
+ public double ExpectedScore { get; }
+
+ /// Gets the complete ordered level distribution.
+ public IReadOnlyList Probabilities { get; }
+}
+
+/// Represents a protocol-invalid provider result.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionProtocolException : Exception
+{
+ /// Initializes a new instance of the class.
+ public DecisionProtocolException()
+ {
+ }
+
+ /// Initializes a new instance of the class with a message.
+ public DecisionProtocolException(string message)
+ : base(message)
+ {
+ }
+
+ /// Initializes a new instance of the class with a message and inner exception.
+ public DecisionProtocolException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+}
+
+internal static class DecisionSnapshots
+{
+ internal static IReadOnlyDictionary? Properties(
+ IReadOnlyDictionary? entries)
+ {
+ if (entries is null)
+ {
+ return null;
+ }
+
+ Dictionary copy = new(StringComparer.Ordinal);
+ foreach (KeyValuePair property in entries)
+ {
+ if (copy.ContainsKey(property.Key))
+ {
+ Throw.ArgumentException(nameof(entries), "Extension property names must be unique.");
+ }
+
+ copy.Add(property.Key, property.Value);
+ }
+
+ return new ReadOnlyDictionary(copy);
+ }
+}
diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionBinding.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionBinding.cs
new file mode 100644
index 00000000000..8c40cd2244d
--- /dev/null
+++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionBinding.cs
@@ -0,0 +1,191 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#pragma warning disable SA1402 // File may only contain a single type — binding proof types are co-located as one API surface.
+#pragma warning disable SA1649 // File name should match first type name — binding proof types are co-located as one API surface.
+#pragma warning disable SA1204 // Static extension type is intentionally grouped with the binding types.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text.Json.Serialization.Metadata;
+using Microsoft.Shared.DiagnosticIds;
+using Microsoft.Shared.Diagnostics;
+
+namespace Microsoft.Extensions.AI;
+
+/// Provides an explicit mapping from a choice candidate ID to an enum value.
+/// The application-owned enum type.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionEnumDefinition
+ where TEnum : struct, Enum
+{
+ private readonly ReadOnlyDictionary _values;
+
+ /// Initializes a new instance of the class.
+ public DecisionEnumDefinition(IEnumerable> values)
+ {
+ _ = Throw.IfNull(values);
+
+ DecisionEnumValue[] copy = values.ToArray();
+ if (copy.Length == 0)
+ {
+ Throw.ArgumentException(nameof(values), "An enum definition requires at least one value.");
+ }
+
+ Dictionary byId = new(StringComparer.Ordinal);
+ HashSet enumValues = new();
+ DecisionCandidate[] candidates = new DecisionCandidate[copy.Length];
+
+ for (int i = 0; i < copy.Length; i++)
+ {
+ DecisionEnumValue value = copy[i];
+ if (!enumValues.Add(value.Value))
+ {
+ Throw.ArgumentException(nameof(values), "Enum aliases or duplicate enum values are not allowed.");
+ }
+
+ if (byId.ContainsKey(value.Id))
+ {
+ Throw.ArgumentException(
+ nameof(values),
+ "Enum candidate IDs must be unique using ordinal comparison.");
+ }
+
+ byId.Add(value.Id, value.Value);
+ candidates[i] = new DecisionCandidate(value.Id, value.Description);
+ }
+
+ _values = new ReadOnlyDictionary(byId);
+ Candidates = Array.AsReadOnly(candidates);
+ }
+
+ /// Gets the ordered candidate snapshot for a choice question.
+ public IReadOnlyList Candidates { get; }
+
+ /// Creates a choice question using this exact enum mapping.
+ /// The choice question with the exact mapped candidate IDs.
+ public ChoiceDecisionQuestion CreateQuestion(string id, string? instructions) =>
+ new(id, instructions, Candidates);
+
+ /// Maps an exact selected candidate ID to its enum value.
+ /// The mapped enum value.
+ public TEnum Parse(string candidateId)
+ {
+ _ = Throw.IfNullOrWhitespace(candidateId);
+ if (_values.TryGetValue(candidateId, out TEnum value))
+ {
+ return value;
+ }
+
+ throw new DecisionProtocolException($"Unknown candidate ID '{candidateId}'.");
+ }
+}
+
+/// Describes one enum mapping entry.
+/// The application-owned enum type.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionEnumValue
+ where TEnum : struct, Enum
+{
+ /// Initializes a new instance of the class.
+ public DecisionEnumValue(TEnum value, string id, string description)
+ {
+ Value = value;
+ Id = Throw.IfNullOrWhitespace(id);
+ Description = Throw.IfNullOrWhitespace(description);
+ }
+
+ /// Gets the application enum value.
+ public TEnum Value { get; }
+
+ /// Gets the exact candidate ID.
+ public string Id { get; }
+
+ /// Gets the candidate description.
+ public string Description { get; }
+}
+
+/// Provides typed access to a complete decision response.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionAnswerSet
+{
+ internal DecisionAnswerSet(DecisionResponse response)
+ {
+ Response = response;
+ }
+
+ /// Gets the complete unmodified response, including probability evidence.
+ public DecisionResponse Response { get; }
+
+ /// Gets a binary answer by exact question ID.
+ /// The complete binary answer.
+ public BinaryDecisionAnswer GetBinary(string questionId) =>
+ Response.GetAnswer(questionId) as BinaryDecisionAnswer ??
+ throw new DecisionProtocolException($"Question '{questionId}' is not binary.");
+
+ /// Gets a choice answer by exact question ID.
+ /// The complete choice answer.
+ public ChoiceDecisionAnswer GetChoice(string questionId) =>
+ Response.GetAnswer(questionId) as ChoiceDecisionAnswer ??
+ throw new DecisionProtocolException($"Question '{questionId}' is not a choice.");
+
+ /// Gets a choice answer and maps its exact selected ID to an enum.
+ /// The application-owned enum type.
+ /// The mapped enum value.
+ public TEnum GetChoice(string questionId, DecisionEnumDefinition definition)
+ where TEnum : struct, Enum
+ {
+ _ = Throw.IfNull(definition);
+ return definition.Parse(GetChoice(questionId).SelectedCandidateId);
+ }
+
+ /// Gets a score answer by exact question ID.
+ /// The complete score answer.
+ public ScoreDecisionAnswer GetScore(string questionId) =>
+ Response.GetAnswer(questionId) as ScoreDecisionAnswer ??
+ throw new DecisionProtocolException($"Question '{questionId}' is not a score.");
+}
+
+/// Maps one complete response to an application-owned result without inference or reflection.
+/// The application-owned result type.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionResultBinding
+{
+ private readonly Func _map;
+
+ /// Initializes a new instance of the class.
+ /// The source-generated JSON contract for the application result.
+ /// The application-owned mapping delegate.
+ public DecisionResultBinding(
+ JsonTypeInfo resultTypeInfo,
+ Func map)
+ {
+ ResultTypeInfo = Throw.IfNull(resultTypeInfo);
+ _map = Throw.IfNull(map);
+ }
+
+ /// Gets the explicit source-generated result contract.
+ public JsonTypeInfo ResultTypeInfo { get; }
+
+ internal TResult Map(DecisionResponse response) => _map(new DecisionAnswerSet(response));
+}
+
+/// Provides response binding extensions.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public static class DecisionBindingExtensions
+{
+ /// Maps a complete response locally using the supplied explicit binding.
+ /// The application-owned result type.
+ /// The application-owned result.
+ public static TResult Bind(
+ this DecisionResponse response,
+ DecisionResultBinding binding)
+ {
+ _ = Throw.IfNull(response);
+ _ = Throw.IfNull(binding);
+ return binding.Map(response);
+ }
+}
diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionClient.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionClient.cs
new file mode 100644
index 00000000000..7777cb682f7
--- /dev/null
+++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionClient.cs
@@ -0,0 +1,546 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#pragma warning disable SA1402 // File may only contain a single type — decision client contracts are co-located as one API surface.
+#pragma warning disable SA1649 // File name should match first type name — decision client contracts are co-located as one API surface.
+#pragma warning disable SA1204 // Static extension types are intentionally grouped with the client contracts.
+#pragma warning disable S1128 // Unused "using" should be removed — ExperimentalAttribute is supplied by the shared API contract.
+#pragma warning disable S2302 // Protocol diagnostics intentionally mention the opaque question concept.
+#pragma warning disable CA1032 // Implement standard exception constructors — client exceptions expose the client-specific constructors.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.Json.Serialization.Metadata;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Shared.DiagnosticIds;
+using Microsoft.Shared.Diagnostics;
+
+namespace Microsoft.Extensions.AI;
+
+/// Provides provider-neutral decision inference over a heterogeneous question batch.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public interface IDecisionClient : IDisposable
+{
+ /// Evaluates all questions against the same request state.
+ /// The owned decision request.
+ /// Optional per-request options.
+ /// The cancellation token to monitor.
+ /// A complete, correlated decision response or an exception.
+ Task GetResponseAsync(
+ DecisionRequest request,
+ DecisionOptions? options = null,
+ CancellationToken cancellationToken = default);
+
+ /// Retrieves a provider service for the exact requested type and key.
+ /// The requested provider service, or when unavailable.
+ object? GetService(Type serviceType, object? serviceKey = null);
+}
+
+/// Provides per-request decision options.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public class DecisionOptions
+{
+ /// Initializes a new instance of the class.
+ public DecisionOptions()
+ {
+ }
+
+ /// Initializes a new instance of the class by copying another instance.
+ protected DecisionOptions(DecisionOptions? other)
+ {
+ if (other is null)
+ {
+ return;
+ }
+
+ ModelId = other.ModelId;
+ AdditionalProperties = other.AdditionalProperties?.Clone();
+ RawRepresentationFactory = other.RawRepresentationFactory;
+ }
+
+ /// Gets or sets the requested model ID.
+ public string? ModelId { get; set; }
+
+ /// Gets or sets provider-specific extension properties.
+ public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
+
+ ///
+ /// Gets or sets a callback that creates provider-specific raw options.
+ /// The callback should return a new instance for each invocation; the provider may mutate it.
+ ///
+ [JsonIgnore]
+ public Func? RawRepresentationFactory { get; set; }
+
+ /// Creates a deliberate shallow clone of these options.
+ /// A cloned options instance.
+ public virtual DecisionOptions Clone() => new(this);
+}
+
+/// Provides metadata about an .
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionClientMetadata
+{
+ /// Initializes a new instance of the class.
+ public DecisionClientMetadata(
+ string? providerName = null,
+ Uri? providerUri = null,
+ string? defaultModelId = null,
+ IReadOnlyList? supportedKinds = null)
+ {
+ ProviderName = providerName;
+ ProviderUri = providerUri;
+ DefaultModelId = defaultModelId;
+
+ if (supportedKinds is not null)
+ {
+ DecisionKind[] copy = supportedKinds.Distinct().ToArray();
+ foreach (DecisionKind kind in copy)
+ {
+ if (!Enum.IsDefined(typeof(DecisionKind), kind))
+ {
+ Throw.ArgumentException(nameof(supportedKinds), "Supported kinds must be defined decision kinds.");
+ }
+ }
+
+ SupportedKinds = Array.AsReadOnly(copy);
+ }
+ }
+
+ /// Gets the provider name, when known.
+ public string? ProviderName { get; }
+
+ /// Gets the provider URI, when known.
+ public Uri? ProviderUri { get; }
+
+ /// Gets the default model ID, when known.
+ public string? DefaultModelId { get; }
+
+ /// Gets the owned supported-kind snapshot, or when unknown.
+ public IReadOnlyList? SupportedKinds { get; }
+}
+
+/// Classifies a provider failure without prescribing retry behavior.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionClientException : Exception
+{
+ /// Initializes a new instance of the class.
+ public DecisionClientException()
+ : this(string.Empty, isTransient: false)
+ {
+ }
+
+ /// Initializes a new instance of the class with a message.
+ public DecisionClientException(string message)
+ : this(message, isTransient: false)
+ {
+ }
+
+ /// Initializes a new instance of the class with provider classification.
+ public DecisionClientException(string message, bool isTransient, Exception? innerException = null)
+ : base(message, innerException)
+ {
+ IsTransient = isTransient;
+ }
+
+ /// Initializes a new instance of the class with a message and inner exception.
+ public DecisionClientException(string message, Exception innerException)
+ : this(message, isTransient: false, innerException)
+ {
+ }
+
+ /// Gets a value indicating whether the provider classified the failure as transient.
+ public bool IsTransient { get; }
+}
+
+/// Provides extensions for decision clients.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public static class DecisionClientExtensions
+{
+ /// Gets a typed provider service, or when it is unavailable.
+ /// The provider service type.
+ /// The requested provider service, or when unavailable.
+ public static TService? GetService(this IDecisionClient client, object? serviceKey = null)
+ {
+ _ = Throw.IfNull(client);
+ return client.GetService(typeof(TService), serviceKey) is TService service ? service : default;
+ }
+
+ /// Evaluates typed state using an explicit source-generated JSON contract.
+ /// The application state type.
+ /// A complete, correlated decision response.
+ public static async Task GetResponseAsync(
+ this IDecisionClient client,
+ TState state,
+ JsonTypeInfo stateTypeInfo,
+ IEnumerable questions,
+ DecisionOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ _ = Throw.IfNull(client);
+ _ = Throw.IfNull(stateTypeInfo);
+
+ DecisionRequest request = DecisionRequest.Create(state, stateTypeInfo, questions);
+ DecisionResponse response = await client.GetResponseAsync(request, options, cancellationToken).ConfigureAwait(false);
+ response.ValidateAgainst(request);
+ return response;
+ }
+
+ /// Evaluates a JSON state using a reusable typed decision definition.
+ /// The application-owned result type.
+ /// The decision client.
+ /// The explicit JSON state evaluated by every declared question.
+ /// The immutable typed decision definition.
+ /// Optional per-request options.
+ /// The cancellation token to monitor.
+ /// The typed result and complete neutral evidence.
+ public static async Task> GetResponseAsync(
+ this IDecisionClient client,
+ JsonElement state,
+ DecisionDefinition definition,
+ DecisionOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ _ = Throw.IfNull(client);
+ _ = Throw.IfNull(definition);
+
+ DecisionRequest request = new(state, definition.Questions);
+ DecisionResponse response = await client.GetResponseAsync(
+ request,
+ options,
+ cancellationToken).ConfigureAwait(false);
+ return definition.Bind(response, request);
+ }
+
+ /// Evaluates typed application state using a reusable typed decision definition.
+ /// The application state type.
+ /// The application-owned result type.
+ /// The decision client.
+ /// The application-owned state.
+ /// The immutable typed decision definition.
+ /// Optional per-request options.
+ /// The cancellation token to monitor.
+ /// The typed result and complete neutral evidence.
+ public static Task> GetResponseAsync(
+ this IDecisionClient client,
+ TState state,
+ DecisionDefinition definition,
+ DecisionOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ _ = Throw.IfNull(definition);
+ return GetResponseAsync(
+ client,
+ state,
+ definition,
+ definition.SerializerOptions,
+ options,
+ cancellationToken);
+ }
+
+ /// Evaluates typed application state using explicit source-generated state metadata.
+ /// The application state type.
+ /// The application-owned result type.
+ /// The decision client.
+ /// The application-owned state.
+ /// The JSON contract for .
+ /// The immutable typed decision definition.
+ /// Optional per-request options.
+ /// The cancellation token to monitor.
+ /// The typed result and complete neutral evidence.
+ public static Task> GetResponseAsync(
+ this IDecisionClient client,
+ TState state,
+ JsonTypeInfo stateTypeInfo,
+ DecisionDefinition definition,
+ DecisionOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ _ = Throw.IfNull(stateTypeInfo);
+ return GetResponseAsync(
+ client,
+ state,
+ definition,
+ stateTypeInfo,
+ options,
+ cancellationToken);
+ }
+
+ private static async Task> GetResponseAsync(
+ IDecisionClient client,
+ TState state,
+ DecisionDefinition definition,
+ JsonSerializerOptions serializerOptions,
+ DecisionOptions? options,
+ CancellationToken cancellationToken)
+ {
+ _ = Throw.IfNull(client);
+ _ = Throw.IfNull(definition);
+
+ JsonTypeInfo stateTypeInfo = serializerOptions.GetTypeInfo(typeof(TState));
+ JsonElement stateJson = JsonSerializer.SerializeToElement(state, stateTypeInfo);
+ return await GetResponseAsync(client, stateJson, definition, options, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static async Task> GetResponseAsync(
+ IDecisionClient client,
+ TState state,
+ DecisionDefinition definition,
+ JsonTypeInfo stateTypeInfo,
+ DecisionOptions? options,
+ CancellationToken cancellationToken)
+ {
+ _ = Throw.IfNull(client);
+ _ = Throw.IfNull(definition);
+
+ JsonElement stateJson = JsonSerializer.SerializeToElement(state, stateTypeInfo);
+ return await GetResponseAsync(client, stateJson, definition, options, cancellationToken).ConfigureAwait(false);
+ }
+}
+
+/// Identifies provider/model provenance without inventing missing identity.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionProvenance
+{
+ /// Initializes a new instance of the class.
+ public DecisionProvenance(
+ string? providerName = null,
+ Uri? providerUri = null,
+ string? modelId = null,
+ string? responseId = null,
+ DecisionPrecision? precision = null)
+ {
+ ProviderName = providerName;
+ ProviderUri = providerUri;
+ ModelId = modelId;
+ ResponseId = responseId;
+ Precision = precision;
+ }
+
+ /// Gets the provider name, when reported.
+ public string? ProviderName { get; }
+
+ /// Gets the provider URI, when reported.
+ public Uri? ProviderUri { get; }
+
+ /// Gets the model ID, when reported.
+ public string? ModelId { get; }
+
+ /// Gets the provider response ID, when reported.
+ public string? ResponseId { get; }
+
+ /// Gets the reported probability precision, when available.
+ public DecisionPrecision? Precision { get; }
+}
+
+/// Represents a complete response correlated to one request.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionResponse
+{
+ /// Initializes a new instance of the class and validates it.
+ [JsonConstructor]
+ public DecisionResponse(
+ DecisionRequest request,
+ IReadOnlyList answers,
+ DecisionProvenance? provenance = null,
+ UsageDetails? usage = null,
+ object? rawRepresentation = null,
+ IReadOnlyDictionary? additionalProperties = null)
+ {
+ Request = Throw.IfNull(request);
+ _ = Throw.IfNull(answers);
+
+ DecisionAnswer[] copy = answers.ToArray();
+ if (copy.Length != request.Questions.Count)
+ {
+ throw new DecisionProtocolException("A response must contain one answer for every question.");
+ }
+
+ for (int i = 0; i < copy.Length; i++)
+ {
+ ValidateAnswer(request.Questions[i], copy[i]);
+ }
+
+ Answers = Array.AsReadOnly(copy);
+ Provenance = provenance;
+ Usage = usage;
+ RawRepresentation = rawRepresentation;
+ AdditionalProperties = DecisionSnapshots.Properties(additionalProperties);
+ }
+
+ /// Gets the request snapshot evaluated by the provider.
+ public DecisionRequest Request { get; }
+
+ /// Gets complete answers in the exact request order.
+ public IReadOnlyList Answers { get; }
+
+ /// Gets provider/model provenance, when reported.
+ public DecisionProvenance? Provenance { get; }
+
+ /// Gets usage details reported by the provider.
+ public UsageDetails? Usage { get; }
+
+ ///
+ /// Gets the provider-owned raw response, if available.
+ /// This value is not cloned or used for semantic data and must be treated as diagnostic-only.
+ ///
+ [JsonIgnore]
+ public object? RawRepresentation { get; }
+
+ ///
+ /// Gets an owned read-only snapshot of provider extension data.
+ /// Values are shallow-copied references and must be independently safe to share.
+ ///
+ public IReadOnlyDictionary? AdditionalProperties { get; }
+
+ /// Gets an answer by exact ordinal question ID.
+ /// The answer associated with the exact question ID.
+ public DecisionAnswer GetAnswer(string questionId)
+ {
+ _ = Throw.IfNullOrWhitespace(questionId);
+ foreach (DecisionAnswer answer in Answers)
+ {
+ if (string.Equals(answer.QuestionId, questionId, StringComparison.Ordinal))
+ {
+ return answer;
+ }
+ }
+
+ throw new KeyNotFoundException($"No answer exists for question ID '{questionId}'.");
+ }
+
+ internal void ValidateAgainst(DecisionRequest expectedRequest)
+ {
+ _ = Throw.IfNull(expectedRequest);
+
+ if (!JsonElement.DeepEquals(Request.State, expectedRequest.State) ||
+ Request.Questions.Count != expectedRequest.Questions.Count)
+ {
+ throw new DecisionProtocolException("The response does not correspond to the request sent by the client.");
+ }
+
+ for (int i = 0; i < Request.Questions.Count; i++)
+ {
+ if (!QuestionsAreEquivalent(Request.Questions[i], expectedRequest.Questions[i]))
+ {
+ throw new DecisionProtocolException("The response does not correspond to the request sent by the client.");
+ }
+ }
+ }
+
+ private static bool QuestionsAreEquivalent(DecisionQuestion actual, DecisionQuestion expected)
+ {
+ if (actual.Kind != expected.Kind ||
+ !string.Equals(actual.Id, expected.Id, StringComparison.Ordinal) ||
+ !string.Equals(actual.Instructions, expected.Instructions, StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ return (actual, expected) switch
+ {
+ (BinaryDecisionQuestion actualBinary, BinaryDecisionQuestion expectedBinary) =>
+ string.Equals(actualBinary.TrueDescription, expectedBinary.TrueDescription, StringComparison.Ordinal) &&
+ string.Equals(actualBinary.FalseDescription, expectedBinary.FalseDescription, StringComparison.Ordinal),
+
+ (ChoiceDecisionQuestion actualChoice, ChoiceDecisionQuestion expectedChoice) =>
+ CandidatesAreEquivalent(actualChoice.Candidates, expectedChoice.Candidates),
+
+ (ScoreDecisionQuestion actualScore, ScoreDecisionQuestion expectedScore) =>
+ LevelsAreEquivalent(actualScore.Levels, expectedScore.Levels),
+
+ _ => false,
+ };
+ }
+
+ private static bool CandidatesAreEquivalent(
+ IReadOnlyList actual,
+ IReadOnlyList expected)
+ {
+ if (actual.Count != expected.Count)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < actual.Count; i++)
+ {
+ if (!string.Equals(actual[i].Id, expected[i].Id, StringComparison.Ordinal) ||
+ !string.Equals(actual[i].Description, expected[i].Description, StringComparison.Ordinal))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool LevelsAreEquivalent(
+ IReadOnlyList actual,
+ IReadOnlyList expected)
+ {
+ if (actual.Count != expected.Count)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < actual.Count; i++)
+ {
+ if (!string.Equals(actual[i].Id, expected[i].Id, StringComparison.Ordinal) ||
+ !string.Equals(actual[i].Description, expected[i].Description, StringComparison.Ordinal))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static void ValidateAnswer(DecisionQuestion question, DecisionAnswer answer)
+ {
+ if (answer is null ||
+ !string.Equals(question.Id, answer.QuestionId, StringComparison.Ordinal) ||
+ question.Kind != answer.Kind)
+ {
+ throw new DecisionProtocolException("An answer does not exactly match its question.");
+ }
+
+ switch (question)
+ {
+ case BinaryDecisionQuestion when answer is BinaryDecisionAnswer:
+ return;
+
+ case ChoiceDecisionQuestion choice when answer is ChoiceDecisionAnswer choiceAnswer:
+ if (choiceAnswer.Probabilities.Count != choice.Candidates.Count ||
+ !choice.Candidates.Select(static candidate => candidate.Id)
+ .SequenceEqual(
+ choiceAnswer.Probabilities.Select(static probability => probability.Id),
+ StringComparer.Ordinal))
+ {
+ throw new DecisionProtocolException(
+ "Choice probabilities must contain exactly the requested candidate IDs in order.");
+ }
+
+ return;
+
+ case ScoreDecisionQuestion score when answer is ScoreDecisionAnswer scoreAnswer:
+ if (scoreAnswer.Probabilities.Count != score.Levels.Count ||
+ !score.Levels.Select(static level => level.Id)
+ .SequenceEqual(
+ scoreAnswer.Probabilities.Select(static probability => probability.Id),
+ StringComparer.Ordinal))
+ {
+ throw new DecisionProtocolException(
+ "Score probabilities must contain exactly the requested level IDs in order.");
+ }
+
+ return;
+
+ default:
+ throw new DecisionProtocolException("An answer kind does not match its question.");
+ }
+ }
+}
diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionDefinitions.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionDefinitions.cs
new file mode 100644
index 00000000000..887426af88b
--- /dev/null
+++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/MEAI/DecisionDefinitions.cs
@@ -0,0 +1,739 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#pragma warning disable SA1402 // Definition and nested builder are one immutable API surface.
+#pragma warning disable SA1649 // File name identifies the primary definition type.
+#pragma warning disable CA1000 // The generic type is the natural home for the typed factory methods.
+#pragma warning disable CA1032 // Decision materialization exposes protocol-specific failures.
+#pragma warning disable S2302 // Protocol exception messages intentionally describe the response and configured options.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.Json.Serialization.Metadata;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Shared.DiagnosticIds;
+using Microsoft.Shared.Diagnostics;
+
+namespace Microsoft.Extensions.AI;
+
+///
+/// Declares the decision questions and application-owned result properties for a typed decision flow.
+///
+/// The application-owned result type.
+[Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+public sealed class DecisionDefinition
+{
+ private readonly ReadOnlyCollection> _questions;
+
+ private DecisionDefinition(
+ JsonTypeInfo resultTypeInfo,
+ JsonSerializerOptions serializerOptions,
+ IReadOnlyList> questions)
+ {
+ ResultTypeInfo = resultTypeInfo;
+ SerializerOptions = serializerOptions;
+ _questions = new ReadOnlyCollection>(questions.ToArray());
+ Questions = new ReadOnlyCollection(_questions.Select(static question => question.Question).ToArray());
+ }
+
+ /// Gets the explicit JSON contract used to materialize the application result.
+ public JsonTypeInfo ResultTypeInfo { get; }
+
+ /// Gets the serializer options associated with this definition.
+ [JsonIgnore]
+ public JsonSerializerOptions SerializerOptions { get; }
+
+ /// Gets the immutable ordered questions declared by this definition.
+ public IReadOnlyList Questions { get; }
+
+ ///
+ /// Creates a typed definition using the configured default JSON contract for .
+ ///
+ /// The explicit question declaration callback.
+ ///
+ /// Optional JSON options used for property and enum metadata. A missing resolver is supplied from the MEAI defaults;
+ /// explicit caller resolvers and converters are preserved without mutating the caller's options.
+ ///
+ /// An immutable decision definition.
+ public static DecisionDefinition Create(
+ Action configure,
+ JsonSerializerOptions? serializerOptions = null)
+ {
+ _ = Throw.IfNull(configure);
+ serializerOptions = new JsonSerializerOptions(serializerOptions ?? AIJsonUtilities.DefaultOptions);
+ serializerOptions.TypeInfoResolver ??= AIJsonUtilities.DefaultOptions.TypeInfoResolver;
+ serializerOptions.MakeReadOnly();
+
+ JsonTypeInfo resultTypeInfo = GetResultTypeInfo(serializerOptions);
+ return Create(resultTypeInfo, configure);
+ }
+
+ /// Creates a typed definition using an application-supplied JSON contract.
+ /// The JSON contract for .
+ /// The explicit question declaration callback.
+ /// An immutable decision definition.
+ public static DecisionDefinition Create(
+ JsonTypeInfo resultTypeInfo,
+ Action configure)
+ {
+ _ = Throw.IfNull(resultTypeInfo);
+ _ = Throw.IfNull(configure);
+
+ Builder builder = new(resultTypeInfo);
+ configure(builder);
+ return builder.Build();
+ }
+
+ private static AIFunctionFactoryOptions GetFunctionOptions(
+ AIFunctionFactoryOptions? functionOptions,
+ JsonSerializerOptions serializerOptions)
+ {
+ if (functionOptions is null)
+ {
+ return new AIFunctionFactoryOptions { SerializerOptions = serializerOptions };
+ }
+
+ if (functionOptions.SerializerOptions is not null)
+ {
+ return functionOptions;
+ }
+
+ return new AIFunctionFactoryOptions
+ {
+ SerializerOptions = serializerOptions,
+ JsonSchemaCreateOptions = functionOptions.JsonSchemaCreateOptions,
+ Name = functionOptions.Name,
+ Description = functionOptions.Description,
+ AdditionalProperties = functionOptions.AdditionalProperties,
+ ConfigureParameterBinding = functionOptions.ConfigureParameterBinding,
+ MarshalResult = functionOptions.MarshalResult,
+ ExcludeResultSchema = functionOptions.ExcludeResultSchema,
+ };
+ }
+
+ /// Creates an that evaluates this definition for a caller-owned state type.
+ /// The application-owned state type exposed as the function's input.
+ /// The caller-owned decision client.
+ /// Optional standard function factory options.
+ ///
+ /// Optional decision options shallow-copied during construction and cloned for each invocation. Nested values and
+ /// the raw-options factory remain caller/provider-owned.
+ ///
+ ///
+ /// Optional explicit JSON contract for . When omitted, the definition's serializer
+ /// options must contain the state contract.
+ ///
+ /// A function whose only model-facing input is and whose result is .
+ public AIFunction AsAIFunction(
+ IDecisionClient client,
+ AIFunctionFactoryOptions? functionOptions = null,
+ DecisionOptions? decisionOptions = null,
+ JsonTypeInfo? stateTypeInfo = null)
+ {
+ _ = Throw.IfNull(client);
+
+ stateTypeInfo ??= GetStateTypeInfo();
+ DecisionOptions? decisionOptionsSnapshot = decisionOptions?.Clone();
+ DecisionFunctionInvoker invoker = new(client, this, stateTypeInfo, decisionOptionsSnapshot);
+
+ return AIFunctionFactory.Create(
+ invoker.InvokeAsync,
+ GetFunctionOptions(functionOptions, stateTypeInfo.Options));
+ }
+
+ internal DecisionResponse Bind(DecisionResponse response, DecisionRequest expectedRequest)
+ {
+ _ = Throw.IfNull(response);
+ response.ValidateAgainst(expectedRequest);
+
+ using MemoryStream stream = new();
+ using (Utf8JsonWriter writer = new(stream))
+ {
+ writer.WriteStartObject();
+
+ foreach (DecisionDefinitionQuestion question in _questions)
+ {
+ DecisionAnswer answer = response.GetAnswer(question.Question.Id);
+ switch (question.Kind)
+ {
+ case DecisionKind.Binary:
+ writer.WriteNumber(question.PropertyName, ((BinaryDecisionAnswer)answer).TrueProbability);
+ break;
+
+ case DecisionKind.Choice:
+ ChoiceDecisionAnswer choice = (ChoiceDecisionAnswer)answer;
+ writer.WriteString(question.PropertyName, choice.SelectedCandidateId);
+ break;
+
+ case DecisionKind.Score:
+ ScoreDecisionAnswer score = (ScoreDecisionAnswer)answer;
+ if (question.UsesExpectedScore)
+ {
+ writer.WriteNumber(question.PropertyName, score.ExpectedScore);
+ }
+ else if (score.Score is double reportedScore)
+ {
+ writer.WriteNumber(question.PropertyName, reportedScore);
+ }
+ else
+ {
+ throw new DecisionProtocolException(
+ $"Question '{question.Question.Id}' does not contain a provider-reported score.");
+ }
+ break;
+
+ default:
+ throw new DecisionProtocolException($"Unsupported decision kind '{question.Kind}'.");
+ }
+ }
+
+ writer.WriteEndObject();
+ }
+
+ byte[] resultJson = stream.ToArray();
+ TResult result;
+ try
+ {
+ result = JsonSerializer.Deserialize(resultJson, ResultTypeInfo)!;
+ }
+ catch (Exception exception) when (exception is JsonException or NotSupportedException)
+ {
+ throw new DecisionProtocolException(
+ "The decision response could not be materialized as the declared result type.",
+ exception);
+ }
+
+ if (result is null)
+ {
+ throw new DecisionProtocolException("The decision response produced a null result.");
+ }
+
+ foreach (DecisionDefinitionQuestion question in _questions)
+ {
+ DecisionAnswer answer = response.GetAnswer(question.Question.Id);
+ object? actualValue = question.ValueAccessor(result);
+ bool preserved = question.Kind switch
+ {
+ DecisionKind.Binary => actualValue is double actualBinary &&
+ actualBinary.Equals(((BinaryDecisionAnswer)answer).TrueProbability),
+ DecisionKind.Choice => question.ChoiceValueMatches is not null &&
+ question.ChoiceValueMatches(actualValue, ((ChoiceDecisionAnswer)answer).SelectedCandidateId),
+ DecisionKind.Score => actualValue is double actualScore &&
+ actualScore.Equals(question.UsesExpectedScore
+ ? ((ScoreDecisionAnswer)answer).ExpectedScore
+ : ((ScoreDecisionAnswer)answer).Score ?? double.NaN),
+ _ => false,
+ };
+
+ if (!preserved)
+ {
+ throw new DecisionProtocolException(
+ $"The decision response value for result property '{question.Property.Name}' was not preserved by the configured JSON contract.");
+ }
+ }
+
+ return new DecisionResponse(result, response, this);
+ }
+
+ private JsonTypeInfo GetStateTypeInfo()
+ {
+ return SerializerOptions.GetTypeInfo(typeof(TState)) is JsonTypeInfo stateTypeInfo
+ ? stateTypeInfo
+ : throw new NotSupportedException(
+ $"The configured JSON options do not contain a contract for state type '{typeof(TState)}'.");
+ }
+
+ private sealed class DecisionFunctionInvoker(
+ IDecisionClient client,
+ DecisionDefinition definition,
+ JsonTypeInfo stateTypeInfo,
+ DecisionOptions? decisionOptionsSnapshot)
+ {
+ private readonly IDecisionClient _client = client;
+ private readonly DecisionDefinition _definition = definition;
+ private readonly JsonTypeInfo _stateTypeInfo = stateTypeInfo;
+ private readonly DecisionOptions? _decisionOptionsSnapshot = decisionOptionsSnapshot;
+
+ [DisplayName("evaluate_decision")]
+ [Description("Evaluate the declared decision for one application state.")]
+ public async Task InvokeAsync(
+ [Description("The application state for the declared decision.")] TState state,
+ CancellationToken cancellationToken)
+ {
+ DecisionResponse response = await _client.GetResponseAsync(
+ state,
+ _stateTypeInfo,
+ _definition,
+ _decisionOptionsSnapshot?.Clone(),
+ cancellationToken).ConfigureAwait(false);
+ return response.Result;
+ }
+ }
+
+ internal IReadOnlyDictionary GetDistribution(
+ DecisionResponse response,
+ Expression> selector)
+ where TEnum : struct, Enum
+ {
+ DecisionDefinitionQuestion question = FindQuestion(selector);
+ if (question.Kind != DecisionKind.Choice ||
+ question.EnumDefinition is not DecisionEnumDefinition definition)
+ {
+ throw new DecisionProtocolException("The selected result property is not a choice enum in this definition.");
+ }
+
+ ChoiceDecisionAnswer answer = (ChoiceDecisionAnswer)response.Evidence.GetAnswer(question.Question.Id);
+ Dictionary values = new();
+ foreach (DecisionProbability probability in answer.Probabilities)
+ {
+ values.Add(definition.Parse(probability.Id), probability.Value);
+ }
+
+ return new ReadOnlyDictionary(values);
+ }
+
+ private static JsonTypeInfo GetResultTypeInfo(JsonSerializerOptions options)
+ {
+ if (options.GetTypeInfo(typeof(TResult)) is not JsonTypeInfo resultTypeInfo)
+ {
+ throw new NotSupportedException(
+ $"The configured JSON options do not contain a contract for result type '{typeof(TResult)}'.");
+ }
+
+ return resultTypeInfo;
+ }
+
+ private static PropertyInfo GetDirectProperty(Expression> selector)
+ {
+ _ = Throw.IfNull(selector);
+
+ Expression body = selector.Body;
+ if (body is UnaryExpression { NodeType: ExpressionType.Convert } conversion)
+ {
+ body = conversion.Operand;
+ }
+
+ if (body is not MemberExpression { Member: PropertyInfo property, Expression: ParameterExpression parameter } ||
+ selector.Parameters.Count != 1 ||
+ selector.Parameters[0] != parameter)
+ {
+ Throw.ArgumentException(
+ nameof(selector),
+ "The selector must access one direct instance property of the result type.");
+ return null!;
+ }
+
+ return property;
+ }
+
+ private DecisionDefinitionQuestion FindQuestion(Expression> selector)
+ {
+ PropertyInfo property = GetDirectProperty(selector);
+ return _questions.FirstOrDefault(question => question.Property == property) ??
+ throw new DecisionProtocolException($"The result property '{property.Name}' is not declared in this definition.");
+ }
+
+ /// Builds a through explicit property declarations.
+ [Experimental(DiagnosticIds.Experiments.AIDecisions, UrlFormat = DiagnosticIds.UrlFormat)]
+ public sealed class Builder
+ {
+ private readonly JsonTypeInfo _resultTypeInfo;
+ private readonly List> _questions = [];
+
+ private static DecisionEnumDefinition CreateEnumDefinition<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(
+ PropertyInfo property,
+ JsonTypeInfo resultTypeInfo,
+ JsonPropertyInfo jsonProperty)
+ where TEnum : struct, Enum
+ {
+ if (property.PropertyType.IsDefined(typeof(FlagsAttribute), inherit: false))
+ {
+ Throw.ArgumentException("selector", "Flags enums are not supported as closed decision choices.");
+ }
+
+ if (jsonProperty.CustomConverter is not null)
+ {
+ throw new NotSupportedException(
+ $"Property-specific JSON converters are not supported for decision enum property '{property.Name}'. " +
+ "Configure the enum converter at the JSON type/options level so candidate IDs and result materialization share one contract.");
+ }
+
+ JsonTypeInfo enumTypeInfo;
+ try
+ {
+ enumTypeInfo = resultTypeInfo.Options.GetTypeInfo(typeof(TEnum));
+ }
+ catch (Exception exception) when (exception is NotSupportedException or InvalidOperationException)
+ {
+ throw new NotSupportedException(
+ $"The configured JSON options do not contain a contract for enum type '{typeof(TEnum)}'.",
+ exception);
+ }
+
+#if NET5_0_OR_GREATER
+ TEnum[] enumValues = Enum.GetValues();
+#else
+ TEnum[] enumValues = Enum.GetValues(typeof(TEnum)).Cast().ToArray();
+#endif
+ List> values = new(enumValues.Length);
+ foreach (TEnum value in enumValues)
+ {
+ JsonElement serialized = JsonSerializer.SerializeToElement(value, enumTypeInfo);
+ if (serialized.ValueKind != JsonValueKind.String || serialized.GetString() is not string id)
+ {
+ throw new NotSupportedException(
+ $"Enum type '{typeof(TEnum)}' must use string JSON serialization for decision choices.");
+ }
+
+ string enumName = Enum.GetName(typeof(TEnum), value)!;
+ string description = typeof(TEnum).GetField(enumName)?.GetCustomAttribute()?.Description ??
+ enumName;
+
+ values.Add(new DecisionEnumValue(value, id, description));
+ }
+
+ return new DecisionEnumDefinition(values);
+ }
+
+ private static JsonPropertyInfo GetJsonProperty(JsonTypeInfo resultTypeInfo, PropertyInfo property)
+ {
+ JsonPropertyInfo? jsonProperty = resultTypeInfo.Properties.FirstOrDefault(
+ candidate => candidate.AttributeProvider is PropertyInfo propertyInfo && propertyInfo == property);
+
+ if (jsonProperty is null)
+ {
+ string expectedName = property.GetCustomAttribute()?.Name ??
+ resultTypeInfo.Options.PropertyNamingPolicy?.ConvertName(property.Name) ??
+ property.Name;
+ jsonProperty = resultTypeInfo.Properties.FirstOrDefault(
+ candidate => string.Equals(candidate.Name, expectedName, StringComparison.Ordinal));
+ }
+
+ if (jsonProperty is null)
+ {
+ Throw.ArgumentException(
+ nameof(property),
+ $"The selected property '{property.Name}' is not present in the configured JSON contract.");
+ }
+
+ return jsonProperty;
+ }
+
+ private static string GetInstructions(JsonPropertyInfo jsonProperty, PropertyInfo property, string? explicitInstructions)
+ {
+ if (explicitInstructions is not null)
+ {
+ return Throw.IfNullOrWhitespace(explicitInstructions);
+ }
+
+ string? description = (jsonProperty.AttributeProvider as PropertyInfo)?.GetCustomAttribute(inherit: true)?.Description;
+ if (description is not null)
+ {
+ return description;
+ }
+
+#if NET9_0_OR_GREATER
+ description = jsonProperty.AssociatedParameter?.AttributeProvider?.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true)
+ .OfType()
+ .FirstOrDefault()
+ ?.Description;
+#else
+ description = GetConstructorDescription(property);
+#endif
+ if (description is not null)
+ {
+ return description;
+ }
+
+ return property.PropertyType.GetCustomAttribute(inherit: true)?.Description ??
+ property.Name;
+ }
+
+ private static void EnsurePropertyCanBeDeclared(PropertyInfo property, Type expectedType)
+ {
+ if (property.GetMethod is null ||
+ property.GetMethod.IsStatic ||
+ property.PropertyType != expectedType)
+ {
+ Throw.ArgumentException("selector", $"The selected property must be a readable instance property of type '{expectedType}'.");
+ }
+ }
+
+#if !NET9_0_OR_GREATER
+ [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "The reflection convenience path checks preserved constructor binding metadata; source-generated metadata is used on newer TFMs.")]
+#endif
+ private static void EnsurePropertyCanBeMaterialized(
+ PropertyInfo property,
+ JsonPropertyInfo jsonProperty)
+ {
+ if (jsonProperty.Set is not null)
+ {
+ return;
+ }
+
+#if NET9_0_OR_GREATER
+ if (jsonProperty.AssociatedParameter is not null)
+ {
+ return;
+ }
+#else
+ ConstructorInfo[] constructors = property.DeclaringType?.GetConstructors() ?? [];
+ if (Array.Exists(
+ constructors,
+ candidate => Array.Exists(
+ candidate.GetParameters(),
+ parameter => string.Equals(parameter.Name, property.Name, StringComparison.OrdinalIgnoreCase))))
+ {
+ return;
+ }
+#endif
+
+ Throw.ArgumentException(
+ "selector",
+ $"The selected property '{property.Name}' is not writable or bound to a JSON constructor parameter.");
+ }
+
+#if !NET9_0_OR_GREATER
+ [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "The reflection convenience path intentionally reads preserved constructor parameter metadata; source-generated metadata is used on newer TFMs.")]
+ private static string? GetConstructorDescription(PropertyInfo property)
+ {
+ ConstructorInfo[] constructors = property.DeclaringType?.GetConstructors() ?? [];
+ ConstructorInfo? constructor = Array.Find(
+ constructors,
+ candidate => Array.Exists(candidate.GetParameters(), parameter =>
+ string.Equals(parameter.Name, property.Name, StringComparison.OrdinalIgnoreCase)));
+ return Array.Find(
+ constructor?.GetParameters() ?? [],
+ parameter => string.Equals(parameter.Name, property.Name, StringComparison.OrdinalIgnoreCase))
+ ?.GetCustomAttribute(inherit: true)
+ ?.Description;
+ }
+#endif
+
+ private static Func CreateValueAccessor(Expression> selector)
+ {
+#if NETFRAMEWORK
+ Func accessor = selector.Compile();
+#else
+ Func accessor = selector.Compile(true);
+#endif
+ return result => accessor(result);
+ }
+
+ private static Func