Overview

Instructor has a built-in support for generating JSON Schema from the classes or objects. This is useful as it helps you avoid writing the JSON Schema manually, which can be error-prone and time-consuming.

Example

<?php
require 'examples/boot.php';

use Cognesy\Instructor\Features\Schema\Factories\SchemaFactory;
use Cognesy\Polyglot\LLM\Enums\Mode;
use Cognesy\Polyglot\LLM\Inference;

class City {
    public string $name;
    public int $population;
    public int $founded;
}

$schema = (new SchemaFactory)->schema(City::class);

$data = (new Inference)
    ->withConnection('openai')
    ->create(
        messages: [['role' => 'user', 'content' => 'What is capital of France? \
        Respond with JSON data.']],
        responseFormat: [
            'type' => 'json_schema',
            'description' => 'City data',
            'json_schema' => [
                'name' => 'city_data',
                'schema' => $schema->toJsonSchema(),
                'strict' => true,
            ],
        ],
        options: ['max_tokens' => 64],
        mode: Mode::JsonSchema,
    )
    ->toJson();

echo "USER: What is capital of France\n";
echo "ASSISTANT:\n";
dump($data);

?>