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);
- }
- });
- });
- });
标签:ch,setopt,chat,openai,整合,WordPress,CHATGPT,curl,CURLOPT From: https://www.cnblogs.com/chinait666/p/17472750.html