Checked AI Extraction in an ASP.NET Core Minimal API
A Minimal API that calls a model needs a clear boundary between the answer it receives and the response it sends. A deserialized object can still have a missing quantity or a malformed product code. An unavailable provider also needs a different response from an extraction that needs review.
This example uses IntentSharp 1.0.0 in ASP.NET Core 10. It returns a checked extraction without creating an order or changing a database. Its automated demonstration uses scripted responses and an in-memory ASP.NET Core server. The results test the HTTP contract and retry behavior, not model accuracy.
Create the API
This example targets 1.0.0. If you used rc.3, follow the migration guide; provider setup has changed.
Create an ASP.NET Core Empty project targeting .NET 10 and install version 1.0.0 of the IntentSharp package from NuGet. Use the web SDK's default implicit usings and nullable settings. The quick start covers provider setup; the configuration and dependency injection guide covers client registration and license configuration.
Create config/intentsharp.providers.json under the project root with the file below. Replace <model id> with a model available in your provider account, and set ANTHROPIC_API_KEY on the server. To choose another provider or fallback chain, use the provider file guide. Keep provider and license keys out of browser code and source control. Real calls incur provider charges.
{
"intentsharp": "providers/1",
"providers": [
{ "name": "main", "kind": "anthropic", "secret": "env:ANTHROPIC_API_KEY", "model": "<model id>" }
],
"roles": { "answer": "main" }
}The startup statements read that folder relative to the application's content root. Include the configuration file in your deployed application and keep its secret reference separate from the key itself.
Replace Program.cs with these using directives followed by the startup statements. One shared client is registered as a singleton. The using declarations dispose the client and document store when the host ends.
using IntentSharp;using IntentSharp.Documents;using Microsoft.AspNetCore.Builder;using Microsoft.Extensions.DependencyInjection;var builder = WebApplication.CreateBuilder(args);using var store = new FolderDocumentStore(Path.Combine(builder.Environment.ContentRootPath, "config"));using var client = new IntentClientBuilder().UseProviderOptions(store).Build();builder.Services.AddSingleton(client);var app = builder.Build();OrderApi.OrderExtraction.Map(app);await app.RunAsync();Add the following two files to the project, retaining their OrderApi namespace. A nullable quantity allows an extraction to represent a quantity that was not supplied.
namespace OrderApi; public sealed record EmailInput(string? Email);namespace OrderApi; public sealed record ExtractedOrder(string Sku, int? Quantity);Map the extraction boundary
Add OrderExtraction.cs below. Blank input or an email longer than 10,000 characters receives HTTP 400 before a model call. This field-length check does not replace server request-body limits.
using System.Text.RegularExpressions;using IntentSharp;using IntentSharp.Extensions;using IntentSharp.Results;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Http; namespace OrderApi; public static class OrderExtraction{ public static void Map(WebApplication app) { app.MapPost("/orders/extract", async Task<IResult> (EmailInput input, IntentClient client, CancellationToken cancellationToken) => { if (string.IsNullOrWhiteSpace(input.Email) || input.Email.Length > 10_000) return Results.BadRequest(new { message = "Supply an email of 1 to 10000 characters." }); var options = new AIRequestOptions { MaxAttempts = 2, MaxModelCalls = 2, Timeout = TimeSpan.FromSeconds(10), } .Require<ExtractedOrder>(o => o.Quantity is > 0, "Quantity must be positive.") .Require<ExtractedOrder>(o => Regex.IsMatch(o.Sku ?? "", @"^[A-Z]-\d{4}$"), "Sku must look like A-1192."); var result = await input.Email.AIAsync<ExtractedOrder>( client, "Extract the SKU and quantity from this order email.", options, cancellationToken); if (!result.Success) { if (result.Issues.Any(i => i.Source == IssueSource.Provider)) return Results.Problem(statusCode: 503, title: "Extraction service unavailable."); return Results.UnprocessableEntity(new { message = "Extraction needs review.", attempts = result.Attempts.Count, }); } return Results.Ok(new { order = result.Value, attempts = result.Attempts.Count }); }); }}The call requests a SKU and nullable quantity. Executable checks require a positive quantity and a SKU shaped like A-1192. Those checks execute in the application process.
MaxAttempts and MaxModelCalls each cap this example at two. Timeout supplies a ten-second budget for the extraction run; it is not a promise about the whole HTTP request's duration or a dollar cap. The request cancellation token is passed through to the call.
Success returns HTTP 200 with the checked order and attempt count. A failed result containing a provider issue returns generic HTTP 503 Problem Details. Other unsuccessful results return HTTP 422 with a review message and attempt count, without an order.
This is the sample's response policy. Extend it for the timeout, cancellation and other failure classifications your application needs. Unexpected programming exceptions still need the application's normal exception handling. Failure responses do not expose raw model output or source emails.
Exercise the endpoint
Run the project and use the local URL it prints. Send an application/json request to POST /orders/extract with an email property containing Please send 40 units of A-1192.
In the scripted demonstration, the first answer contains A1192 and fails the format check. The next contains A-1192 and quantity 40. The endpoint returns HTTP 200 after two attempts. Real model responses can differ.
Then use Please send A-1192; I will confirm the quantity later.
as the email. The demonstration supplies null quantity twice, so the endpoint returns HTTP 422 without an order. Blank and oversized emails each return 400 without another model call. A scripted unavailable provider returns 503.
Checked order: HTTP 200, attempts 2, SKU A-1192, quantity 40Missing quantity: HTTP 422, attempts 2, no order returnedEmpty or oversized email: HTTP 400, no additional model callProvider unavailable: HTTP 503, no order returnedThe site build exercises the endpoint through TestServer without opening a network listener or contacting a model. It checks statuses, extracted values, retry counts and rejection before model use. TestHost is a verification dependency; the API application itself needs IntentSharp and the ASP.NET Core framework.
Keep the business decision explicit
The SKU expression checks format, not product existence. A positive number is not proof that the email contained that quantity. A model can invent a positive number and pass that particular check. Compare results with authoritative data or require review when downstream actions need stronger evidence.
The sample performs no business write. It also leaves the endpoint anonymous. Add authentication, authorization, per-user limits, server body limits and required approvals before exposing an endpoint that incurs provider cost. The sample does not implement those deployment controls. Configure logging and retention for your data requirements.
IntentSharp is commercial software built and sold by C2Consultants LLC. Development and test evaluation is free for 30 days; afterward any business use requires a paid license, and production needs one from day one. Personal use and coursework remain free. I create and sell the library.