如何将CHATGPT 整合到WordPress上使用
CHATGPT出来有一段时间了,一直想琢磨怎么在我们网站上使用CHATGPT, https://www.3cseller.com/
使用WordPress Ajax 请求https://api.openai.com/v1/chat/completions返回openai结果,做一个chatgpt在线问答功能
-
function openai_chat_request() {
-
$content = $_POST['content'];
-
-
-
$url = 'https://api.openai.com/v1/chat/completions';
-
$api_key = '你的key';
-
-
$headers = [
-
'Accept: application/json',
-
'Content-Type: application/json',
-
'Authorization: Bearer ' . $api_key
-
];
-
-
$data = array(
-
'model' => 'gpt-3.5-turbo',
-
'messages' => array(
-
array(
-
'role' => 'user',
-
'content' => $content,
-
),
-
),
-
);
-
-
$ch = curl_init();
-
curl_setopt($ch, CURLOPT_URL, $url);
-
curl_setopt($ch, CURLOPT_POST, 1);
-
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
-
-
$response = curl_exec($ch);
-
-
if (curl_errno($ch)) {
-
echo 'Error: '.curl_error($ch);
-
} else {
-
$json = json_decode($response, true);
-
$content = $json['choices'][0]['message']['content'];
-
-
echo $content;
-
}
-
-
curl_close($ch);
-
wp_die();
-
}
-
-
add_action('wp_ajax_openai_chat_request', 'openai_chat_request');
-
add_action('wp_ajax_nopriv_openai_chat_request', 'openai_chat_request');
-
<form id="my-form">
-
<input type="text" id="my-input">
-
<button type="submit">提交</button>
-
</form>
-
jQuery(document).ready(function($) {
-
-
// 当表单提交时执行
-
$('#my-form').on('submit', function(event) {
-
event.preventDefault();
-
-
// 获取输入内容
-
var inputContent = $('#my-input').val();
-
var inputurl = "https://www.3cseller.com/wholesale/scania-vci3-scanner-9.html";
-
// 发送Ajax请求
-
$.ajax({
-
url: ajaxurl,
-
type: 'post',
-
dataType: 'json',
-
data: {
-
action: 'openai_chat_request',
-
inputContent: inputContent
-
},
-
success: function(response) {
-
// 处理响应
-
console.log(response);
-
},
-
error: function(xhr, status, error) {
-
// 处理错误
-
console.log(error);
-
}
-
});
-
});
-
-
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结