<?php error_reporting(E_ALL); ini_set('display_errors', '1'); set_time_limit(100);

$key = isset($_POST['key'])?$_POST['key']:''; $content = isset($_POST['content'])?$_POST['content']:'';

if ($key === '') { echo '请输入chatgpt 的key,例如:sk-Mn1UJ4TcPrKDCYMwkR7VT3BlbkFJq9ioSM7y5gwuwEB****'; exit; }

function json_output($str) { return str_replace("\n", "<br>", $str); }

$response = get_ai_article($content, $key);

$data_ret = json_decode($response, true);

if (isset($data_ret['choices'])) { $answer = $data_ret['choices'][0]['message']['content']; } else { if ($data_ret['error']["message"]) { $answer = $data_ret['error']["message"]; } else { $answer = 'ai写作模块出现错误.'; } }

$answer = ltrim($answer, "\r"); $answer = ltrim($answer, "\n");

echo json_output($answer);

function get_ai_article($content, $key) { $post_data = array( 'model'=>'gpt-3.5-turbo', 'messages'=>array(array( 'role'=>'user', 'content'=>$content)) );

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

$headers = array();
$headers[] = 'Authorization: Bearer '.$key;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

return $result;

} ?>

<form method="post"> <label for="key">ChatGPT API 密钥:</label> <input type="text" id="key" name="key" required> <br> <label for="content">文章内容:</label> <textarea id="content" name="content" rows="10" required> </textarea> <br> <input type="submit" value="生成文章"> </form>

<textarea id="result" rows="10" readonly> </textarea>

<script> document.addEventListener('DOMContentLoaded', function() { const resultTextarea = document.getElementById('result'); const form = document.querySelector('form');

form.addEventListener('submit', function(event) {
  event.preventDefault();
  const key = document.getElementById('key').value;
  const content = document.getElementById('content').value;

  fetch('/your-script-path.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'key=' + encodeURIComponent(key) + '&content=' + encodeURIComponent(content)
  })
  .then(response => response.text())
  .then(data => {
    resultTextarea.value = data;
  })
  .catch(error => {
    console.error('Error:', error);
    resultTextarea.value = '生成文章失败';
  });
});

}); </script>

ChatGPT API PHP 代码:使用 ChatGPT 生成文章 - 免费在线工具

原文地址: https://www.cveoy.top/t/topic/pT8n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录