-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrok.php
More file actions
77 lines (67 loc) · 2.26 KB
/
grok.php
File metadata and controls
77 lines (67 loc) · 2.26 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
<?php
require 'vendor/autoload.php'; // 确保已安装 Guzzle
use GuzzleHttp\Client;
function chat_with_model($content,$token)
{
$client = new Client([
'base_uri' => 'https://api.x.ai',
'stream' => true, // 使用流式响应
'timeout' => 6000,
]);
$messages = [
['role' => 'system', 'content' => $content],
];
$count = 0;
$response = $client->post('/api/chat', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.$token
],
'json' => [
'model' => 'grok-beta',
'messages' => $messages,
'stream' => true,
],
'stream' => true,
]);
$buffer = '';
$body = $response->getBody();
if (ob_get_level() > 0) {
ob_flush();
}
flush();
$assistant_response = '';
while (! $body->eof()) {
$chunk = $buffer.$body->read(1024); // 每次读取 1024 字节
if ($chunk) {
$datas = explode("}\n", $chunk);
foreach ($datas as $data) {
$message_json = json_decode($data.'}', true);
if ($message_json) {
$message = $message_json['message']['content'] ?? '';
echo "data: " . json_encode(['content' => $message]) . "\n\n";
$assistant_response .= $message;
if (ob_get_level() > 0) {
ob_flush();
}
flush(); // 发送输出到浏览器或终端
}
}
if ($datas) {
$last_match_end = strlen($chunk) - strlen(end($datas));
$buffer = substr($chunk, $last_match_end);
} else {
$buffer = $chunk;
}
}
}
// 将助手响应添加到对话历史
$messages[] = ['role' => 'assistant', 'content' => $assistant_response];
$count++;
}
$content = $_GET['content'];
$token = $_GET['token'];
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
chat_with_model($content,$token);