<?php
use Cognesy\Messages\Messages;
use Cognesy\Polyglot\Inference\Data\ResponseFormat;
use Cognesy\Polyglot\Inference\Inference;
$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',
],
'forecast' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'day' => ['type' => 'string'],
'high' => ['type' => 'number'],
'low' => ['type' => 'number'],
'conditions' => ['type' => 'string'],
],
'required' => ['day', 'high', 'low', 'conditions'],
],
],
],
'required' => ['location', 'current_temperature', 'conditions', 'forecast'],
];
$data = Inference::using('openai')
->with(
messages: Messages::fromString('Provide a weather report for Paris, France.'),
responseFormat: ResponseFormat::jsonSchema(
schema: $schema,
name: 'weather_report',
strict: true,
),
)
->asJsonData();
echo "Weather in {$data['location']}: {$data['conditions']}, {$data['current_temperature']}C\n";
foreach ($data['forecast'] as $day) {
echo " {$day['day']}: {$day['low']}C - {$day['high']}C, {$day['conditions']}\n";
}
// @doctest id="3fe5"