Learn how to use Markdown JSON mode in Polyglot for structured LLM responses.
Markdown JSON mode is a special mode that requests the model to format its response as JSON within a Markdown code block. This is particularly useful for models or providers that don’t have native JSON output support.
<?phpuse Cognesy\Polyglot\Inference\Inference;use Cognesy\Polyglot\Inference\Enums\OutputMode;$inference = new Inference();// This works with virtually any provider$response = $inference->with( messages: 'List three programming languages and their key features.', mode: OutputMode::MdJson)->asJsonData();// The model will return JSON wrapped in Markdown, which Polyglot processes for youforeach ($response['languages'] as $language) { echo "{$language['name']} - {$language['paradigm']}\n"; echo "Key features: " . implode(', ', $language['key_features']) . "\n\n";}
While MdJson is more flexible across providers, you still need to provide clear instructions:
Copy
<?phpuse Cognesy\Polyglot\Inference\Inference;use Cognesy\Polyglot\Inference\Enums\OutputMode;$inference = new Inference();// Include expected format in the prompt$prompt = <<<EOTList three programming languages with their key features.Respond with a JSON object following this structure:{ "languages": [ { "name": "Language name", "paradigm": "Programming paradigm", "year_created": year as number, "key_features": ["feature1", "feature2", "feature3"] }, ]}EOT;$response = $inference->with(messages: $prompt,mode: OutputMode::MdJson)->toJson();// Process as normal JSON