如何将CHATGPT 整合到WordPress上使用

CHATGPT出来有一段时间了,一直想琢磨怎么在我们网站上使用CHATGPT, https://www.3cseller.com/

 

使用WordPress Ajax 请求https://api.openai.com/v1/chat/completions返回openai结果,做一个chatgpt在线问答功能

 

  1.  
    function openai_chat_request() {
  2.  
    $content = $_POST['content'];
  3.  
     
  4.  
     
  5.  
    $url = 'https://api.openai.com/v1/chat/completions';
  6.  
    $api_key = '你的key';
  7.  
     
  8.  
    $headers = [
  9.  
    'Accept: application/json',
  10.  
    'Content-Type: application/json',
  11.  
    'Authorization: Bearer ' . $api_key
  12.  
    ];
  13.  
     
  14.  
    $data = array(
  15.  
    'model' => 'gpt-3.5-turbo',
  16.  
    'messages' => array(
  17.  
    array(
  18.  
    'role' => 'user',
  19.  
    'content' => $content,
  20.  
    ),
  21.  
    ),
  22.  
    );
  23.  
     
  24.  
    $ch = curl_init();
  25.  
    curl_setopt($ch, CURLOPT_URL, $url);
  26.  
    curl_setopt($ch, CURLOPT_POST, 1);
  27.  
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  28.  
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  29.  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  30.  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  31.  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  32.  
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  33.  
     
  34.  
    $response = curl_exec($ch);
  35.  
     
  36.  
    if (curl_errno($ch)) {
  37.  
    echo 'Error: '.curl_error($ch);
  38.  
    } else {
  39.  
    $json = json_decode($response, true);
  40.  
    $content = $json['choices'][0]['message']['content'];
  41.  
     
  42.  
    echo $content;
  43.  
    }
  44.  
     
  45.  
    curl_close($ch);
  46.  
    wp_die();
  47.  
    }
  48.  
     
  49.  
    add_action('wp_ajax_openai_chat_request', 'openai_chat_request');
  50.  
    add_action('wp_ajax_nopriv_openai_chat_request', 'openai_chat_request');
  1.  
    <form id="my-form">
  2.  
    <input type="text" id="my-input">
  3.  
    <button type="submit">提交</button>
  4.  
    </form>
  1.  
    jQuery(document).ready(function($) {
  2.  
     
  3.  
    // 当表单提交时执行
  4.  
    $('#my-form').on('submit', function(event) {
  5.  
    event.preventDefault();
  6.  
     
  7.  
    // 获取输入内容
  8.  
    var inputContent = $('#my-input').val();
  9.  
  10.  
    // 发送Ajax请求
  11.  
    $.ajax({
  12.  
    url: ajaxurl,
  13.  
    type: 'post',
  14.  
    dataType: 'json',
  15.  
    data: {
  16.  
    action: 'openai_chat_request',
  17.  
    inputContent: inputContent
  18.  
    },
  19.  
    success: function(response) {
  20.  
    // 处理响应
  21.  
    console.log(response);
  22.  
    },
  23.  
    error: function(xhr, status, error) {
  24.  
    // 处理错误
  25.  
    console.log(error);
  26.  
    }
  27.  
    });
  28.  
    });
  29.  
     
  30.  
    });

 

posted @ 2023-06-11 11:48  hilong911  阅读(183)  评论(0编辑  收藏  举报