## 对话聊天API核心代码如下所示
##### 看起来很简单,没什么业务逻辑,就两个参数
>[info]
> $Questionmessage :你给机器人发的消息,仅限文字
$context:你跟机器人对话的内容上下文,每次都会拼接,这样机器人会根据你最近的五条对话来回答你接下来的问题,让机器人看起来显得没那么笨笨的感觉。但是有一个前提,<span style="color:red">这个开启会导致费用增加
</span>返回的结果,需要转string格式。在前面加一个 `(string)` 即可。
```
/**
* @return void
* @throws \Exception
* 消息
*/
public function ChatGPT($Questionmessage, $context = "[]")
{
$open_ai = new OpenAi(config("site.key"));
// 设置默认的请求文本prompt
$prompt = "这是前置内容,每次提交都伴随此,可以改为空\n\n";
$version = "text-davinci-003";
if (empty($context)) {
// 如果没有内容,下面是默认内容
$prompt .= "
Question:\n'我问你个问题,你告诉我答案OK吗?
\n\nAnswer:\n好
\n\n Question:\n'请你输入你的问题
\n\nAnswer:\n 输入问题后可以获取答案
";
$please_use_above = "";
} else {
// 将上次的问题和答案作为问题进行提交
$prompt .= "";
$context = array_slice($context, -5);
foreach ($context as $message) {
$prompt .= "Question:\n" . $message[0] . "\n\nAnswer:\n" . $message[1] . "\n\n";
}
$please_use_above = ". Please use the questions and answers above as context for the answer.";
}
// add new question to prompt
$prompt = $prompt . "Question:\n" . $Questionmessage . $please_use_above . "\n\nAnswer:\n\n";
// add new question to prompt
$prompt = $prompt . "Question:\n" . $Questionmessage . $please_use_above . "\n\nAnswer:\n\n";
// create a new completion
$complete = json_decode($open_ai->completion([
'model' => $version,
'prompt' => $prompt,
'temperature' => 0.9,
'max_tokens' => 2000, //最大字符数,建议别改大了
'top_p' => 1,
'frequency_penalty' => 0,
'presence_penalty' => 0,
'stop' => [
"\nNote:",
"\nQuestion:"
]
]));
// get message text
if (isset($complete->choices[0]->text)) {
$text = str_replace("\\n", "\n", $complete->choices[0]->text);
} elseif (isset($complete->error->message)) {
$text = $complete->error->message;
} else {
$text = "Sorry, but I don't know how to answer that.";
}
return (string)$text;
}
```