PHP code example of opctim / chatgpt-schema-generator

1. Go to this page and download the library: Download opctim/chatgpt-schema-generator 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/ */

    

opctim / chatgpt-schema-generator example snippets




use Opctim\ChatGpt\SchemaGenerator\Generator;
use Opctim\ChatGpt\SchemaGenerator\Tests\Fixtures\Dto\User;

// Generate the schema based on your DTO
$schema = $this->generator->generateSchema(User::class);

// Specify the schema (you can play with this here: https://platform.openai.com/playground/chat?models=gpt-4o)
$responseFormat = [
    'type' => 'json_schema',
    'json_schema' => $schema->getSchema()
];

$prompt = 'Generate an example user and return based on the input schema with the name ' . $schema->getName();
$model = 'gpt-4o';
$temperature = 0.5;

$answer = $myChatClient->chat($model, $temperature, $prompt, $responseFormat);

// Deserialize from the response :)
$user = $serializer->deserialize($answer, User::class, 'json');

// Done, ready to use your example user object!


declare(strict_types=1);

use Opctim\ChatGpt\SchemaGenerator\Attribute\Excluded;

class User
{
    #[Excluded]
    private int $id;
    
    /**
     * This will be ignored too!
     * 
     * @internal 
     */
    private int $someNumber;
    
    // [...]
}


declare(strict_types=1);

use Opctim\ChatGpt\SchemaGenerator\Attribute\Excluded;

#[Excluded]
class User
{
    // [...]
}


declare(strict_types=1);

use Opctim\ChatGpt\SchemaGenerator\Attribute\Excluded;

class User
{
    private Address|Account $addressOrAccount;
}



use Opctim\ChatGpt\SchemaGenerator\Generator;
use Opctim\ChatGpt\SchemaGenerator\Tests\Fixtures\Dto\User;

$schema = $this->generator->generateSchema(User::class);

$schema->getName(); // Returns the name of the schema, to be referenced in your custom ChatGPT prompt

$schema->getSchema(); // Returns the schema as array
$schema['name']; // The schema can also be accessed as an array

$schema->getJson(); // Returns the same as (string)$schema

echo (string)$schema;