Structured JSON extraction

Turn free text into JSON that matches your schema: pick a tier that supports structured output, send response_format, and validate the result.

Extraction turns free text, such as a support email, into a record your code can use. Asking for JSON in prose gets you JSON most of the time. Sending a schema in response_format constrains the output to it. This recipe chains Models, to find a tier that supports structured output, and Chat, to run the extraction.

The request

The central call is one chat request with a json_schema:

curl
curl https://api.cruxy.ai/api/v1/chat \
  -H "Authorization: Bearer $CRUXY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "saga",
    "stream": false,
    "messages": [
      { "role": "system", "content": "Extract the ticket fields from the email." },
      { "role": "user", "content": "Hi, I was charged twice for order 8841 on 3 November. Please refund one. Priya" }
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "ticket",
        "schema": {
          "type": "object",
          "properties": {
            "category": { "type": "string", "enum": ["billing", "shipping", "account", "other"] },
            "order_id": { "type": "string", "nullable": true },
            "customer_name": { "type": "string", "nullable": true },
            "summary": { "type": "string", "maxLength": 200 }
          },
          "required": ["category", "order_id", "customer_name", "summary"],
          "additionalProperties": false
        }
      }
    }
  }'

The full recipe

The script below reads the tier catalog, picks a tier whose supports_structured_output is true, runs the extraction, and checks the result before trusting it.

TypeScript
const BASE = 'https://api.cruxy.ai'
const auth = {
  Authorization: `Bearer ${process.env.CRUXY_API_KEY}`,
  'Content-Type': 'application/json',
}
 
type Ticket = {
  category: 'billing' | 'shipping' | 'account' | 'other'
  order_id: string | null
  customer_name: string | null
  summary: string
}
 
const CATEGORIES = ['billing', 'shipping', 'account', 'other']
 
const ticketSchema = {
  type: 'object',
  properties: {
    category: { type: 'string', enum: CATEGORIES },
    order_id: { type: 'string', nullable: true },
    customer_name: { type: 'string', nullable: true },
    summary: { type: 'string', maxLength: 200 },
  },
  required: ['category', 'order_id', 'customer_name', 'summary'],
  additionalProperties: false,
}
 
// 1. Find a tier that honours response_format. Read it; do not hardcode it.
async function structuredTier(preferred: string[]): Promise<string> {
  const res = await fetch(`${BASE}/api/v1/models`, { headers: auth })
  if (!res.ok) throw new Error(`models failed: ${res.status}`)
  const { data } = await res.json()
  const supported = new Set(
    data
      .filter((m: { supports_structured_output?: boolean }) => m.supports_structured_output)
      .map((m: { id: string }) => m.id),
  )
  const tier = preferred.find((id) => supported.has(id))
  if (!tier) throw new Error('no preferred tier supports structured output')
  return tier
}
 
// 2. Run the extraction.
async function extract(model: string, email: string): Promise<Ticket> {
  const res = await fetch(`${BASE}/api/v1/chat`, {
    method: 'POST',
    headers: auth,
    body: JSON.stringify({
      model,
      stream: false,
      messages: [
        { role: 'system', content: 'Extract the ticket fields from the email.' },
        { role: 'user', content: email },
      ],
      response_format: {
        type: 'json_schema',
        json_schema: { name: 'ticket', schema: ticketSchema },
      },
    }),
  })
 
  if (!res.ok) {
    const err = await res.json()
    // 422 structured_output_unsatisfied: the output did not match the schema.
    // The attempt was billed, and a retry may pass. Every other code here
    // describes the request, and fails the same way until you change it.
    throw new Error(`${res.status} ${err.code}: ${err.error} (request_id ${err.request_id})`)
  }
 
  const completion = await res.json()
  if (completion.finish_reason !== 'stop') {
    throw new Error(`extraction ended with finish_reason ${completion.finish_reason}`)
  }
 
  // 3. Parse and check in your own code as well.
  const ticket = JSON.parse(completion.message.content) as Ticket
  if (!CATEGORIES.includes(ticket.category) || typeof ticket.summary !== 'string') {
    throw new Error('extraction does not match the schema')
  }
  return ticket
}
 
const tier = await structuredTier(['saga', 'epos', 'canto'])
const ticket = await extract(
  tier,
  'Hi, I was charged twice for order 8841 on 3 November. Please refund one. Priya',
)
console.log(tier, ticket)

What the gateway guarantees

  • The schema is checked first. A schema outside the supported keywords and limits is 400 invalid_schema before any model call. Schema rules lists them. $ref and $defs are not supported, so write the schema flat.
  • A named tier is never moved. A structured request that names a tier without support is 422 structured_output_unsupported. With model: "auto", the router sends it only to a tier that supports it.
  • A non-streaming answer is re-validated. Output that does not conform is 422 structured_output_unsatisfied. It is billed, and it may pass on a retry.
  • A stream is not re-validated. The constraint is enforced upstream, and the gateway does not check the assembled output, so validate it yourself.
  • Reasoning is off. Structured output turns reasoning off for the request.

Why validate again

The gateway's check covers the schema. It does not cover what your code needs beyond the schema: that an order_id exists in your system, or that a date is in range. It also cannot help when the answer is cut short: a finish_reason of length means the JSON may be truncated, which is why the recipe checks for stop before parsing. Keep the schema small, mark every property required, and use nullable for a value the text may not contain, so the model returns null instead of inventing one.

Next steps

Was this page helpful?