Skip to content

Instantly share code, notes, and snippets.

@isaaclepes
Last active March 17, 2023 06:28
Show Gist options
  • Save isaaclepes/627d338d1fdf5d4b970f62178f41e005 to your computer and use it in GitHub Desktop.
Save isaaclepes/627d338d1fdf5d4b970f62178f41e005 to your computer and use it in GitHub Desktop.
These PHP files constitute a gpt-3.5-turbo powered chat assistant.
<?php
session_start();
if (!isset($_SESSION['chat_id'])) {
$_SESSION['chat_id'] = uniqid();
}
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
// Load configuration
$config = parse_ini_file('chatit.conf', true);
// Connect to the MariaDB server
$mysqli = new mysqli($config['database']['host'], $config['database']['username'], $config['database']['password'], 'ChatIT', $config['database']['port']);
// Check connection
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
// Set up OpenAI API client
$openai_api_key = $config['api']['key'];
$httpClient = new Client(['base_uri' => 'https://api.openai.com/v1/']);
// Sanitize input function
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Retrieve chat history
function get_chat_history($mysqli) {
$chat_history = [];
$chat_id = $_SESSION['chat_id'];
$stmt = $mysqli->prepare("SELECT message, response, timestamp FROM _chat_history WHERE chat_id = ? ORDER BY timestamp ASC");
$stmt->bind_param('s', $chat_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$chat_history[] = $row;
}
$stmt->close();
return $chat_history;
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$user_message = sanitize_input($_POST['message']);
// Limit the user message to 256 tokens
$user_message = substr($user_message, 0, 256);
// Generate response using GPT API
$messages = [
['role' => 'system', 'content' => 'You are a friendly and helpful AI assistant from Geek it Together, an IT MSP company in Littleton, CO. Provide basic IT support to the user.'],
['role' => 'system', 'content' => 'When the chat is complete, thank the user for contacting support and wish them well.'],
['role' => 'system', 'content' => 'Limit topics of discussion to computers, technology, software, networking, and other office IT related topics.'],
['role' => 'user', 'content' => $user_message],
];
$response = $httpClient->post('chat/completions', [
'headers' => [
'Authorization' => "Bearer {$openai_api_key}",
'Content-Type' => 'application/json',
],
'json' => [
'model' => "gpt-3.5-turbo",
'messages' => $messages,
'max_tokens' => 150,
],
]);
$response_data = json_decode($response->getBody()->getContents(), true);
$gpt_response = $response_data['choices'][0]['message']['content'];
$gpt_response = trim($gpt_response); // Remove leading/trailing whitespace
// Limit the GPT response to 1024 tokens
$gpt_response = substr($gpt_response, 0, 1024);
// Store chat record
$chat_id = $_SESSION['chat_id'];
$stmt = $mysqli->prepare("INSERT INTO _chat_history (chat_id, message, response) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $chat_id, $user_message, $gpt_response);
$stmt->execute();
$stmt->close();
}
$chat_history = get_chat_history($mysqli);
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatIT</title>
</head>
<body>
<h1>ChatIT</h1>
<div id="chat-history" style="border: 1px solid #000; padding: 10px; max-height: 300px; overflow-y: scroll;">
<?php foreach ($chat_history as $chat): ?>
<p><strong>You:</strong> <?php echo htmlspecialchars($chat['message']); ?></p>
<p><strong>Geek it Together (AI):</strong> <?php echo htmlspecialchars($chat['response']); ?></p>
<hr>
<?php endforeach; ?>
</div>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<label for="message">Your message:</label><br>
<input type="text" id="message" name="message" required><br><br>
<input type="submit" value="Send">
</form>
</body>
</html>
[api]
key = your_openai_api_key
[database]
host = your_database_host
port = your_database_port
username = your_database_username
password = your_database_password
body {
font-family: 'Open Sans', sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.chat-container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 600px;
}
h1 {
color: #4d4d4d;
font-size: 24px;
margin: 0 0 20px;
}
.warning-message {
display: none;
color: #f44336;
font-size: 14px;
margin-bottom: 10px;
}
.chat-history {
background-color: #f8f8f8;
border: 1px solid #e0e0e0;
border-radius: 5px;
padding: 20px;
height: 300px;
overflow-y: auto;
margin-bottom: 10px;
}
.chat-form {
display: flex;
align-items: center;
}
label {
font-size: 14px;
font-weight: bold;
margin-right: 10px;
}
.user-message {
flex-grow: 1;
padding: 5px 10px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 5px;
outline: none;
margin-right: 10px;
}
.submit-button {
background-color: #0070ad;
color: #fff;
font-size: 14px;
padding: 5px 10px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.submit-button:hover {
background-color: #005e8a;
}
.submit-button:active {
background-color: #004966;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setup ChatIT</title>
</head>
<body>
<h1>Setup ChatIT</h1>
<form method="post" action="setup_action.php">
<label for="db_host">Database Host:</label><br>
<input type="text" id="db_host" name="db_host" value="localhost" required><br><br>
<label for="db_port">Database Port:</label><br>
<input type="text" id="db_port" name="db_port" value="3306" required><br><br>
<label for="db_user">Database Username:</label><br>
<input type="text" id="db_user" name="db_user" required><br><br>
<label for="db_pass">Database Password:</label><br>
<input type="password" id="db_pass" name="db_pass" required><br><br>
<label for="api_key">OpenAI API Key:</label><br>
<input type="text" id="api_key" name="api_key" required><br><br>
<input type="submit" name="action" value="Save">
<input type="submit" name="action" value="Revert">
<input type="submit" name="action" value="Test Connection">
</form>
</body>
</html>
<?php
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$action = sanitize_input($_POST['action']);
if ($action === 'Save') {
$db_host = sanitize_input($_POST['db_host']);
$db_port = sanitize_input($_POST['db_port']);
$db_user = sanitize_input($_POST['db_user']);
$db_pass = sanitize_input($_POST['db_pass']);
$api_key = sanitize_input($_POST['api_key']);
// Save configuration
$config = [
'database' => [
'host' => $db_host,
'port' => $db_port,
'username' => $db_user,
'password' => $db_pass,
],
'api' => [
'key' => $api_key,
],
];
$config_text = '';
foreach ($config as $section => $values) {
$config_text .= "[$section]\n";
foreach ($values as $key => $value) {
$config_text .= "$key=$value\n";
}
}
file_put_contents('chatit.conf', $config_text);
// Test connection
$mysqli = new mysqli($db_host, $db_user, $db_pass, 'ChatIT', (int)$db_port);
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
} else {
// Create table if it does not exist
$create_table_query = "CREATE
TABLE IF NOT EXISTS _chat_history (
id INT AUTO_INCREMENT PRIMARY KEY,
chat_id VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
response TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($mysqli->query($create_table_query) === TRUE) {
echo "Table '_chat_history' created successfully.";
} else {
echo "Error creating table: " . $mysqli->error;
}
}
$mysqli->close();
} elseif ($action === 'Revert') {
header('Location: setup.php');
exit;
} elseif ($action === 'Test Connection') {
$db_host = sanitize_input($_POST['db_host']);
$db_port = sanitize_input($_POST['db_port']);
$db_user = sanitize_input($_POST['db_user']);
$db_pass = sanitize_input($_POST['db_pass']);
$mysqli = new mysqli($db_host, $db_user, $db_pass, 'ChatIT', (int)$db_port);
if ($mysqli->connect_error) {
echo 'Connection failed: ' . $mysqli->connect_error;
} else {
echo 'Connection successful!';
}
$mysqli->close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment