相關程式碼
<?php
$message = $this->request->post('newMessage');
$selType = $this->request->post('selType');
try {
switch ($selType) {
case 1: // 問答模式
$response = static::$openaiClient->completions()
->create(
['model' => 'text-davinci-003',
'prompt' => $message,
'temperature' => 1,
'max_tokens' => 2048,
'stop' => '\n'
]
)->toModel();
if ($response->choices) {
$user = $this->auth->getUser();
$data = [
'user_id' => $user->id,
'from_msg' => $message,
'to_msg' => $response->choices[0]->text,
];
Message::create($data);
$this->success('', $response->choices[0]->text);
}
break;
case 2: // 上下文模式
/** @var CreateResponse $response */
$gpt = cookie('chat-gpt');
$user = $this->auth->getUser();
$messageM = $message;
if ($gpt) {
$msg = '';
$time = $gpt + 60 * 9;
Message::where(['user_id' => $user->id,
'type' => 2,
'createtime' => ['between', "{$gpt},{$time}"]
])->order('createtime', 'asc')
->select()
->each(function ($item) use (&$msg) {
$msg .= "(You:{$item->from_msg}\n){$item->to_msg} ";
});
$message = $msg . "(You:{$message})";
}
$response = static::$openaiClient->completions()
->create(
['model' => 'text-davinci-003',
'prompt' => $message,
'max_tokens' => 2048,
'stop' => '\n\n'
]
)->toModel();
if ($response->choices) {
$data = [
'user_id' => $user->id,
'from_msg' => $messageM,
'type' => $selType,
'to_msg' => $response->choices[0]->text,
];
Message::create($data);
if (!$gpt) {
cookie('chat-gpt', time(), ['expire' => 10 * 60]);
}
$this->success('', $response->choices[0]->text);
}
break;
case 3: // 程式碼模式
$response = static::$openaiClient->completions()
->create(
['model' => 'text-davinci-003',
'prompt' => $message,
'temperature' => 0,
'max_tokens' => 2048,
]
)->toModel();
if ($response->choices) {
$user = $this->auth->getUser();
$data = [
'user_id' => $user->id,
'from_msg' => $message,
'type' => $selType,
'to_msg' => $response->choices[0]->text,
];
Message::create($data);
$this->success('', $response->choices[0]->text);
}
break;
case 4: // 圖片模式
$response = static::$openaiClient->imagesGenerations()
->create(
['prompt' => $message,
'size' => '512x512',
'n' => 2,
"response_format" => "url",
]
)->toArray();
if ($response['data']) {
$user = $this->auth->getUser();
$data = [
'user_id' => $user->id,
'from_msg' => $message,
'type' => $selType,
'to_msg' => json_encode($response['data'], JSON_UNESCAPED_UNICODE),
];
Message::create($data);
$this->success('', $response['data']);
}
break;
}
} catch (\Tectalic\OpenAi\ClientException|\think\exception\ErrorException $exception) {
$this->error($exception->getMessage());
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結