Use cases, before and after.
Most cases start where hand-written code usually starts, with Microsoft.Extensions.AI: a model call, a JSON parse, a check and a retry loop.
12 cases
The code you write by hand, and the IntentSharp version.
Each case puts the careful hand-written version, in outline, beside the IntentSharp version, with the intent between them. The IntentSharp code compiles with the site, and the outputs come from the demo program, on a scripted model.
Order triage
For line-of-business teams: rule changes without a release.
Rate how urgent each order email is. The scale, the wording and the examples change as the business finds what works, and today each change is a build and a deployment. If the scale never changes, the same check works inline with AIAsync<int> and a Require<int> rule; the file is for when it does change. To stop the triage without a release, set enabled: false in the file: the next call throws IntentDisabledException before any model call.
- Before
- The wording and the scale compiled in, with your own check and retry.
- The intent
Orders.ClassifyUrgency, in a file: rate the urgency of an order email from 1 (routine) to 5 (critical).- After
- A call by name: the wording, the scale and the rules move into the file.
Before
By hand, the wording, the scale and the examples are constants in your code. Your code sends them with each email, checks that the answer is a whole number from 1 to 5 and asks again with the finding when it is not. Each change to the wording or the scale is a build and a deployment.
public static async Task<int?> ClassifyUrgencyAsync(IChatClient chat, string email, CancellationToken ct = default){ // 1. Send your instructions, scale and examples with the email. var response = await chat.GetResponseAsync<int>(messages, cancellationToken: ct); // 2. Check for a whole number from 1 to 5. // 3. On a failure, send the finding back and ask again. // 4. After your last attempt, return null.}
After
using var scope = intents.AsAmbient();var urgency = await email.RunIntentAsync<int>("Orders.ClassifyUrgency");
name: Orders.ClassifyUrgencyversion: 1owner: order-deskintent: Rate the urgency of this order email from 1 (routine) to 5 (critical).shape: intrules: minimum: 1 maximum: 5examples: - input: "Line 3 is down until the bearings arrive. Ship today." output: 5 - input: "Please restock these when convenient, no rush." output: 1
Success: trueValue: 4Issues: none
Invoice intake
For finance and operations apps: rules the model must meet.
Pull the vendor, number, currency and total out of invoice emails, and refuse anything outside the currencies you accept. A wrong currency goes back to the model as a concrete finding. The rule can live in the intent file, as here, or in code with Require<T>; either way the finding drives the next attempt.
- Before
- Required members, plus hand-written checks and a retry.
- The intent
Invoice.Extract, in a file: the vendor, invoice number, currency and total, in USD, EUR or GBP, with no negative total.- After
- The rules move into the file; a broken rule is retried.
Before
By hand, the accepted currencies and the minimum total are checks in your code. After each answer your code runs every check and sends the findings back for another attempt when one fails. A new currency is a code change and a release.
public static async Task<Invoice?> ExtractAsync(IChatClient chat, string email, CancellationToken ct = default){ // 1. Ask for an Invoice record whose members are required. var response = await chat.GetResponseAsync<Invoice>(messages, cancellationToken: ct); // 2. Check your rules: USD, EUR or GBP, and no negative total. // 3. On a failure, send every finding back and ask again. // 4. After your last attempt, return null.}
After
name: Invoice.Extractversion: 1owner: accounts-payableintent: Extract the vendor, invoice number, currency and total from this invoice email.shape: kind: schema schema: type: object properties: vendor: { type: string } invoiceNumber: { type: string } currency: { type: string } total: { type: number } required: [vendor, invoiceNumber, currency, total]rules: properties: currency: enum: [USD, EUR, GBP] total: minimum: 0
var invoice = await email.RunIntentAsync(intents, "Invoice.Extract");[Validator] attempt 1: value.currency is "US$"; allowed: USD, EUR, GBP.Success: true, after 2 attemptsValue: {"vendor":"Contoso Supplies","invoiceNumber":"INV-2291","currency":"USD","total":1240.00}
Ticket grouping
For support and product tools: your objects, not copies.
Sort a backlog into defects and feature requests. On success the original objects come back, each in exactly one group: your own Ticket objects, not copies. AISortAsync and AIFilterAsync hand back your objects the same way: a sort returns every ticket exactly once, and a filter returns the matching tickets in their original order.
- Before
- Tie the answer back to your tickets, check each is in one group, retry by hand.
- The intent
- Group the tickets by whether each reports a defect or asks for a feature.
- After
- One call: the tie-back to your objects and the group check are built in.
Before
By hand, your code ties each ticket in the model's answer back to one of your own objects, then checks that every ticket sits in exactly one group and that the answer names none you did not send. On a failure it sends the findings back and asks again.
public static async Task<Dictionary<string, List<Ticket>>?> GroupAsync(IChatClient chat, IReadOnlyList<Ticket> tickets, CancellationToken ct = default){ // 1. Send the tickets and ask for labelled groups. // 2. Tie each ticket in the answer to one of your Ticket objects. // 3. Check each ticket is in exactly one group, and none is invented. // 4. On a failure, send the findings back and ask again. // 5. After your last attempt, return null.}
After
var tickets = new List<Ticket>{ new(101, "Login page returns 500 after password reset", "Critical"), new(102, "Add dark mode", "Low"), new(103, "Export to CSV drops the last row", "High"), new(104, "Let admins invite users in bulk", "Medium"),};var groups = await tickets.AIGroupAsync(client, "by whether the ticket reports a defect or asks for a feature");
Success: trueDefect: 101, 103Feature request: 102, 104Every grouped Ticket is the object from tickets, not a copy: trueIssues: none
Agent tools
For teams adopting Microsoft Agent Framework: checked tools.
Give an agent work it can delegate. AsAIFunctions() turns every enabled intent into a standard AIFunction tool, with no model call. The model is asked only when the agent runs a tool. Each answer is checked against the file's rules, and a failure comes back to the agent as JSON instead of an exception. A saved edit to an intent file changes the rules the next tool call is checked against; the tool's name and description refresh when you build the tools again.
- Before
- Wrap your own checked call in a tool by hand.
- The intent
Orders.ClassifyUrgency, as a tool the agent calls: rate each order email from 1 (routine) to 5 (critical).- After
- One call makes every enabled intent a checked tool.
Before
By hand, each tool wraps your own checked call in an AIFunction, with a name and a description you keep in step with the code. The tool catches every failure and returns it as JSON, since a tool must not throw into the agent loop. Each new tool is the same code again.
public static AIFunction UrgencyTool(IChatClient model) => AIFunctionFactory.Create( async (string input, CancellationToken ct) => { // 1. Run your checked ClassifyUrgencyAsync, from order triage. // 2. Catch every failure: a tool must never throw to the agent. // 3. Return the value or the error as JSON the agent can read. }, name: "Orders_ClassifyUrgency", description: "Rates the urgency of an order email from 1 (routine) to 5 (critical).");
After
var options = new ChatOptions { Tools = [.. intents.AsAIFunctions()] };var reply = await agent.GetResponseAsync(inbox, options);
The agent's scripted model calls Orders_ClassifyUrgency once per email. Tool call 1, input: Our packaging line stops on Thursday unless the 40 replacement belts arrive. Can you expedite?Tool result: {"success":true,"intent":"Orders.ClassifyUrgency","value":4} Tool call 2, input: URGENT!!! On a scale of 1 to 10 this is a 9. Please send the replacement filters by the end of the month.Tool result: {"success":false,"intent":"Orders.ClassifyUrgency","error":"value is 9; the maximum is 5."}
Ranking by judgement without losing an item
For backlogs and lead lists: your own objects, every one exactly once.
On success the original objects come back, ordered by the model, each exactly once. An answer that leaves a ticket out or repeats one fails the attempt and goes back to the model as a finding, and the next answer returns your own Ticket objects in the new order. The whole list goes in one request, so every public property of each item and every member marked [JsonInclude] is sent, unless it is marked [JsonIgnore], and MaxInputChars (200,000 characters by default) caps its size.
- Before
- Tie the order back to your tickets, check each comes back once, retry by hand.
- The intent
- Rank the tickets by how badly each blocks users, most blocking first.
- After
- One call: the once-each check and the retry are built in.
Before
By hand, your code ties the model's order back to your own Ticket objects and checks that every ticket comes back exactly once, with none missing, repeated or invented. On a failure it sends the findings back and asks again, within the attempts you allow.
public static async Task<List<Ticket>?> SortAsync(IChatClient chat, IReadOnlyList<Ticket> tickets, CancellationToken ct = default){ // 1. Send the tickets and ask for them most blocking first. // 2. Tie each ticket in the answer to one of your Ticket objects. // 3. Check each comes back once: none missing, repeated or invented. // 4. On a failure, send the findings back and ask again. // 5. After your last attempt, return null.}
After
var ranked = await tickets.AISortAsync(client, "by how badly the ticket blocks users, most blocking first");Attempt 1 passed: falseSuccess: true, after 2 attempts1. 101 Login page returns 500 after password reset (Critical)2. 103 Export to CSV drops the last row (High)3. 104 Let admins invite users in bulk (Medium)4. 102 Add dark mode (Low)Every ticket appears exactly once, as the object from tickets: true
Free-text prices into numbers, keyed by SKU
For catalogues and price lists: every key checked.
Turn a dictionary of SKU to price text into SKU to decimal? in one request. A missing, extra or repeated key fails the attempt and goes back to the model as a finding, and the nullable result lets the model answer null where the text gives no price. The keys stay yours: the call cannot rename or add one, and the whole dictionary must fit in MaxInputChars.
- Before
- One call per key, each with its own check and retry.
- The intent
- Read each unit price in US dollars as a number, or null when no price is given.
- After
- One request for all the keys, checked and retried.
Before
By hand, the simple way to keep each price tied to its SKU is one model call per key, each with its own check and retry. The calls grow with the list, and one key that fails leaves the whole map without a result.
public static async Task<Dictionary<string, decimal?>?> ReadPricesAsync(IChatClient chat, IReadOnlyDictionary<string, string> prices, CancellationToken ct = default){ // 1. For each SKU, one model call: its text in, a number or null out. // 2. Check each answer; on a failure, send the finding and ask again. // 3. The loop, not the model, ties each answer to its key. // 4. One key with no valid answer fails the whole map: return null.}
After
var unitPrices = await prices.AIMapValuesAsync<string, string, decimal?>(client, "Read the unit price in US dollars as a number. Use null when no price is given.");
[Validator] attempt 1: Missing keys: C-3301.Success: true, after 2 attemptsA-1192: "31.00 each" -> 31.00B-2040: "12.50 dollars per box" -> 12.50C-3301: "call for a quote" -> nullModel calls (ScriptedProvider.CallCount): 2 for 3 keys
Different fields per customer
For multi-tenant apps: a shape chosen at run time.
Each customer's field list is a JSON schema kept in config or a database. TransformAsync(input, intent, schema) asks the model for JSON in that shape, with no class to compile when a field changes. The core checks only that the reply is JSON and not null, so the schema's own rules need your validators, such as the required-fields check here, or an intent file's schema shape.
- Before
- A class per tenant and a switch, so a new field is a release.
- The intent
- Extract the fields of each customer's JSON schema from the invoice email.
- After
- The schema passed as data, plus your required-fields check.
Before
By hand, each customer's fields are a class in your code, and a switch picks the class for the customer. A new customer, or a new field for one, is a code change, a build and a deployment.
// One class per customer: TenantAInvoice, TenantBInvoice, and so on.public static async Task<object?> ExtractAsync(IChatClient chat, string tenant, string email, CancellationToken ct = default) => tenant switch{ "tenant-a" => await ExtractAsync<TenantAInvoice>(chat, email, ct), // ask, check, ask again on a failure "tenant-b" => await ExtractAsync<TenantBInvoice>(chat, email, ct), _ => throw new ArgumentException($"No invoice class for tenant \"{tenant}\".", nameof(tenant)),};
After
// The core checks that the reply is JSON and not null. The schema's own rules are for your validators: this// one checks that every required field is present.static AIRequestOptions RequiredFields(JsonNode schema) => new AIRequestOptions().Validate<JsonNode>(value => schema["required"]!.AsArray().Select(name => name!.GetValue<string>()) .Where(name => value[name] is null) .Select(name => $"{name} is required.")); var results = new Dictionary<string, AIResult<JsonNode>>();foreach (var (tenant, schema) in schemas) results[tenant] = await client.TransformAsync(email, "Extract these fields from the invoice email.", schema, RequiredFields(schema));
tenant-a, schema fields: vendor, totalSuccess: trueValue: {"vendor":"Contoso Supplies","total":1240.00}Issues: none tenant-b, schema fields: supplier, invoiceNumber, dueDateSuccess: trueValue: {"supplier":"Contoso Supplies","invoiceNumber":"INV-2291","dueDate":"2026-11-01"}Issues: none The core checked each reply for JSON and not null; the RequiredFields validator checked the requiredfields. The core does not check other schema rules: add validators, or use an intent file's schema shape.
Questions over the database you have
For internal tools and reporting: plain words in, records out.
Connect your database as a target and ask for customers in California with a total above 1000: PlanAsync returns one statement and its parameters without running it, and CheckAsync has the target inspect it and checks it against your rule file, here read only and the Customers table only. Once a person approves the plan, ExecuteAsync runs the same check again, then the target runs the statement, with no model call. Keep the approved plan and run it again the same way: the model is asked only when you plan; the check runs every time you execute. The model sees every table the target describes, so a rule, not the prompt, refuses a statement that reads PaymentCards. The check is a guard, not a permission boundary, so the database account's own permissions still matter.
- Before
- The same SELECT written by hand in ADO.NET, one method per question, no model.
- The intent
- A question in plain words: customers in California with a total above 1000.
- After
- The question in plain words: a checked plan for a person to approve, then run by your target under your rule file.
Before
By hand, each question your users ask is a method, with its SQL and its parameters written and reviewed in advance. A new question is new SQL, a build and a deployment.
// One method per question: a new question is new SQL and a release.public static async Task<List<(long Id, string FullName, string State, double Total)>> CustomersAboveAsync( DbConnection connection, string state, double minTotal, CancellationToken ct = default){ // 1. The SQL, written and reviewed in advance: // SELECT Id, FullName, State, Total FROM Customers WHERE State = @state AND Total > @minTotal ORDER BY Total DESC // 2. Bind @state and @minTotal, run the command and read the rows.}
After
intentsharp: rules/1 set: customers-read checkpoint: data target: sqlite rules: - id: customers-only subject: data.entities allow: [Customers] message: Use only the Customers table. - id: read-only subject: data.operations allow: [read] message: Only read; this set never changes data. settings: data.maxResults: 200
// customers-read, a rule file: read only, and only the Customers table.var runtime = new TargetRuntime(client, target, new TargetRuntimeOptions { GuardrailSets = ["customers-read"] }); // Plan only: the statement and its parameters come back, and nothing runs.var plan = await runtime.PlanAsync("Customers in California with a total above 1000");var check = await runtime.CheckAsync(plan.Value!); // After a person approves the plan, run it. The rules check it again first.var outcome = await runtime.ExecuteAsync(plan.Value!);
Question: Customers in California with a total above 1000Plan: Success: trueStatement: SELECT Id, FullName, State, Total FROM Customers WHERE State = @state AND Total > @minTotal ORDER BY Total DESCParameters: @state = "CA", @minTotal = 1000Check: allowed true, entities Customers, operations read ExecuteAsync: executed true, 2 records{"Id":3,"FullName":"Chen Wu","State":"CA","Total":3000}{"Id":1,"FullName":"Alice Moreno","State":"CA","Total":1500} A plan that reads PaymentCards, checked and not run:Check: allowed false customers-read/customers-only: Use only the Customers table.
The model's JSON almost parses
For every model call: checked, then retried with the finding.
Ask for your own record type, and every reply is checked by code before your code sees it. A reply that does not read as the type, a missing required member or a name that is not an enum member fails the attempt, and the next attempt shows the model its answer and the finding, within the attempts you allow. The type sets the shape, not ranges or patterns, which go in your own rules.
- Before
- Parse, catch the error and retry by hand.
- The intent
- Extract the vendor, invoice number, currency and total into your
Invoicerecord. - After
- One call: the parse check and the retry are built in.
Before
By hand, your code parses the reply into your record and turns a parse error or a missing member into a message for the model. Then it asks again, within the attempts you allow.
public static async Task<Invoice?> ExtractAsync(IChatClient chat, string email, CancellationToken ct = default){ // 1. Ask for an Invoice record whose members are required. var response = await chat.GetResponseAsync<Invoice>(messages, cancellationToken: ct); // 2. Parse the reply into your record yourself. // 3. Make a parse error or a missing member a finding; ask again. // 4. After your last attempt, return null.}
After
var invoice = await client.TransformAsync<Invoice>(email, "Extract the vendor, invoice number, currency and total from this invoice email.");Attempt 1 passed: false, one Verification findingSuccess: true, after 2 attemptsValue: {"vendor":"Contoso Supplies","invoiceNumber":"INV-2291","currency":"USD","total":1240.00}
A ceiling on one call
For any web request: limits you set.
Cap the model calls (judge calls included) and the wall-clock time of one request with MaxModelCalls and Timeout. When either limit is hit, the request ends with Success = false and an issue that names the limit, not a hung request or an exception. The limits count attempts, model calls, output tokens and time, not money.
- Before
- A call counter, a time budget and a retry, by hand.
- The intent
- Extract the purchase request, within 3 model calls and 10 seconds.
- After
- The limits as options on the call, reported on the result.
Before
By hand, your code counts its own model calls, keeps its own time budget, and tells a cancel from the caller apart from the budget running out. Each stop has to come back as something your code can report, not as a hung request or an exception.
public static async Task<(PurchaseRequest? Order, string? StoppedBy)> ExtractAsync(IChatClient chat, string email, CancellationToken ct = default){ // 1. Start a 10-second budget, linked to the caller's token. // 2. Before each model call, stop at the ceiling of 3 calls. // 3. Ask, check the quantity, and on a failure send the finding back. // 4. Tell a caller's cancel from a spent budget; name the limit.}
After
var options = new AIRequestOptions { MaxAttempts = 5, MaxModelCalls = 3, Timeout = TimeSpan.FromSeconds(10) } .Require<PurchaseRequest>(r => r.Quantity > 0, "Quantity must be a positive number."); var order = await email.AIAsync<PurchaseRequest>(client, "Extract the purchase request from this email.", options);
Success: false, after 3 attemptsIssues: [Validator] attempt 1: Quantity must be a positive number. [Validator] attempt 2: Quantity must be a positive number. [Validator] attempt 3: Quantity must be a positive number. [Constraint] attempt 4: Model call ceiling of 3 reached before a verified result was produced.Model calls (ScriptedProvider.CallCount): 3 of the 5 answers queued
The vendor is down or rate-limiting you
For anything that must keep answering: one fallback, only on transient errors.
Name one fallback provider, which can also be a local model behind an IChatClient. It is called only on a transient error: a 408, a 429, a 5xx, a transport failure, an unreadable reply, a model the provider does not serve (404) or the provider's HTTP timeout. It is never called on an authentication error, a bad request or a wrong answer, and the result says which provider answered. A model name set on a call goes to the first provider only; the fallback asks for its own model.
- Before
- A try/catch around two chat clients, with your own transient-error test.
- The intent
- Rate the urgency of an order email from 1 to 5, from the first provider or, on a transient error, the fallback.
- After
- One builder line: transient errors only; the result names the provider.
Before
By hand, your code holds two chat clients and a try/catch around the call, and decides for itself which errors move the call to the second client. It has to tell a rate limit or an outage apart from a bad key or a bad request, and report which client answered.
public static async Task<(int? Urgency, string AnsweredBy)> ClassifyUrgencyAsync( IChatClient primary, IChatClient fallback, string email, CancellationToken ct = default){ // 1. Call the primary with ClassifyUrgencyAsync, from order triage. // 2. Catch only a failure that may pass next time (your own test). // 3. On one, run the same code on the fallback; say which answered. // 4. A bad key, a bad request or a wrong answer does not fall back.}
After
using var client = new IntentClientBuilder() .UseProvider(primary) .UseFallbackProvider(fallback) // only on a transient error: 408, 429, 5xx, transport, unreadable reply, 404, timeout .Build(); var urgency = await email.AIAsync<int>(client, "Rate the urgency of this order email from 1 (routine) to 5 (critical).");
Primary (scripted): threw AIProviderException "Service unavailable (503).", IsTransient = true, on 1 callSuccess: trueValue: 4Issues: noneProvider: FallbackAttempts: 1, answered by Fallback
The same question, answered from the cache
For anything you pay for twice: re-checked before reuse.
With WithCache(new InMemoryRequestCache()), an identical request is answered from an in-process cache with no call for the answer, while the entry lasts (one hour by default). A judge, if on, still reviews it with one call. A cached answer is checked against the current request's rules before it is reused, and replaced if it fails them. So an answer cached under older rules is not served unchecked. The cache lives in this process only, and a new wording or a new result shape is a new request.
- Before
- A dictionary cache, checked once when the answer is stored.
- The intent
- Rate the urgency of an order email from 1 to 5; the same request again is answered from the cache.
- After
- One builder line: a hit is checked again before reuse.
Before
By hand, a dictionary in front of the call keeps each accepted answer. A hit comes back as it was stored, with no check against the rules in force now, and your code decides what makes two requests the same and how long an entry lasts.
// Your own class: a dictionary of accepted answers in front of the call.public async Task<(int? Urgency, bool FromCache)> ClassifyAsync(string email, CancellationToken ct = default){ // 1. Look the request up; a hit comes back as stored, unchecked. // 2. On a miss, ask, check for 1 to 5, and ask again on a failure. // 3. Store the answer for the next request you count as the same.}
After
using var client = new IntentClientBuilder() .UseProvider(provider) .WithCache(new InMemoryRequestCache()) .Build(); var intent = "Rate the urgency of this order email from 1 (routine) to 5 (critical).";var first = await email.AIAsync<int>(client, intent); // calls the modelvar again = await email.AIAsync<int>(client, intent); // the same request: answered from the cache, no model call // A different request has a different key and calls the model: a new wording, or a new result shape (text).var reworded = await email.AIAsync<int>(client, intent + " A stopped production line is critical.");var asText = await email.AIAsync(client, intent);
first: Success: true, Value: 4, FromCache: falseagain: Success: true, Value: 4, FromCache: true, Usage: 0 input tokens, 0 output tokensreworded: Success: true, Value: 5, FromCache: falseasText: Success: true, Value: 4, FromCache: falseModel calls (ScriptedProvider.CallCount): 3 for 4 requests; "again" made none.