- Call a language model to list countries and capitals.
- Instruct the model to return valid JSON using a
JsonOutputParser’s format instructions. - Parse the LLM response into native Python data structures for direct use in application logic.
1) Imports and a simple LLM call
Start by importing the necessary components and creating an LLM client:2) Add a JsonOutputParser and obtain format instructions
Instantiate aJsonOutputParser to provide the LLM with exact format instructions. The parser exposes a helper string you can embed in your prompt to ask for valid JSON:
format_instructions will be a short guideline such as “Return a JSON object.” Use this text so the model knows to produce valid, parseable JSON.
3) Create a prompt that includes the format instructions
Embed the parser’s instructions into your prompt usingpartial_variables. This ensures every invocation contains the necessary instructions for structured output:
4) Invoke the LLM with the structured prompt and parse the result
Call the model with the new prompt and then parse the returned JSON string into native Python types:5) Why this approach helps
- The parser’s format instructions encourage the LLM to produce valid JSON (or another predictable format), reducing parsing errors.
- Passing the LLM response through
JsonOutputParserconverts a string into native Python types (dict, list), which eliminates manual parsing and validation plumbing. - Once parsed, the result can be fed directly into application logic, converted into dataclasses, or serialized for storage/transmission.
Quick reference: workflow steps
Links and further reading
Always include the parser’s format instructions in the prompt when you want structured output; otherwise the model may return freeform text that fails to parse.