<?php
use Cognesy\Polyglot\Inference\Inference;
use Cognesy\Polyglot\Inference\Enums\OutputMode;
$inference = new Inference()->using('openai'); // Currently best supported by OpenAI
// Define a schema for a weather report
$schema = [
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'The city and country'
],
'current_temperature' => [
'type' => 'number',
'description' => 'Current temperature in Celsius'
],
'conditions' => [
'type' => 'string',
'description' => 'Current weather conditions (e.g., sunny, rainy)'
],
'forecast' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'day' => [
'type' => 'string',
'description' => 'Day of the week'
],
'temperature_high' => [
'type' => 'number',
'description' => 'Expected high temperature in Celsius'
],
'temperature_low' => [
'type' => 'number',
'description' => 'Expected low temperature in Celsius'
],
'conditions' => [
'type' => 'string',
'description' => 'Expected weather conditions'
]
],
'required' => ['day', 'temperature_high', 'temperature_low', 'conditions']
],
'description' => 'Three-day weather forecast'
]
],
'required' => ['location', 'current_temperature', 'conditions', 'forecast']
];
// Request a weather report
$response = $inference->with(
messages: 'Provide a weather report for Paris, France.',
responseFormat: [
'type' => 'json_schema',
'json_schema' => [
'name' => 'weather_report',
'schema' => $schema,
'strict' => true,
],
],
mode: OutputMode::JsonSchema
)->asJsonData();
// The response will match the schema's structure exactly
echo "Weather in {$response['location']}:\n";
echo "Currently {$response['conditions']} and {$response['current_temperature']}°C\n\n";
echo "Forecast:\n";
foreach ($response['forecast'] as $day) {
echo "{$day['day']}: {$day['conditions']}, {$day['temperature_low']}°C to {$day['temperature_high']}°C\n";
}
// @doctest id="55c3"