-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructured_outputs.php
More file actions
179 lines (152 loc) · 5.44 KB
/
Copy pathstructured_outputs.php
File metadata and controls
179 lines (152 loc) · 5.44 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?php
/**
* This file is part of the xAI PHP SDK.
*
* (c) 2026 Displace Technologies, LLC
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* This work was inspired by X.AI LLC's Python SDK.
*
* Structured Outputs Example
* ==========================
*
* This example demonstrates how to get structured (JSON) outputs from the xAI API.
* You can define a JSON schema for the expected response format, and the model
* will return data matching that schema.
*
* Usage:
* php examples/structured_outputs.php
*
* Requirements:
* - Set the XAI_API_KEY environment variable
*/
declare(strict_types=1);
require_once dirname(__DIR__) . '/vendor/autoload.php';
use Displace\XaiSdk\XaiClient;
use function Displace\XaiSdk\Chat\image;
use function Displace\XaiSdk\Chat\system;
use function Displace\XaiSdk\Chat\user;
// Parse command line arguments
$options = getopt('', ['help']);
if (isset($options['help'])) {
echo <<<HELP
xAI PHP SDK - Structured Outputs Example
Usage: php examples/structured_outputs.php
This example demonstrates extracting structured data from an image of a receipt.
The model will return JSON matching a defined schema.
Environment:
XAI_API_KEY Your xAI API key (required)
HELP;
exit(0);
}
// Create the client
try {
$client = new XaiClient();
} catch (RuntimeException $e) {
echo "Error: {$e->getMessage()}\n";
echo "Please set the XAI_API_KEY environment variable.\n";
exit(1);
}
echo "xAI Structured Outputs Example\n";
echo "==============================\n\n";
// Define the JSON schema for the receipt
$receiptSchema = [
'type' => 'json_schema',
'json_schema' => [
'name' => 'receipt',
'strict' => true,
'schema' => [
'type' => 'object',
'properties' => [
'date' => [
'type' => 'string',
'description' => 'The date of the receipt in ISO 8601 format',
],
'items' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'name' => [
'type' => 'string',
'description' => 'Name of the item',
],
'quantity' => [
'type' => 'integer',
'description' => 'Quantity purchased',
],
'price_in_cents' => [
'type' => 'integer',
'description' => 'Price in cents',
],
],
'required' => ['name', 'quantity', 'price_in_cents'],
'additionalProperties' => false,
],
],
'currency' => [
'type' => 'string',
'description' => 'Currency code (e.g., USD, EUR)',
],
'total_in_cents' => [
'type' => 'integer',
'description' => 'Total amount in cents',
],
],
'required' => ['date', 'items', 'currency', 'total_in_cents'],
'additionalProperties' => false,
],
],
];
// Create chat with vision model and structured output format
$chat = $client->chat->create(
model: 'grok-2-vision',
messages: [
system('You are an expert at extracting information from receipts. You pay great attention to detail. Always respond with valid JSON matching the provided schema.'),
],
responseFormat: $receiptSchema,
);
// Sample receipt image
$receiptImageUrl = 'https://images.pexels.com/photos/13431759/pexels-photo-13431759.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2';
echo "Analyzing receipt image...\n\n";
// Add the user message with the image
$chat->append(
user(
'Extract the information contained in this receipt.',
image($receiptImageUrl, 'high'),
),
);
try {
$response = $chat->sample();
$content = $response->getContent();
echo "Raw Response:\n";
echo "{$content}\n\n";
// Parse the JSON response
$receipt = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
echo "Parsed Receipt:\n";
echo "---------------\n";
echo "Date: {$receipt['date']}\n\n";
echo "Items:\n";
foreach ($receipt['items'] as $item) {
$price = number_format($item['price_in_cents'] / 100, 2);
echo " {$item['quantity']}x {$item['name']} - {$price} {$receipt['currency']}\n";
}
$total = number_format($receipt['total_in_cents'] / 100, 2);
echo "\nTotal: {$total} {$receipt['currency']}\n";
echo "\n---------------\n";
echo "Usage:\n";
echo " Prompt tokens: {$response->usage->promptTokens}\n";
echo " Completion tokens: {$response->usage->completionTokens}\n";
echo " Total tokens: {$response->usage->totalTokens}\n";
} catch (JsonException $e) {
echo "Error parsing JSON response: {$e->getMessage()}\n";
exit(1);
} catch (Displace\XaiSdk\Exceptions\XaiException $e) {
echo "\nError: {$e->getMessage()}\n";
if ($e->getHttpStatusCode() !== null) {
echo "HTTP Status: {$e->getHttpStatusCode()}\n";
}
exit(1);
}