Introducing an Object-Oriented JSON Schema Builder for PHP

Hi!
The ChatGPT API provides a very powerful instrument called tools, but building a JSON schema for it is extremely difficult and involves a lot of extra work. My library 021/json-schema allows you to minimize the amount of work on building it and avoid unwanted errors. It also adds hints to the IDE.

For comparison, this is what the building tools scheme looks like without my library:

$weather = [
    'type' => 'function',
    'function' => [
        'name' => 'get_current_weather',
        'description' => 'Get the current weather for a location',
        'properties' => [
            'location' => [
                'type' => 'string',
                'description' => 'The city and state, e.g. San Francisco, CA'
            ],
            'unit' => [
                'type' => 'string',
                'enum' => ['celsius', 'fahrenheit'],
            ]
        ],
    ]
];
$tools[] = $weather;

And with:

use O21\JsonSchema\Schema;
use O21\JsonSchema\Enums\Type;

$weather = [
    'type' => 'function',
    'function' => (new Schema(
        type: Type::OBJECT,
        properties: [
            'location' => new Schema(
                type: Type::STRING,
                description: 'The city and state, e.g. San Francisco, CA'
            ),
            'unit' => new Schema(
                type: Type::STRING,
                enum: ['celsius', 'fahrenheit']
            )
        ],
        transform: function (stdClass $schema) {
            $schema->name = 'get_current_weather';
            $schema->description = 'Get the current weather in a given location';
        }
    ))->toObject()
];
$tools[] = $weather;

Enjoy using it and give it stars :star:

1 Like

Using arrays in PHP is far more efficient. It seems like you’re solving a problem you’ve created yourself. But hey best of luck.

For simple cases, it might be better to use arrays, but for large schemes, using arrays can make the code very difficult to maintain and cause additional problems, because it is easy to get confused in large levels of nesting. For example, here’s what a schema build looks like in the IDE with objects and arrays:


The second option is much more difficult to read, and it is only one function. In addition, the object-oriented approach helps to avoid errors when writing, since all available keys are suggested by the IDE.

By creating tools, tool and function classes we can get well-maintained code instead of a large number of arrays