WordPress接入openAI
为了实现一个WordPress页面模板,你需要创建一个PHP文件并将其保存在你的主题目录中。以下是一个简单的示例,展示了如何通过HTML、PHP和JavaScript调用OpenAI API来实现人机对话。在这个例子中,我们将使用jQuery和Axios库来处理API请求。请注意,这个例子仅用于演示目的,并不是一个完整的、安全的解决方案。你可能需要根据你的需求和环境进一步优化和调整代码。
在你的WordPress主题目录中,创建一个名为openai-chat.php
的文件,并添加以下内容:
<?php
/*
Template Name: OpenAI Chat
*/
get_header();
?>
<div class="container">
<h1>OpenAI Chatbot</h1>
<div class="chat-container">
<div class="chat-output" id="chat-output"></div>
<div class="chat-input">
<input type="text" id="user-input" placeholder="Type your message here...">
<button id="send-button">Send</button>
</div>
</div>
</div>
<?php
wp_enqueue_script('jquery');
wp_enqueue_script('axios', 'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js');
?>
<script>
jQuery(document).ready(function($) {
const chatOutput = $('#chat-output');
const userInput = $('#user-input');
const sendButton = $('#send-button');
sendButton.click(async function() {
const message = userInput.val();
if (!message) return;
userInput.val('');
appendMessage('User', message);
sendButton.prop('disabled', true);
try {
const response = await axios.post('/wp-json/openai/v1/chat', {
message: message
});
appendMessage('Chatbot', response.data.response);
} catch (error) {
console.error('Error:', error);
appendMessage('Chatbot', 'An error occurred. Please try again.');
} finally {
sendButton.prop('disabled', false);
}
});
function appendMessage(sender, message) {
chatOutput.append(`<div class="chat-message ${sender.toLowerCase()}"><strong>${sender}:</strong> ${message}</div>`);
}
});
</script>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 1rem;
}
.chat-container {
border: 1px solid #ccc;
padding: 1rem;
margin-bottom: 1rem;
}
.chat-output {
max-height: 400px;
overflow-y: auto;
margin-bottom: 1rem;
}
.chat-input {
display: flex;
}
.chat-input input {
flex-grow: 1;
border: 1px solid #ccc;
padding: 0.5rem;
border-radius: 5px 0 0 5px;
}
.chat-input button {
background-color: #0073aa;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 0 5px 5px 0;
cursor: pointer;
}
.chat-input button:hover {
background-color: #0096db;
}
.chat-message {
margin-bottom: 0.5rem;
}
.chat-message.user {
text-align: right;
}
</style>
<?php
get_footer();
接下来,需要创建一个用于处理API请求的WordPress REST API端点。在你的主题的functions.php
文件中添加以下内容:
// Add this code to your theme's functions.php file.
function openai_chat_endpoint() {
register_rest_route('openai/v1', '/chat', array(
'methods' => 'POST',
'callback' => 'openai_chat_callback',
'permission_callback' => '__return_true',
));
}
add_action('rest_api_init', 'openai_chat_endpoint');
function openai_chat_callback($request) {
$message = $request->get_param('message');
if (!$message) {
return new WP_Error('empty_message', 'Message is empty.', array('status' => 400));
}
$api_key = 'your_openai_api_key'; // Replace with your actual OpenAI API key.
$url = 'https://api.openai.com/v1/engines/davinci-codex/completions';
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key,
);
$body = json_encode(array(
'prompt' => $message,
'max_tokens' => 50,
'n' => 1,
'stop' => null,
'temperature' => 0.7,
));
$response = wp_remote_post($url, array(
'headers' => $headers,
'body' => $body,
));
if (is_wp_error($response)) {
return $response;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
$chat_response = $body['choices'][0]['text'];
return array(
'response' => $chat_response,
);
}
这段代码首先创建了一个名为openai_chat_endpoint
的函数,用于在WordPress REST API中注册一个名为/openai/v1/chat
的新端点。当用户发送聊天消息时,我们的JavaScript代码将向此端点发送POST请求。openai_chat_callback
函数将处理这些请求并调用OpenAI API以获取聊天响应。
请注意,你需要将your_openai_api_key
替换为你的实际OpenAI API密钥。你还可以根据需要调整其他参数,例如max_tokens
或temperature
。
在完成上述步骤后,你可以在WordPress后台创建一个新页面,并在“页面属性”框中的“模板”下拉菜单中选择“OpenAI Chat”模板。然后,发布页面并在前端查看它。你应该可以看到一个简单的聊天界面,用户可以在其中与基于OpenAI的聊天机器人进行互动。