instructJson static method
Rewrites a prompt to ask for JSON, and describes the shape you expect.
Appending the shape explicitly measurably improves compliance, and stating "no prose" up front saves the extraction step from having to work.
Implementation
static String instructJson(
String prompt, {
Map<String, Object?>? schema,
bool array = false,
}) {
final buffer = StringBuffer(prompt)
..write('\n\nRespond with ')
..write(array ? 'a JSON array' : 'a JSON object')
..write(' only. Do not include prose, explanation, or a markdown fence.');
if (schema != null) {
buffer
..write(' The object must have exactly these keys: ')
..write(schema.keys.join(', '))
..write('. Example shape:\n')
..write(jsonEncode(schema));
}
return buffer.toString();
}