-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.php
More file actions
236 lines (194 loc) · 5.94 KB
/
chat.php
File metadata and controls
236 lines (194 loc) · 5.94 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<?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.
*
* Basic Chat Example
* ==================
*
* This example demonstrates basic chat functionality with the xAI API.
* It shows how to:
* - Create a client and chat session
* - Have multi-turn conversations
* - Use streaming responses
* - Sample multiple responses at once
*
* Usage:
* php examples/chat.php # Basic chat
* php examples/chat.php --stream # Streaming chat
* php examples/chat.php --n=3 # Multiple responses
* php examples/chat.php --stream --n=3 # Streaming with multiple responses
*
* 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\assistant;
use function Displace\XaiSdk\Chat\system;
use function Displace\XaiSdk\Chat\user;
// Parse command line arguments
$options = getopt('', ['stream', 'n::', 'help', 'test']);
$streaming = isset($options['stream']);
$n = isset($options['n']) ? (int) $options['n'] : 1;
$testMode = isset($options['test']);
if (isset($options['help'])) {
echo <<<HELP
xAI PHP SDK - Chat Example
Usage: php examples/chat.php [OPTIONS]
Options:
--stream Enable streaming responses
--n=<count> Number of responses to generate (default: 1)
--test Run a single test exchange (non-interactive)
--help Show this help message
Environment:
XAI_API_KEY Your xAI API key (required)
Examples:
php examples/chat.php
php examples/chat.php --stream
php examples/chat.php --n=3
php examples/chat.php --stream --n=3
php examples/chat.php --test
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);
}
// Create a chat session with initial messages
$chat = $client->chat->create(
model: 'grok-3',
messages: [
system('You talk like a pirate.'),
user('How are you?'),
assistant('Ahoy! I be doing mighty fine, matey!'),
],
);
echo "xAI Chat Example\n";
echo "================\n";
echo 'Mode: ' . ($streaming ? 'Streaming' : 'Basic') . ($n > 1 ? " (n={$n})" : '') . ($testMode ? ' (test)' : '') . "\n";
// Test mode: run a single exchange and exit
if ($testMode) {
try {
$chat->append(user('Say "Hello, world!" and nothing else.'));
$response = $chat->sample();
echo "Test prompt: Say \"Hello, world!\" and nothing else.\n";
echo "Response: {$response->getContent()}\n";
echo "\nTest passed!\n";
exit(0);
} catch (Displace\XaiSdk\Exceptions\XaiException $e) {
echo "Test failed: {$e->getMessage()}\n";
if ($e->getHttpStatusCode() !== null) {
echo "HTTP Status: {$e->getHttpStatusCode()}\n";
}
exit(1);
}
}
echo "Type 'exit' to quit.\n\n";
/**
* Basic chat without streaming.
*/
function basicChat(Displace\XaiSdk\Chat\Chat $chat): void
{
while (true) {
echo 'You: ';
$prompt = trim((string) fgets(STDIN));
if (strtolower($prompt) === 'exit') {
break;
}
if ($prompt === '') {
continue;
}
// Add user message
$chat->append(user($prompt));
// Get response
$response = $chat->sample();
echo "Grok: {$response->getContent()}\n\n";
// Add assistant response to history
$chat->append($response);
}
}
/**
* Chat with streaming responses.
*/
function chatWithStreaming(Displace\XaiSdk\Chat\Chat $chat): void
{
while (true) {
echo 'You: ';
$prompt = trim((string) fgets(STDIN));
if (strtolower($prompt) === 'exit') {
break;
}
if ($prompt === '') {
continue;
}
// Add user message
$chat->append(user($prompt));
echo 'Grok: ';
// Stream the response
$lastResponse = null;
foreach ($chat->stream() as [$response, $chunk]) {
echo $chunk->content;
$lastResponse = $response;
}
echo "\n\n";
// Add the complete response to history
if ($lastResponse !== null) {
$chat->append($lastResponse);
}
}
}
/**
* Batch chat - generate multiple responses.
*/
function batchChat(Displace\XaiSdk\Chat\Chat $chat, int $n): void
{
while (true) {
echo 'You: ';
$prompt = trim((string) fgets(STDIN));
if (strtolower($prompt) === 'exit') {
break;
}
if ($prompt === '') {
continue;
}
// Add user message
$chat->append(user($prompt));
// Get multiple responses
$responses = $chat->sampleBatch($n);
foreach ($responses as $index => $response) {
echo 'Grok (response ' . ($index + 1) . "): {$response->getContent()}\n";
}
echo "\n";
// Add only the first response to history
$chat->append($responses[0]);
}
}
// Run the appropriate chat mode
try {
match ([$n > 1, $streaming]) {
[false, false] => basicChat($chat),
[false, true] => chatWithStreaming($chat),
[true, false] => batchChat($chat, $n),
[true, true] => batchChat($chat, $n), // Streaming batch not implemented yet
};
} catch (Displace\XaiSdk\Exceptions\XaiException $e) {
echo "\nError: {$e->getMessage()}\n";
if ($e->getHttpStatusCode() !== null) {
echo "HTTP Status: {$e->getHttpStatusCode()}\n";
}
exit(1);
}
echo "Goodbye!\n";