Skip to main content
In this tutorial, you’ll learn how to:
  • Guarantee structured output using our chat completions API
  • This can be done using JSON Schema / Pydantic models, (schemaless) JSON Mode, regular expressions, and multiple choice.

Sentiment Analysis using Multiple Choice

One of the simplest forms of structured output is multiple choice. The only possible outputs of the following code snippet are positive or negative.
Make sure you have set the TELNYX_API_KEY environment variable
zai-org/GLM-5.2 is a reasoning model. Your structured output still arrives in choices[0].message.content — the model’s chain-of-thought is returned separately in choices[0].message.reasoning_content, so it never pollutes the JSON you parse. To surface the reasoning, read it alongside content:

Building on this with guided_json

Now let’s say we want to capture an explanation for the classification as well. We can leverage the guided_json field for this.
This will ensure a JSON response with the same schema as the following

Simplifying Schema Generation using Pydantic

The above is helpful to see the raw JSON Schema specification being sent via API. However, for practical purposes, using Pydantic models can help simplify generating the specs. The following is functionally equivalent to the previous example.

Schema-less JSON Mode

We also support the schema-less JSON mode provided by OpenAI

And now for something completely different (regular expressions)

You can do a lot with regular expressions, and now you can ensure language model outputs follow a regex. Something we see a lot, especially in a voice context, is wanting to limit the length of a response. Below is a toy example limiting a response to a sentence with 20 words or fewer.