-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.php
More file actions
53 lines (42 loc) · 1.44 KB
/
Copy pathchat.php
File metadata and controls
53 lines (42 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
require 'db.php';
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
$message = trim($input['message']);
$model = $input['model'];
// Save user message
$stmt = $db->prepare("INSERT INTO messages (role, content, model) VALUES (?, ?, ?)");
$stmt->execute(['user', $message, $model]);
// Load API key
$env = parse_ini_file('.env');
$apiKey = $env['OPENAI_API_KEY'] ?? die(json_encode(['error' => 'API key not found']));
// Get full conversation
$stmt = $db->prepare("SELECT role, content FROM messages WHERE model = ? ORDER BY timestamp ASC");
$stmt->execute([$model]);
$conversation = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Call OpenAI
$payload = [
'model' => $model,
'messages' => $conversation,
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer $apiKey"
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
$reply = $data['choices'][0]['message']['content'] ?? "No response.";
// Save assistant reply
$stmt = $db->prepare("INSERT INTO messages (role, content, model) VALUES (?, ?, ?)");
$stmt->execute(['assistant', $reply, $model]);
echo json_encode([
'user' => $message,
'assistant' => $reply
]);