-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.php
More file actions
57 lines (47 loc) · 1.41 KB
/
backend.php
File metadata and controls
57 lines (47 loc) · 1.41 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
<?php
while (ob_get_level()) {
ob_end_clean();
}
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
$API_KEY = $_SERVER['HTTP_X_API_KEY'] ?? '';
if (empty($API_KEY)) {
echo "data: " . json_encode(['error' => 'API-Key missing!']) . "\n\n";
exit;
}
$input = file_get_contents('php://input');
$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'x-api-key: ' . $API_KEY,
'anthropic-version: 2023-06-01',
'content-type: application/json'
]);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
echo $data;
if (ob_get_level() > 0) ob_flush();
flush();
return strlen($data);
});
$result = curl_exec($ch);
if ($result === false) {
$error_msg = curl_error($ch);
echo "data: " . json_encode(['error' => 'CURL-Error: ' . $error_msg]) . "\n\n";
} else {
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code >= 400) {
// ...
}
}
curl_close($ch);
?>