forked from rueetschli/OpenAI-GPT-3.5-turbo-simple-script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.php
62 lines (55 loc) · 2.17 KB
/
message.php
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
54
55
56
57
58
59
60
61
62
<?php
header( "Access-Control-Allow-Origin: *" );
header( "Content-Type: application/json" );
$context = json_decode( $_POST['context'] ?: "[]" ) ?: [];
// Initialisierung der Modellparameter
$postData = [
"model" => "gpt-3.5-turbo",
"messages" => [],
"temperature" => 0.3,
"presence_penalty" => 0,
"frequency_penalty" => 1.2,
];
if( !empty( $context ) ) {
$context = array_slice( $context, -5 );
foreach( $context as $message ) {
$postData['messages'][] = ['role' => 'user', 'content' => str_replace("\n", "\\n", $message[0])];
$postData['messages'][] = ['role' => 'assistant', 'content' => str_replace("\n", "\\n", $message[1])];
}
}
$postData['messages'][] = ['role' => 'user', 'content' => $_POST['message']];
$ch = curl_init();
$OPENAI_API_KEY = "Deine-OpenAI-API";
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Bearer ' . $OPENAI_API_KEY . ''
];
$postData = json_encode($postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
$complete = json_decode($result);
if( isset( $complete->choices[0]->message->content ) ) {
$text = trim(str_replace( "\\n", "\n", $complete->choices[0]->message->content ),"\n");
} elseif( isset( $complete->error->message ) ) {
$text = "Der Server gibt eine Fehlermeldung zurück.".$complete->error->message;
} else {
$text = "Der Server bricht ab oder gibt eine Ausnahmemeldung zurück.";
}
echo json_encode( [
"message" => $text,
"raw_message" => $text,
"status" => "success",
] );
$content2 = $_SERVER["REMOTE_ADDR"]." | ".date("Y-m-d H:i:s")."\n";
$content2 .= "Q:".$_POST['message']."\nA:".$text."\n----------------\n";
$myfile = fopen(__DIR__ . "/chat.txt", "a") or die("Writing file failed.");
fwrite($myfile, $content2);
fclose($myfile);
?>