Home/
Part XV — Troubleshooting, Checklists, and Reference/45. Common Failure Modes (And Fix Recipes)/45.2 Outputs are correct but messy
45.2 Outputs are correct but messy
Overview and links for this section of the guide.
On this page
Symptom
The content is right, but the formatting is inconsistent, has extra whitespace, or doesn't match your schema.
Fixes
// Fix 1: Enforce JSON schema
const schema = z.object({
answer: z.string(),
confidence: z.number().min(0).max(1)
});
const response = await model.generateContent({
contents: prompt,
generationConfig: { responseMimeType: 'application/json' }
});
const parsed = schema.parse(JSON.parse(response.text()));
// Fix 2: Post-processing
function cleanOutput(text: string): string {
return text
.trim()
.replace(/```json\n?/g, '') // Remove markdown
.replace(/```\n?/g, '')
.replace(/^\s*\n/gm, ''); // Remove blank lines
}
// Fix 3: Be explicit about format
const prompt = `
Output format (exact structure):
{
"answer": "string, max 100 chars",
"sources": ["array", "of", "strings"]
}
No markdown. No explanation. Just the JSON object.
`;