<?php
use Cognesy\Messages\Messages;
use Cognesy\Polyglot\Inference\Data\ResponseFormat;
use Cognesy\Polyglot\Inference\Inference;
use Cognesy\Utils\JsonSchema\JsonSchema;
// Define child schemas
$address = JsonSchema::object(
name: 'address',
properties: [
JsonSchema::string('street', 'Street address'),
JsonSchema::string('city', 'City name'),
JsonSchema::string('postal_code', 'Postal/ZIP code'),
JsonSchema::string('country', 'Country name'),
],
requiredProperties: ['street', 'city', 'postal_code', 'country'],
);
$contact = JsonSchema::object(
name: 'contact',
properties: [
JsonSchema::string('email', 'Email address'),
JsonSchema::string('phone', 'Phone number', nullable: true),
],
requiredProperties: ['email', 'phone'],
);
$hobbies = JsonSchema::array(
name: 'hobbies',
description: 'List of user hobbies',
itemSchema: JsonSchema::object(
properties: [
JsonSchema::string('name', 'Hobby name'),
JsonSchema::string('description', 'Hobby description', nullable: true),
JsonSchema::integer('years_experience', 'Years of experience', nullable: true),
],
requiredProperties: ['name', 'description', 'years_experience'],
),
);
// Compose the parent schema
$userSchema = JsonSchema::object(
properties: [
JsonSchema::string('name', 'User\'s full name'),
JsonSchema::integer('age', 'User\'s age'),
$address,
$contact,
$hobbies,
JsonSchema::enum('status', 'Account status', enumValues: ['active', 'inactive', 'pending']),
],
requiredProperties: ['name', 'age', 'address', 'contact', 'hobbies', 'status'],
);
// Use the schema with Inference
$userData = Inference::using('openai')
->with(
messages: Messages::fromArray([
['role' => 'user', 'content' => 'Generate a profile for John Doe who lives in New York.'],
]),
responseFormat: ResponseFormat::jsonSchema(
schema: $userSchema->toJsonSchema(),
name: 'user_profile',
strict: true,
),
)
->asJsonData();
print_r($userData);
// @doctest id="c025"