-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmessages_structured_output.php
More file actions
executable file
·63 lines (48 loc) · 1.87 KB
/
messages_structured_output.php
File metadata and controls
executable file
·63 lines (48 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env php
<?php
/**
* Structured Output: Type Inference
*
* This example demonstrates using structured output model classes.
* The SDK automatically infers JSON schema from PHP type hints:
* - string, int, float, bool -> corresponding JSON types
* - ?type (nullable) -> optional field
* - No #[Required] needed for basic fields!
*/
require_once dirname(__DIR__).'/vendor/autoload.php';
use Anthropic\Client;
use Anthropic\Lib\Attributes\Constrained;
use Anthropic\Lib\Concerns\StructuredOutputModelTrait;
use Anthropic\Lib\Contracts\StructuredOutputModel;
// Define a model class - types are automatically inferred
class Person implements StructuredOutputModel
{
use StructuredOutputModelTrait;
#[Constrained(description: 'The person\'s full name')]
public string $name;
#[Constrained(description: 'Age in years')]
public int $age;
public string $occupation; // No attribute needed - type is inferred!
public ?string $email = null; // Nullable = optional field
}
$client = new Client(
apiKey: getenv('ANTHROPIC_API_KEY') ?: 'my-anthropic-api-key'
);
echo "=== Structured Output: Type Inference ===\n\n";
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Generate a profile for a 28-year-old data scientist named Bob with email bob@example.com.']],
model: 'claude-sonnet-4-5-20250929',
outputConfig: ['format' => Person::class] // Pass the class directly!
);
// Get the parsed output as a Person instance
$person = $message->parsedOutput();
if ($person instanceof Person) {
echo "Name: {$person->name}\n";
echo "Age: {$person->age}\n";
echo "Occupation: {$person->occupation}\n";
echo "Email: " . ($person->email ?? 'Not provided') . "\n";
// The model can be serialized back to JSON
echo "\nSerialized back to JSON:\n";
echo $person->toJson() . "\n";
}