Open History to see the last commit
1<?php
2
3declare(strict_types=1);
4
5require_once __DIR__ . '/lib/Agui.php';
6require_once __DIR__ . '/lib/Messages.php';
7require_once __DIR__ . '/lib/Providers.php';
8
9$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
10$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
11
12if ($method === 'OPTIONS') {
13 cors_preflight();
14 exit;
15}
16
17if ($path === '/health') {
18 header('Content-Type: text/plain');
19 http_response_code(200);
20 echo 'ok';
21 exit;
22}
23
24if ($path !== '/' || $method !== 'POST') {
25 http_response_code($method === 'POST' ? 404 : 405);
26 header('Content-Type: text/plain');
27 echo $method === 'POST' ? 'not found' : 'method not allowed';
28 exit;
29}
30
31$rawBody = file_get_contents('php://input');
32if ($rawBody === false) {
33 http_response_code(400);
34 header('Content-Type: text/plain');
35 echo 'failed to read body';
36 exit;
37}
38
39$input = json_decode($rawBody, true);
40if (!is_array($input)) {
41 http_response_code(400);
42 header('Content-Type: text/plain');
43 echo 'invalid JSON body';
44 exit;
45}
46
47$threadId = is_string($input['threadId'] ?? null) ? $input['threadId'] : '';
48$runId = is_string($input['runId'] ?? null) ? $input['runId'] : '';
49$messages = is_array($input['messages'] ?? null) ? $input['messages'] : [];
50
51if ($threadId === '' || $runId === '') {
52 http_response_code(400);
53 header('Content-Type: text/plain');
54 echo 'threadId and runId are required';
55 exit;
56}
57
58$config = provider_from_input($input);
59[$system, $chatMessages] = to_chat_messages($messages);
60
61if ($chatMessages === []) {
62 stream_error_only($threadId, $runId, 'no user or assistant messages to send');
63 exit;
64}
65
66stream_text($threadId, $runId, static function (callable $emit) use ($config, $system, $chatMessages): void {
67 stream_completion($config, $system, $chatMessages, $emit);
68});