PHP对接文心一言

作者:IT技术圈子 浏览量:516   发表于 2024-07-18 09:52 标签:

要在PHP中对接文心一言(Wechaty),您需要使用cURL来发送HTTP请求。以下是一个简单的PHP脚本示例,展示了如何向文心一言发送请求并获取响应:

<?php 
// 文心一言API地址
$apiUrl = 'https://openapi.xfyun.cn/v2/ai_chat'; 
// 请求头部设置
$headers = array(    
'Content-Type: application:json',    
'X-NLS-SecretKey: 你的SecretKey',    
'X-NLS-AccessKey: 你的AccessKey',    
'X-NLS-RequestId: 你的RequestId',    
'X-NLS-ProjectId: 你的ProjectId',
); 
// 请求体
$data = json_encode([    
'query' => '你好', // 用户输入的问题    
'user_id' => '用户ID', // 用户标识]
); 
// 初始化cURL会话
$ch = curl_init($apiUrl); 
// 设置cURL选项
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
// 执行cURL会话
$response = curl_exec($ch); 
// 关闭cURL会话
curl_close($ch); 
// 打印响应结果
$result = json_decode($response, true);
echo $result['result']['response']; 
// 输出文心一言的回答 
?>

确保替换相应的$headers数组中的SecretKey, AccessKey, RequestId, 和 ProjectId为你的文心一言服务的凭证。

这段代码首先定义了API地址和必要的请求头部,然后构建了请求体并初始化了cURL会话。通过cURL选项设置,它将POST请求发送到文心一言API,并接收JSON格式的响应。最后,关闭cURL会话,解析响应并打印文心一言的回答