<?php
class ChatApp {
private $model;
private $messages;
public $api_key;
public function __construct($model = "gpt-3.5-turbo", $load_file = "") {
$this->model = $model;
$this->messages = array();
if ($load_file != '') {
$this->load($load_file);
}
}
public function chat($message) {
if ($message == "exit") {
$this->save();
exit();
} elseif ($message == "save") {
$this->save();
return "(saved)";
}
$this->messages[] = array("role" => "user", "content" => $message);
$post_fields = array(
"model" => $this->model,
"messages" => $this->messages
);
$header = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $this->api_key
);
$ch = curl_init();
$url = 'https://api.openai.com/v1/chat/completions';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result, true);
$assistant_message = $response["choices"][0]["message"]["content"];
$this->messages[] = array("role" => "assistant", "content" => $assistant_message);
return $assistant_message;
}
public function save() {
try {
$ts = time();
$json_object = json_encode($this->messages, JSON_PRETTY_PRINT);
$filename_prefix = preg_replace('/[^0-9a-zA-Z]+/', '-', substr($this->messages[0]["content"], 0, 30));
$filename = "chat_model_" . $filename_prefix . "_" . $ts . ".json";
file_put_contents($filename, $json_object);
} catch (Exception $e) {
exit();
}
}
public function load($load_file) {
$json_data = file_get_contents($load_file);
$this->messages = json_decode($json_data, true);
}
}
$chatApp = new ChatApp();
$chatApp->api_key="sk-lyaikhPwD73bPVtUMO5FT3BlbkFJ";
$assistant_message = $chatApp->chat("Merhaba, nasılsın?");
$assistant_message = $chatApp->chat("Hava durumu hakkında bilgi verir misin?");
$assistant_message = $chatApp->chat("Konya");
echo $assistant_message;
$chatApp->chat("exit");
?>