i am using llama-cpp
- User
i am using llama-cpp
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
i am using llama-cpp
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
When using llama-cpp (or llama.cpp) to ensure JSON output, you have two powerful approaches: grammar-based enforcement (most reliable) and prompt engineering. Here's how to implement both:
llama.cpp supports GBNF grammars to force valid JSON output. Create a .gbnf file defining your JSON schema:
json_schema.gbnf:root ::= object
value ::= object | array | string | number | "true" | "false" | "null"
object ::= "{" (string ":" value ("," string ":" value)*)? "}"
array ::= "[" (value ("," value)*)? "]"
string ::= "\"" ([a-zA-Z0-9] | " " | "-" | "_" | "." | "," | ":" | "!" | "?" | "'")* "\""
number ::= [0-9]+ ("." [0-9]+)?
# Enforce specific keys (customize this part!)
root ::= "{"
"\"name\"" ":" string ","
"\"age\"" ":" number ","
"\"hobbies\"" ":" array
"}"
from llama_cpp import Llama, LlamaGrammar
# Load model
llm = Llama(model_path="./your-model.gguf")
# Load grammar
with open("json_schema.gbnf", "r") as f:
grammar_str = f.read()
grammar = LlamaGrammar.from_string(grammar_str)
# Generate with grammar enforcement
response = llm(
"User query: Tell me about John, a 30-year-old who loves hiking and coding",
max_tokens=512,
grammar=grammar,
stop=["}"], # Stop generation after closing brace
temperature=0.0 # Minimize randomness
)
print(response["choices"][0]["text"])
# Output: {"name": "John", "age": 30, "hobbies": ["hiking", "coding"]}
If you can't use grammars, reinforce JSON in your prompt:
prompt = """[INST]
<<SYS>>You MUST output VALID JSON ONLY. Use this structure:
{
"key1": "value",
"key2": ["list", "items"],
"key3": {"nested": "object"}
}
<</SYS>>
User request: {user_input}
[/INST]
JSON:
""".format(user_input="Your query here")
response = llm(prompt, max_tokens=512, stop=["\n}"])
Grammar Builder Tools:
Model Recommendations:
Mistral-7B-Instruct-v0.3 (best for JSON)Phi-3 variantsLlama-3-8B-InstructCritical Parameters:
response = llm(
prompt,
grammar=grammar, # Enforce structure
temperature=0.0, # Disable randomness
max_tokens=512, # Prevent truncation
stop=["}\n", "}]", "}}"], # Stop at valid endpoints
top_p=0.1 # Reduce diversity
)
Parse & Validate Output:
import json
from json.decoder import JSONDecodeError
raw_output = response["choices"][0]["text"] + "}" # Close if needed
try:
data = json.loads(raw_output)
except JSONDecodeError:
# Fallback: Use repair logic
data = json.loads(raw_output.strip().split("{")[-1].split("}")[0] + "}")
| Problem | Solution |
|---|---|
| Truncated JSON | Increase max_tokens, add stop=["}"] |
| Trailing commas | Use grammar that forbids them: array ::= "[" (value ("," value)*)? "]" |
| Unclosed brackets | Append }/] programmatically before parsing |
| Key hallucinations | Strict grammar: root ::= "{" "\"name\"" ":" string ... }" |
| Numeric inconsistencies | Grammar enforcement: number ::= [0-9]+ ("." [0-9]+)? |
# Step 1: Define grammar
grammar = LlamaGrammar.from_string(r'''
root ::= {"name": string, "age": number, "active": boolean}
boolean ::= "true" | "false"
string ::= "\"" [a-zA-Z0-9_ ]+ "\""
number ::= [0-9]+
''')
# Step 2: Generate response
response = llm(
"Extract: 'Alex, 28 years, status: active' as JSON",
grammar=grammar,
temperature=0.0
)
# Step 3: Parse safely
output = response['choices'][0]['text'].strip()
if not output.endswith("}"): output += "}"
try:
data = json.loads(output)
except:
# Fallback: Extract first JSON-like substring
import re
json_str = re.search(r"{.*}", output, re.DOTALL).group()
data = json.loads(json_str)
print(data) # {'name': 'Alex', 'age': 28, 'active': True}
For production, combine grammar enforcement with a validation layer. Most issues disappear when using strict grammars with temperature=0!