Skip to content

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 (not admin, not ai.extract, not ai.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 that ai/extract uses 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.

csharp
// 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 railWhat the platform does
Who may callApplication-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 dataThe 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).
ConsentsubjectConsentAttested is required, recorded in the audit row, and a refusal is itself audited.
SchemaInline schema (a JSON object) or a catalog schemaKey, never both. Refused before any lookup or spend (400 invalid_schema): see the subset below.
Instruction precedencePlatform 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).
OutputThe 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.
RetentionYour 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.
SpendThe 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.
BurstSame 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. null and 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: 1 on a list the notes never mention, or an enum with 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_invalid is a schema problem; fix the schema.
  • Dates: format is refused. Use a string with a description such 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 ​

HTTPerrorSDK exception
400invalid_request, invalid_schema, blockedTenancyEngineValidationException
402ai_allowance_exceeded, ai_structured_not_included, ai_credit_exhaustedTenancyEnginePlanRequiredException
403ai_processing_consent_required, environment_not_allowed, missing scopeTenancyEngineForbiddenException
404tenant_not_found, unknown applicationTenancyEngineNotFoundException
429rate limitedTenancyEngineRateLimitedException
502ai_output_invalidTenancyEngineStructuredOutputInvalidException
503ai_not_configured, ai_budget_stopped, inference_failedTenancyEngineNotConfiguredException / TenancyEngineApiException

Other behaviours ​

  • 503 inference_failed is 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 tenantId that is not a GUID, is refused by the framework with a plain 400 and no error code. The SDK validates both before sending.
  • Follow-up: the runtime ai/extract route 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.

TenancyEngine platform documentation