用PHP写一段代码代码作用是通过GPT的API生成一篇500字文章判断生成的内容中是否有exceeded your current quota和key is associated with a deactivated account如果有就用当前目录中atxt文件的第一行内容替换掉ai_article_gptphp文件的第14行内容替换后删除atxt的第一行内容
以下是用PHP编写的代码,实现了根据GPT的API生成一篇500字文章,并对生成的内容进行判断和替换操作:
<?php
// 获取当前目录中a.txt文件的第一行内容
$aFile = fopen("a.txt", "r");
$replacement = fgets($aFile);
fclose($aFile);
// 调用GPT的API生成一篇500字文章
$apiKey = "YOUR_API_KEY";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.openai.com/v1/engines/davinci-codex/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{
"prompt": "Write a 500-word article.",
"max_tokens": 500
}',
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . $apiKey
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// 判断生成的内容中是否包含特定的提示信息
if (strpos($response, "exceeded your current quota") !== false || strpos($response, "key is associated with a deactivated account") !== false) {
// 替换ai_article_gpt.php文件的第14行内容
$filename = "ai_article_gpt.php";
$lines = file($filename);
$lines[13] = '$apiKey = "' . $replacement . '";' . PHP_EOL;
file_put_contents($filename, implode('', $lines));
// 删除a.txt的第一行内容
$content = file_get_contents("a.txt");
$newContent = substr($content, strpos($content, "\n") + 1);
file_put_contents("a.txt", $newContent);
echo "Replaced and deleted successfully.";
} else {
echo "No replacement needed.";
}
}
?>
请确保将代码中的YOUR_API_KEY替换为您自己的GPT API密钥,并将该代码保存为generate_article.php文件。
此代码首先从a.txt文件中读取第一行内容,然后使用GPT的API生成一篇500字的文章。接下来,它会检查生成的内容中是否包含"exceeded your current quota"或"key is associated with a deactivated account"这两个提示信息。如果存在这些提示信息,它将使用a.txt文件的第一行内容替换ai_article_gpt.php文件的第14行,并删除a.txt的第一行内容。如果不存在这些提示信息,则不进行替换操作。
请确保在运行此代码之前,将a.txt文件放置在与generate_article.php相同的目录中,并在a.txt的第一行中填写要替换的内容
原文地址: http://www.cveoy.top/t/topic/hU4T 著作权归作者所有。请勿转载和采集!