Skip to content

Commit 1828384

Browse files
committed
feat: add cls sse example
1 parent 3077662 commit 1828384

1 file changed

Lines changed: 120 additions & 0 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<?php
2+
require_once __DIR__.'/../../../vendor/autoload.php';
3+
// 导入对应产品模块的client
4+
use TencentCloud\Cls\V20201016\ClsClient;
5+
// 导入要请求接口对应的Request类
6+
use TencentCloud\Cls\V20201016\Models\ChatCompletionsRequest;
7+
use TencentCloud\Cls\V20201016\Models\Message;
8+
use TencentCloud\Cls\V20201016\Models\MetadataItem;
9+
10+
use TencentCloud\Common\Exception\TencentCloudSDKException;
11+
use TencentCloud\Common\Credential;
12+
// 导入可选配置类
13+
use TencentCloud\Common\Profile\ClientProfile;
14+
use TencentCloud\Common\Profile\HttpProfile;
15+
16+
17+
function streamProcessResult($chunk)
18+
{
19+
// 解析原始 SSE 文本块,提取 event 和 data 字段
20+
$event = '';
21+
$data = '';
22+
foreach (explode("\n", trim($chunk)) as $line) {
23+
if (str_starts_with($line, 'event:')) {
24+
$event = trim(substr($line, 6));
25+
} elseif (str_starts_with($line, 'data:')) {
26+
$data = trim(substr($line, 5));
27+
}
28+
}
29+
30+
// 跳过心跳等 data 为空的事件(如服务端每隔一段时间发送的 :heartbeat 注释)
31+
if (!$data) return;
32+
33+
// 服务端通过 event: error 返回应用层错误
34+
if ($event === 'error') {
35+
$err = json_decode($data, true);
36+
fwrite(STDERR, "\n[流式] error " . json_encode($err['Response']['Error'], JSON_UNESCAPED_UNICODE) . PHP_EOL);
37+
return;
38+
}
39+
40+
// 实时输出内容
41+
$parsed = json_decode($data, true);
42+
foreach (($parsed['Choices'] ?? []) as $choice) {
43+
// 实时输出思考过程(ReasoningContent)
44+
if (!empty($choice['Delta']['ReasoningContent'])) {
45+
echo $choice['Delta']['ReasoningContent'];
46+
}
47+
// 实时输出回复内容(Content)
48+
if (!empty($choice['Delta']['Content'])) {
49+
echo $choice['Delta']['Content'];
50+
}
51+
}
52+
}
53+
54+
try {
55+
// 实例化一个证书对象,入参需要传入腾讯云账户secretId,secretKey
56+
// $cred = new Credential("【secretId】", "【secretKey】");
57+
$cred = new Credential(getenv("TENCENTCLOUD_SECRET_ID"),
58+
getenv("TENCENTCLOUD_SECRET_KEY"));
59+
60+
// 实例化一个http选项,可选的,没有特殊需求可以跳过
61+
$httpProfile = new HttpProfile();
62+
$httpProfile->setReqMethod("POST"); // post请求(默认为post请求)
63+
$httpProfile->setReqTimeout(300); // 流式接口可能耗时较长,因此将请求超时时间设置为 300 秒
64+
// 通过SSE流式调用此接口时,请务必设置请求域名(Endpoint)为 cls.ai.tencentcloudapi.com
65+
$httpProfile->setEndpoint("cls.ai.tencentcloudapi.com");
66+
67+
// 实例化一个client选项,可选的,没有特殊需求可以跳过
68+
$clientProfile = new ClientProfile();
69+
$clientProfile->setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256)
70+
$clientProfile->setHttpProfile($httpProfile);
71+
72+
// 实例化要请求产品的client对象,clientProfile是可选的
73+
$client = new ClsClient($cred, "ap-guangzhou", $clientProfile);
74+
75+
// 构造请求参数
76+
$req = new ChatCompletionsRequest();
77+
// 指定要使用的功能,例如 "text2sql"
78+
$req->Model = "text2sql";
79+
80+
// 设置对话消息,角色为 "user",内容为用户的提问
81+
$message = new Message();
82+
$message->Role = "user";
83+
$message->Content = "状态码200, 统计日志条数";
84+
$req->Messages = [$message];
85+
86+
// 设置元数据,传递日志主题地域和日志主题 ID
87+
$metaRegion = new MetadataItem();
88+
$metaRegion->Key = "topic_region";
89+
$metaRegion->Value = "ap-guangzhou";
90+
91+
$metaTopicId = new MetadataItem();
92+
$metaTopicId->Key = "topic_id";
93+
$metaTopicId->Value = "xxxxxxxx-xxxx";
94+
95+
$req->Metadata = [$metaRegion, $metaTopicId];
96+
97+
98+
// 3. 流式调用
99+
// CLS ChatCompletions 同时支持流式和非流式两种模式。
100+
// 将 Stream 参数设置为 true,表示以流式方式获取响应。
101+
$req->Stream = true;
102+
// 如果响应是SSE-event流,可以设置回调函数逐个处理事件流,否则一次返回所有响应内容
103+
$client->setSseResponseCallbackFunc('streamProcessResult');
104+
$client->ChatCompletions($req);
105+
echo PHP_EOL;
106+
echo '[流式] 完成,开始非流式调用...' . PHP_EOL;
107+
108+
// 4. 非流式调用
109+
// 通过 Stream=false 参数来指定非 stream 协议,一次性拿到结果。
110+
$client->setSseResponseCallbackFunc(null);
111+
$req->Stream = false;
112+
$resp = $client->ChatCompletions($req);
113+
if (!empty($resp->Choices[0]->Message->ReasoningContent)) {
114+
echo "思考过程:" . $resp->Choices[0]->Message->ReasoningContent . PHP_EOL;
115+
}
116+
echo "[非流式] 回复内容:" . PHP_EOL . $resp->Choices[0]->Message->Content . PHP_EOL;
117+
118+
} catch (TencentCloudSDKException $e) {
119+
echo $e;
120+
}

0 commit comments

Comments
 (0)