我做了个简易对话代码html,api.php源码。回复比较缓慢自己优化一下
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>百度文心 API 测试</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
}
#chat-container {
flex: 1;
overflow-y: auto;
padding: 10px;
}
.message {
margin: 5px 0;
padding: 10px;
border-radius: 5px;
word-wrap: break-word;
}
.user {
background-color: #e0f7fa;
text-align: right;
}
.bot {
background-color: #f1f8e9;
display: block; /* 确保元素可见 */
}
.error {
color: red;
font-style: italic;
}
#input-container {
display: flex;
padding: 10px;
border-top: 1px solid #ccc;
}
#input-field {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
#send-button {
margin-left: 10px;
padding: 10px 20px;
background-color: #2196f3;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
#new-conversation-button {
position: fixed;
bottom: 70px;
right: 20px;
padding: 10px 20px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="chat-container">
<!-- 聊天消息将显示在这里 -->
</div>
<div id="input-container">
<input type="text" id="input-field" placeholder="输入你的问题">
<button id="send-button">发送</button>
</div>
<button id="new-conversation-button">新建对话</button>
<script>
const chatContainer = document.getElementById('chat-container');
const inputField = document.getElementById('input-field');
const sendButton = document.getElementById('send-button');
const newConversationButton = document.getElementById('new-conversation-button');
let history = [];
sendButton.addEventListener('click', sendMessage);
inputField.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
sendMessage();
}
});
newConversationButton.addEventListener('click', function () {
history = [];
chatContainer.innerHTML = '';
});
function sendMessage() {
const message = inputField.value.trim();
if (message === '') return;
// 显示用户消息
const userMessage = document.createElement('div');
userMessage.classList.add('message', 'user');
userMessage.textContent = message;
chatContainer.appendChild(userMessage);
// 清空输入框
inputField.value = '';
// 发送请求到后端
const data = {
message: message,
history: history
};
fetch('api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(result => {
console.log('Received response:', result);
// 验证响应格式
if (!result || typeof result.response !== 'string') {
throw new Error('Invalid response format');
}
// 显示机器人回复
const botMessage = document.createElement('div');
botMessage.classList.add('message', 'bot');
botMessage.textContent = result.response; // 自动解码Unicode转义
chatContainer.appendChild(botMessage);
// 更新历史记录
history.push({ role: 'user', content: message });
history.push({ role: 'assistant', content: result.response });
})
.catch(error => {
console.error('Error:', error);
// 显示错误提示
const errorMessage = document.createElement('div');
errorMessage.classList.add('message', 'bot', 'error');
errorMessage.textContent = `错误:${error.message}`;
chatContainer.appendChild(errorMessage);
});
}
</script>
</body>
</html>
<?php
// 设置编码
header('Content-Type: application/json; charset=utf-8');
// 允许跨域请求
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
// 百度文心 API 相关配置
// 百度文心 API 相关配置
$apiKey = 'xxxxxxxx';
$secretKey = 'xxxxxxxx';
$apiUrl = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro';
function getAccessToken($apiKey, $secretKey)
{
$curl = curl_init();
$postData = array(
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey
);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query($postData)
));
$response = curl_exec($curl);
if ($response === false) {
$error = curl_error($curl);
error_log('Curl error when getting access token: '. $error);
curl_close($curl);
return null;
}
curl_close($curl);
$rtn = json_decode($response);
if ($rtn === null ||!isset($rtn->access_token)) {
error_log('Failed to get access token. Response: '. $response);
return null;
}
return $rtn->access_token;
}
// 获取用户输入和历史记录
$input = json_decode(file_get_contents('php://input'), true);
if ($input === null) {
http_response_code(400);
echo json_encode(['error' => 'Invalid input data']);
exit;
}
$message = $input['message'];
$history = $input['history'];
// 构建请求数据
$accessToken = getAccessToken($apiKey, $secretKey);
if ($accessToken === null) {
http_response_code(500);
echo json_encode(['error' => 'Failed to get access token']);
exit;
}
$requestData = [
'messages' => array_merge($history, [
[
'role' => 'user',
'content' => $message
]
]),
'temperature' => 0.8,
'top_p' => 0.8,
'max_output_tokens' => 1024,
'response_format' => 'text'
];
// 发送请求到百度文心 API
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $apiUrl . "?access_token={$accessToken}",
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($requestData),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
)
));
$response = curl_exec($curl);
if ($response === false) {
error_log('Curl error when sending request to API: '. curl_error($curl));
http_response_code(500);
echo json_encode(['error' => 'Failed to send request to API']);
exit;
}
curl_close($curl);
// 解析响应
$result = json_decode($response, true);
if ($result === null) {
error_log('Failed to decode API response: '. $response);
http_response_code(500);
echo json_encode(['error' => 'Failed to decode API response']);
exit;
}
$botResponse = $result['result'];
// 返回响应给前端
echo json_encode([
'response' => $botResponse
]);
?>
今天做了个百度的ERNIE对接,搞了一小时才弄懂
首先要去创建应用
然后再把应用的对接信息填进去
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容