How They Use AI  |  Newest

<< Home  |  Prompting craft

Output valid JSON pretty much 100% of the time

AreaPrompting craft
AI usedLlama 3.1
SourceReddit thread
Posted2024-08-12

The move

Combine multi-shot examples, zero temperature, end-of-prompt reminders, and response prefilling with an opening bracket.
When this worksWhen it doesn't
An LLM like Llama 3.1 includes conversational filler, introductions, or markdown code blocks when asked for JSON output.The API or interface does not allow setting temperature to 0 or prefilling the assistant response.

Key details

Prompt for your AI

Role and goal: You are a strict JSON generator. Your sole function is to process inputs and return raw, valid JSON with no extra text. Rules for implementation: 1. Set model temperature to 0 to minimize randomness. 2. Structure the prompt with multi-shot examples showing the exact structure expected: Here is an example input: [EXAMPLE INPUT] Here is an example output: {"key": "value"} 3. Add direct behavioral instructions: "Respond only with valid JSON. Do not write an introduction or summary." 4. Repeat the constraint at the very end of the prompt: "Only respond with valid JSON. Nothing else. The first character in your response should be {" 5. Use response prefilling: if using an Instruct format (such as Llama 3 Instruct), place `{` after the assistant tag to force output generation to start within JSON object structure. Here is the real input: [REAL INPUT] Now write the real output: Before you give me the final result, check with me: - Model temperature is set to 0. - At least one multi-shot example input/output pair is provided. - The JSON-only constraint is repeated right at the end of the prompt. - The assistant output header is prefilled with an opening brace '{'.

What happened

A user needed Llama 3.1 to return pure JSON without conversational text. By setting temperature to 0, adding multi-shot examples, repeating 'Only respond with valid JSON' at the end, and prefilling the assistant response with '{', the model outputted valid JSON 100% of the time.

Who confirmed it

The first character in your response should be { as the last part of my system prompt works well.

Give it to your agent

Read https://howtheyuse.ai/p/force-model-to-output-only-valid-json.md and help me do this.

Sources



Last updated November 26, 2026.