Agent Structured Output

Production-grade guide to agent structured output covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Orientation

Agent structured output refers to the practice of getting an artificial intelligence agent to return a response that conforms to a predictable, machine‑readable shape—most commonly a JSON document that validates against a declared schema—rather than free‑form natural language. This matters whenever an agent’s output feeds downstream systems: API calls, database writes, configuration generation, or routing logic. Without structured output, every agent response requires parsing, regex extraction, or brittle string matching, and the cost of that parsing grows linearly with every additional agent in the system.

Requesting a Structured Reply

When an agent needs to pass data downstream, the HTTP request is extended with a payload section that describes the expected output shape. The method is almost always POST to the chat‑completion endpoint. The Content-Type header is set to application/json, and the Authorization header carries a bearer token. The request body includes the conversation history (or a single user message) and the schema‑carrying section.

Many chat‑completion endpoints accept an additional payload section that carries the desired output shape; the identifier for this section is implementation‑specific. Below is a concrete curl invocation that follows the structural pattern used across providers:

curl -s -X POST https://api.example.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "messages": [
      {"role": "user", "content": "Extract the issuing bank and expiry date from this card: 4532 XXXX XXXX 1234, expiry 03/31."}
    ],
    "output_schema": {
      "type": "object",
      "properties": {
        "bank": {"type": "string"},
        "expiry": {"type": "string", "pattern": "^(0[1-9]|1[0-2])/([0-9]{2})$"}
      },
      "required": ["bank", "expiry"]
    }
  }'

The output_schema key in the body signals the service to constrain the model’s output. After the request completes, the content field of the final assistant message should contain a JSON string that conforms to the declared schema, or the provider returns a validation error.

Verifying the Output Shape

Once the response is received, the content field is extracted and typically parsed with a JSON validator. A common pattern uses jq to both extract and validate in one step:

curl -s -X POST https://api.example.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{"messages": [{"role": "user", "content": "Extract the data."}], "output_schema": {...}}' |
  jq -e '.choices[0].message.content' > /dev/null

If jq exits with a non‑zero status, the output either is not valid JSON or does not match the shape expectations of the downstream consumer. In production pipelines this exit code triggers a retry or a fallback path.

Enforcing and Validating Shape

The schema supplied in the request describes allowed types, required fields, and optional constraints such as enums or regex patterns. The model is instructed—via the payload structure—to generate only output that adheres to this shape. In practice, compliance is not guaranteed.

A sharp edge: a model may produce a valid JSON document that nonetheless violates a subtle schema constraint, such as an enum value substituted with a close synonym, or a pattern match that is nearly satisfied but fails. When this happens, the downstream parser raises an exception, and if error handling is absent the agent loop may silently continue, leading to corrupted data in downstream stores.

Another sharp edge: increasing temperature raises the probability of schema violations. When strict adherence is required, temperature should be set to 0 or a very low value, but even at 0 some models decline to follow the schema if the prompt context does not strongly reinforce it.

Handling Failures and Retries

When the model’s output does not match the schema, the provider returns an error response. A typical error payload, regardless of vendor, looks like this:

{
  "error": {
    "message": "response does not conform to the requested schema",
    "type": "validation_error",
    "param": null,
    "code": "schema_validation_failed"
  }
}

The code field names the error category; the message describes the mismatch. Some providers include a path indicator showing which schema field caused the failure.

Common failure modes that trigger this error:

Retry strategy: when a validation error is received, the agent can (a) reduce temperature, (b) re‑prompt with a few‑shot example that demonstrates the exact expected format, or (c) adjust the schema to be less restrictive and perform post‑processing validation locally. There is no universal “retry limit” baked into the protocol; each deployment must define its own policy. Unbounded retries with the same prompt can consume tokens indefinitely, especially if the model systematically ignores the schema key.

Adjusting Parameters for Reliability

Chaining Output into Workflows

In a multi‑agent or agent‑tool pipeline, the structured output from one step becomes the input to the next. The typical flow is:

  1. Agent A receives a user query and returns a JSON object with extracted fields.
  2. A downstream consumer (another agent, a script, a database loader) reads the JSON and acts on it.
  3. If the JSON is invalid, the consumer routes the request to a retry or error‑handling branch.

To make this reliable, the schema declared in step 1 should be versioned or documented explicitly, because a schema change in step 1 breaks the consumer in step 2 without any runtime error from the provider—the failure is purely a data‑shape mismatch. A practical pattern is to include a "version" field in the output schema so that consumers can reject payloads that do not match the expected version.

When piping output through jq or equivalent tools, the command often looks like:

curl -s -X POST ... | jq '.choices[0].message.content' | jq 'fromjson'

The first jq extracts the raw string from the API response; the second jq parses it as JSON. If either step fails, the pipeline halts and can invoke a fallback.

Sharp Edges – What Silently Fails in Production

Quick Checklist for Production Deployments

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.