How to ensure llm return json?
- User
How to ensure llm return json?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to ensure llm return json?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To ensure an LLM reliably returns valid JSON, use these proven techniques:
Structure your prompt with:
Always respond in valid JSON format. Use this exact structure:
{
"key1": "value",
"key2": ["array", "of", "items"],
"key3": { "nested": "object" }
}
"Do not add explanations or extra text outside the JSON"Define a strict schema using $schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {"type": "string"},
"items": {"type": "array", "items": {"type": "string"}},
"count": {"type": "number"}
},
"required": ["name", "items"]
}
OpenAI Function Calling:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": "List 3 books"}],
functions=[{
"name": "output_formatter",
"parameters": {
"type": "object",
"properties": {
"books": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {"type": "string"},
"author": {"type": "string"}
}
}
}
}
}
}],
function_call={"name": "output_formatter"} # Force JSON output
)
Anthropic Claude (XML Tags):
<output>
{"response": "your_json_here"}
</output>
Always validate and fix responses:
import json
from json_repair import repair_json
def safe_parse(json_str):
try:
return json.loads(json_str)
except json.JSONDecodeError:
repaired = repair_json(json_str) # Use json_repair library
return json.loads(repaired)
# Usage:
valid_json = safe_parse(llm_response)
Use these libraries for guaranteed JSON:
LangChain:
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel
class Book(BaseModel):
title: str
author: str
parser = PydanticOutputParser(pydantic_object=Book)
prompt = f"Generate book data: {parser.get_format_instructions()}"
LlamaIndex:
from llama_index.program import OpenAIPydanticProgram
program = OpenAIPydanticProgram(
model=Book,
prompt_template="List books about {topic}"
)
program(topic="science")
temperature=0 for deterministic output\n or "} to prevent extra text| Issue | Solution |
|---|---|
| Trailing commas | Use jsonrepair library |
| Unescaped quotes | Add "Replace quotes with \\\"" in prompt |
| Truncated responses | Increase max_tokens |
| XML/Text wrappers | Add "Remove outer XML tags" instruction |
json.loads()response_format={ "type": "json_object" } (OpenAI)Pro Tip: For production systems, use two-shot validation:
- First LLM call generates JSON
- Second call verifies with:
"Verify this JSON is valid: {json_str}. Return {'valid':true} or fix it."