gpt-35-turbo не запоминает сообщения в PHP
Я создал бота Telegram, который отвечает на сообщения пользователей, используя API OpenAI GPT. Все работает нормально, но есть проблема. В модели gpt-35-turbo есть возможность добавлять параметры для запоминания сообщений и отслеживания разговоров, что я и сделал, но не работает. Я делюсь своим кодом для помощи
Вот мой код
<?php
class Bot
{
private $bot_token;
public function __construct($bot_token)
{
$this->bot_token = $bot_token;
}
public function handleUpdate($update)
{
$message = $update['message'];
$chat_id = $message['chat']['id'];
$text = $message['text'];
switch ($text) {
case '/start':
$this->sendTypingAction($chat_id);
sleep(1);
$welcome_message = " Hello \nWith me, you can get the answer to EVERYTHING in a few seconds!\n\n I speak all languages, send /prof to start";
$this->sendMessage($chat_id, $welcome_message);
break;
case '/help':
$this->sendTypingAction($chat_id);
sleep(1);
$help_message = "Need help? Here's what I can do: \n\n/start - To begin\n/help - To get help\n/prof - To start a chat session with a virtual teacher";
$this->sendMessage($chat_id, $help_message);
break;
default:
$this->sendTypingAction($chat_id);
sleep(1);
$response = $this->generateResponse($text);
$this->sendMessage($chat_id, $response);
}
}
private function generateResponse($text)
{
$response = "";
// Get the user's Telegram ID
$chat_id = $update['message']['chat']['id'];
// Get the user's session data (if any)
session_id("tg_" . $chat_id);
session_start();
$conversation = isset($_SESSION['conversations']) ? $_SESSION['conversations'] : array();
// detect if there is some mention of date or time in the text:
// ========================================================
// Define the keywords to search for
$keywords = array('time', 'date', 'day is it');
// Check if the text contains any of the keywords
$containsKeyword = false;
$regex = '/\b(' . implode('|', $keywords) . ')\b/i';
$containsKeyword = preg_match($regex, $text);
// If the text contains a keyword, call the getDateTime() function
if ($containsKeyword) {
$datetime = getDateTime();
$text = "It is " . $datetime . ". If appropriate, respond to
the following in a short sentence: " . $text;
}
// set up a session variable to store the last n questions and responses
$number_of_interactions_to_remember = 10;
$openai_api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
if (!isset($_SESSION['conversations'])) {
$_SESSION['conversations'] = array();
}
// Remove oldest conversation if the number of interactions >= $number_of_interactions_to_remember
if (count($_SESSION['conversations']) > $number_of_interactions_to_remember + 1) {
$_SESSION['conversations'] = array_slice($_SESSION['conversations'], -$number_of_interactions_to_remember, $number_of_interactions_to_remember, true);
}
// Prepare the request to the OpenAI API
$data = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'system',
'content' => 'You are called Chatty McChatface. You give short, friendly responses. '
)
)
);
// Add the last 10 interactions in the request to the OpenAI API
foreach ($conversation as $conversation_item) {
foreach ($conversation_item as $message) {
array_push($data['messages'], array(
'role' => $message['role'],
'content' => $message['content']
));
}
}
// Add user's last question in request to OpenAI API
array_push($data['messages'], array(
'role' => 'user',
'content' => $text
));
// Send request to OpenAI API
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $openai_api_key,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
if (isset($response['choices'][0]['message']['content'])) {
$content = $response['choices'][0]['message']['content'];
} else {
$content = "Something went wrong! ```" . json_encode($response) . "```";
}
// Add the last interaction in the user's session
$new_conversation = array(
array(
'role' => 'user',
'content' => $text
),
array(
'role' => 'assistant',
'content' => $content
)
);
if (count($conversation) > $number_of_interactions_to_remember) {
array_shift($conversation);
}
array_push($conversation, $new_conversation);
$_SESSION['conversations'] = $conversation;
return $content;
}
private function sendMessage($chat_id, $text)
{
$url = "https://api.telegram.org/bot" . $this->bot_token . "/sendMessage?chat_id=" . $chat_id . "&text=" . urlencode($text);
file_get_contents($url);
}
private function sendTypingAction($chat_id)
{
$url = "https://api.telegram.org/bot" . $this->bot_token . "/sendChatAction?chat_id=" . $chat_id . "&action=typing";
file_get_contents($url);
}
}
$update = json_decode(file_get_contents('php://input'), true);
if (isset($update)) {
$bot = new Bot('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$bot->handleUpdate($update);
}