-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.php
More file actions
216 lines (141 loc) · 5.42 KB
/
index.php
File metadata and controls
216 lines (141 loc) · 5.42 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
<?php
$API_KEY = 'ur api key lol';
$GEMINI_MODEL = 'gemini-2.5-flash';
$GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/{$GEMINI_MODEL}:generateContent?key={$API_KEY}";
$infoPath = __DIR__ . '/info.txt';
$buttonsPath = __DIR__ . '/buttons.json';
$rateLimitDir = __DIR__ . '/rate_limit';
header("Access-Control-Allow-Origin: https://bio-sim.us");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Only POST is allowed.']);
exit;
}
$MAX_REQUESTS = 10;
$WINDOW_SECONDS = 600;
try {
if (!is_dir($rateLimitDir)) {
@mkdir($rateLimitDir, 0755, true);
}
$clientIp = $_SERVER['HTTP_CF_CONNECTING_IP']
?? $_SERVER['HTTP_X_FORWARDED_FOR']
?? $_SERVER['REMOTE_ADDR']
?? 'unknown';
$ipKey = sha1($clientIp);
$rlFile = $rateLimitDir . '/' . $ipKey . '.json';
$now = time();
$history = [];
if (file_exists($rlFile)) {
$history = json_decode(file_get_contents($rlFile), true) ?? [];
}
$history = array_values(array_filter($history, function ($ts) use ($now, $WINDOW_SECONDS) {
return is_int($ts) && ($ts > $now - $WINDOW_SECONDS);
}));
if (count($history) >= $MAX_REQUESTS) {
echo json_encode(['reply' => 'Too Many Requests (Rate Limit Exceeded)', 'button' => 'none']);
exit;
}
$history[] = $now;
file_put_contents($rlFile, json_encode($history));
} catch (Exception $e) {
}
$raw = file_get_contents('php://input');
$body = json_decode($raw, true);
if (!isset($body['userinput']) || trim($body['userinput']) === '') {
http_response_code(400);
echo json_encode(['error' => 'Missing userinput']);
exit;
}
$userInput = $body['userinput'];
$infoText = file_exists($infoPath) ? file_get_contents($infoPath) : "No background info provided.";
$buttonsMapping = [];
if (file_exists($buttonsPath)) {
$buttonsMapping = json_decode(file_get_contents($buttonsPath), true) ?? [];
}
$buttonsKeys = array_keys($buttonsMapping);
$buttonsKeysJson = json_encode($buttonsKeys);
$systemPrompt = <<<EOT
Answer the prompt delimited by the triple apostrophes in the best way possible using your knowledge about biology.
When possible, incorporate information delimited by the triple backticks in your answer.
Limit yourself to 5 sentences unless otherwise specified by the prompt.
When possible, make your answer a bulleted list, adding "<br><br>" after each line break.
Do not bold any texts by wrapping the texts with **.
Highlight any key/important words in your response. In order to highlight a text, wrap the text with <b> and </b>.
Use "-" before each bullet point.
If you are unable to respond to the prompt using either your knowledge about biology, or by using the information delimited by the triple backticks,
then add 'what is' in front of the prompt and then attempt to respond to it.
If you still are unable to respond to the prompt, then respond with the response "Sorry, I cannot help you with that".
Background Info:
```{$infoText}```
User Prompt:
'''{$userInput}'''
EOT;
$payloadChat = [
'contents' => [
[
'parts' => [['text' => $userInput]]
]
],
'systemInstruction' => [
'parts' => [['text' => $systemPrompt]]
]
];
$responseChat = makeGeminiCall($GEMINI_URL, $payloadChat);
$replyText = "Sorry, I couldn't produce a response.";
if (isset($responseChat['candidates'][0]['content']['parts'][0]['text'])) {
$replyText = $responseChat['candidates'][0]['content']['parts'][0]['text'];
}
$buttonPrompt = <<<EOT
The given prompt is delimited by the triple apostrophes.
The given Array is delimited by the triple backticks.
Your task is to pick one of the strings in the Array which is the most relevant to the prompt.
Your response should only include that string, and nothing else.
If none of the keys in the JSON text are relevant to the prompt, your response should be "none".
User Prompt:
'''{$userInput}'''
Available Buttons:
```{$buttonsKeysJson}```
EOT;
$payloadButton = [
'contents' => [
[
'parts' => [['text' => $buttonPrompt]]
]
]
];
$responseButton = makeGeminiCall($GEMINI_URL, $payloadButton);
$selectedKey = 'none';
if (isset($responseButton['candidates'][0]['content']['parts'][0]['text'])) {
$selectedKey = trim($responseButton['candidates'][0]['content']['parts'][0]['text']);
$selectedKey = trim(preg_replace('/\s\s+/', ' ', $selectedKey));
}
$buttonValue = array_key_exists($selectedKey, $buttonsMapping) ? $buttonsMapping[$selectedKey] : 'none';
echo json_encode([
'reply' => $replyText,
'button' => $buttonValue,
]);
function makeGeminiCall($url, $payload) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return null;
}
curl_close($ch);
return json_decode($response, true);
}
?>