PHP code example of mertcanekiz / phpydantic

1. Go to this page and download the library: Download mertcanekiz/phpydantic library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mertcanekiz / phpydantic example snippets


use Phpydantic\BaseModel;

class Step extends BaseModel
{
    /** @Description A detailed explanation for this step */
    public string $explanation;

    /** @Description The result or output of this step */
    public string $output;
}

class MathReasoning extends BaseModel
{
    /**
     * @var Step[]
     * @Description List of reasoning steps
     */
    public array $steps;

    /** @Description The final answer to the problem */
    public string $finalAnswer;
}

// Returns schema as PHP array
$schemaArray = MathReasoning::schema();

// Returns pretty-printed JSON string
$schemaJson = MathReasoning::jsonSchema();

use OpenAI\OpenAI;

$client = OpenAI::client('YOUR_API_KEY');
$schema = MathReasoning::openAiSchema();

$response = $client->chat()->create([
    'model' => 'gpt-4o-2024-08-06',
    'messages' => [
        ['role' => 'system',  'content' => 'You are a helpful math tutor. Guide the user step by step.'],
        ['role' => 'user',    'content' => 'How can I solve 8x + 7 = -23?'],
    ],
    'response_format' => [
        'type' => 'json_schema',
        'json_schema' => $schema,
    ],
]);

$data = json_decode($response['choices'][0]['message']['content'], true);
// Access results: $data['steps'], $data['finalAnswer']

$json = '{
    "steps": [
        {
            "explanation": "First, subtract 7 from both sides",
            "output": "8x = -30"
        },
        {
            "explanation": "Then divide both sides by 8",
            "output": "x = -3.75"
        }
    ],
    "finalAnswer": "x = -3.75"
}';

$reasoning = MathReasoning::fromJson($json);

// Access the data as PHP objects
foreach ($reasoning->steps as $step) {
    echo $step->explanation . "\n";
    echo $step->output . "\n";
}
echo "Final answer: " . $reasoning->finalAnswer;