A lightweight PHP library for generating JSON Schemas from PHP models, inspired by Python's Pydantic. Ideal for integrating with OpenAI structured outputs, function calling, or any other JSON-schema–driven tooling.
- Automatic Type Inference: Infers JSON Schema types from PHP property types (
int,float,string,bool). - Nullable Support: Handles nullable types (e.g.,
?string) astype: ["string", "null"]. - Nested Models & Arrays: Supports nested
BaseModeland arrays of models via@var ModelName[]annotations. - Property Descriptions: Leverage
@Descriptiontags in docblocks to include descriptions in schemas. - Strict Mode: Generate strict schemas for OpenAI function calling or JSON validation.
- PHP 8.0 or higher
- Composer
Install via Composer:
composer require mertcanekiz/phpydanticExtend Phpydantic\BaseModel and declare public properties. Use docblocks for metadata:
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;
}Use static methods to generate schema definitions:
// Returns schema as PHP array
$schemaArray = MathReasoning::schema();
// Returns pretty-printed JSON string
$schemaJson = MathReasoning::jsonSchema();Example JSON Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MathReasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": { "$ref": "#/definitions/Step" }
},
"finalAnswer": { "type": "string" }
},
"required": ["steps", "finalAnswer"],
"additionalProperties": false
}Generate schemas compatible with OpenAI function calling or JSON mode:
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']Use fromJson to create model instances from JSON strings:
$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;The fromJson method handles:
- Nested model deserialization
- Arrays of models
- Type casting for primitive values
- Nullable properties
- JSON validation
| Method | Description |
|---|---|
::schema(): array |
Returns schema as a PHP array. |
::jsonSchema(): string |
Returns pretty-printed JSON schema. |
::openAiSchema(): array |
Wraps schema() for OpenAI function-calling compatibility. |
::fromJson(string): static |
Creates a model instance from a JSON string. |
Run PHPUnit tests:
composer testContributions are welcome! Please follow these steps:
- Fork the repository
- Create a new branch:
git checkout -b feature/YourFeature - Commit your changes:
git commit -m 'Add new feature' - Push to your branch:
git push origin feature/YourFeature - Open a Pull Request
Ensure all tests pass and adhere to PSR-12 coding standards.
This project is licensed under the MIT License. See the LICENSE file for details.