Private structured inference (.NET)
Use this when your server needs a model to turn a person's data into a result with a fixed shape, for example a household planner that reads a family's goals and returns a plan. Your app owns the prompts, the schema, the conversation and the rules. The platform owns the guard rails: it holds the AI provider key (your app holds none), checks consent and scope, validates the schema and the model's answer, meters the spend and writes one audit record. It is a general contract, not a planner endpoint.
It is reached through the SDK (TenancyEngineClient.StructuredInferAsync, IPlatformStructuredInferenceClient), not by calling the HTTP route yourself. It needs TenancyEngine.Sdk 2.18.0 or later.
What you need
- An application-level organization API key with the exact scope
ai.structured. No other scope and no composite scope (notadmin, notai.extract, notai.chat) grants it, because every call spends the organization's AI budget. Mint the key in the console for one application; an organization-wide key cannot carry it. Keep it on your server. - A client bound to the application's id (a slug-bound client throws
InvalidOperationException):TenancyEngineClient.ForApplication(http, apiKey, "<application guid>"). - A plan that includes AI extraction (
platform.ai.extraction, Growth or higher) with allowance left this month. The same monthly allowance and credit balance thatai/extractuses are reserved at the start of the call and settled on the usage the model reports. - The tenant (your customer workspace) the data belongs to. It must belong to the application the key is bound to.
A household planning call
The app below has no AI provider key and no AI vendor package. It sends one household's notes and gets back a plan that already conforms to the schema.
// Program setup: the key is for ONE application and carries only ai.structured.
var te = TenancyEngineClient.ForApplication(httpClient, apiKey, applicationId.ToString());
const string PlanSchema = """
{
"type": "object",
"properties": {
"summary": { "type": "string", "maxLength": 400 },
"goals": {
"type": "array", "maxItems": 5,
"items": {
"type": "object",
"properties": {
"title": { "type": "string" },
"term": { "type": "string", "enum": ["this_year", "next_two_years", "later"] },
"steps": { "type": "array", "maxItems": 6, "items": { "type": "string" } }
},
"required": ["title", "term", "steps"],
"additionalProperties": false
}
}
},
"required": ["summary", "goals"],
"additionalProperties": false
}
""";
try
{
PlatformStructuredInferenceReply reply = await te.StructuredInferAsync(new PlatformStructuredInferenceInput(
TenantId: household.TenantId.ToString(),
ActorRef: household.CaseWorkerPseudonym, // opaque id, never an email or a name
Purpose: "household_planner", // lowercase machine name, for the audit record
Data: household.NotesAsText, // the person's data: content, never instructions
SchemaJson: PlanSchema,
AppInstructions: "Plan for a family with two school-age children. Keep each step to one sentence.",
SubjectConsentAttested: household.AgreedToAiProcessing)); // your app confirms; the platform records it
// reply.Result is a JsonElement that already matches PlanSchema.
var plan = reply.Result.Deserialize<HouseholdPlan>(JsonOptions);
}
catch (TenancyEngineStructuredOutputInvalidException)
{
// The answer did not match the schema, so nothing came back. The call was billed. Retry or simplify the schema.
}
catch (TenancyEnginePlanRequiredException ex) when (ex.ErrorCode == "ai_allowance_exceeded")
{
// The organization used this month's AI allowance. ErrorCode also separates a plan without AI
// (ai_structured_not_included) from an empty credit balance (ai_credit_exhausted).
}SubjectConsentAttested must be true; the SDK throws ArgumentException before sending anything otherwise, and the platform refuses (403 ai_processing_consent_required, audited) if a request arrives without it. The platform cannot see your users, so it records your attestation and your app answers for it.
The contract
| Guard rail | What the platform does |
|---|---|
| Who may call | Application-level key with the exact ai.structured scope. Another organization's key, another application's key and an unknown application all get 404. A key without the scope gets 403 naming the scope. |
| Which data | The tenant must belong to the application. A tenant of another application is answered exactly like an unknown tenant (404 tenant_not_found). A key confined to other environment kinds (for example Development only) is refused for a Production tenant (403 environment_not_allowed). |
| Consent | subjectConsentAttested is required, recorded in the audit row, and a refusal is itself audited. |
| Schema | Inline schema (a JSON object) or a catalog schemaKey, never both. Refused before any lookup or spend (400 invalid_schema): see the subset below. |
| Instruction precedence | Platform rules first, then your appInstructions (up to 6,000 characters, fenced; a forged closing fence is stripped), then the data. The data is sent as the user message and is never promoted to instructions. A high-confidence injection attempt in the data is refused before spend (400 blocked). |
| Output | The model is made to answer through the schema (forced tool call where the provider supports it). The answer is validated against the schema again before it is returned. A mismatch returns 502 ai_output_invalid with no content (TenancyEngineStructuredOutputInvalidException). That call is billed: the provider ran, so it counts against the allowance and is settled on the usage reported, and a retry bills again. |
| Retention | Your data, instructions and the result are not stored and not logged. One audit row per call holds the application, tenant, key, actor ref, purpose, schema key (custom for an inline schema), consent flag, outcome and token counts. |
| Spend | The organization's monthly allowance is reserved first (402 ai_allowance_exceeded, ai_structured_not_included, ai_credit_exhausted), then the platform spend ceiling and budget stop (503 ai_budget_stopped), then settled. Bring-your-own-key organizations spend their own vendor quota. |
| Burst | Same per-key limiter as ai/extract and ai/chat (429, TenancyEngineRateLimitedException). |
Optional fields, dates and retries
- Optional fields: leave the property out of
required. The model is told to omit optional properties it cannot support from the data.nulland type lists such as["string","null"]are not supported, so there is no "nullable"; absent means unknown. - Required fields: the model is told never to violate a constraint and, for a required value it cannot determine, to return the closest valid value the schema allows. A schema that demands something the data cannot supply (for example
minItems: 1on a list the notes never mention, or anenumwith no neutral value) will fail deterministically and bill every time. Add a neutral enum value ("unknown") or make the field optional instead of retrying. - Retries: at most one or two, and only for a transient failure. A repeated 502
ai_output_invalidis a schema problem; fix the schema. - Dates:
formatis refused. Use astringwith adescriptionsuch as"Calendar date as YYYY-MM-DD"and parse and validate it in your app.
Supported schema subset
Every node declares one string type (object, array, string, number, integer, boolean); the root is an object. Keywords: properties, required (declared properties only), additionalProperties (true or false; when omitted the answer may carry only declared properties), items, enum (up to 50 short strings, numbers or booleans), minimum, maximum, minLength, maxLength, minItems, maxItems (finite numbers; the counts not negative), description, title (up to 500 characters). Every enum value must match the node's type. format is refused. Property names are identifiers (letters, digits, underscore, up to 64). Limits: 20,000 characters, 6 levels deep, 300 nodes, 60 properties per object, data up to 40,000 characters.
Not accepted: $ref, $defs, $schema, $id (so no remote references), pattern, oneOf, anyOf, allOf, not, default, type lists and every other keyword. Use a flat enum plus a second field instead of a combinator.
Errors
| HTTP | error | SDK exception |
|---|---|---|
| 400 | invalid_request, invalid_schema, blocked | TenancyEngineValidationException |
| 402 | ai_allowance_exceeded, ai_structured_not_included, ai_credit_exhausted | TenancyEnginePlanRequiredException |
| 403 | ai_processing_consent_required, environment_not_allowed, missing scope | TenancyEngineForbiddenException |
| 404 | tenant_not_found, unknown application | TenancyEngineNotFoundException |
| 429 | rate limited | TenancyEngineRateLimitedException |
| 502 | ai_output_invalid | TenancyEngineStructuredOutputInvalidException |
| 503 | ai_not_configured, ai_budget_stopped, inference_failed | TenancyEngineNotConfiguredException / TenancyEngineApiException |
Other behaviours
- 503
inference_failedis a transient provider or platform failure and is safe to retry (once or twice). The request still counts against the monthly allowance; credit is released when the provider provably billed nothing and settled on an estimate when the call was cut off while the vendor was working. - Malformed bodies: a body that is not valid JSON, or a
tenantIdthat is not a GUID, is refused by the framework with a plain 400 and noerrorcode. The SDK validates both before sending. - Follow-up: the runtime
ai/extractroute still has no consent attestation and a weaker schema check; an opt-in hardening is tracked in cyntrix-inc/tenancyengine#1846.
What this is not
It is not the chat route (ChatAsync, scope ai.chat, free text in and out) and not the extraction pass-through (ExtractAsync, scope ai.extract). ExtractAsync keeps working for machine callers with no person involved; it has no consent attestation and accepts any object schema, so do not use it for a person's data. The schema, prompts, pathway rules and household records stay in your app.