Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
#!/usr/bin/env python3
"""Local deterministic OpenAI-protocol HTTP fixture for the DBMS_VECTOR regression test."""
 
import json
import signal
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
 
PORT = 18180
LOG_PATH = "/tmp/kilo/dbms_vector/fixture_requests.log"
KEY_PREFIX = "sk-test"
 
 
class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
 
    def log_message(self, format, *args):
        pass
 
    def _send(self, status, body, content_type="application/json"):
        data = body if isinstance(body, bytes) else body.encode("utf-8")
        try:
            self.send_response(status)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        except (BrokenPipeError, ConnectionResetError):
            pass
 
    def _authorized(self):
        auth = self.headers.get("Authorization", "")
        return auth.startswith("Bearer " + KEY_PREFIX)
 
    def _read_json(self):
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length) if length else b"{}"
        try:
            return json.loads(raw)
        except ValueError:
            return {}
 
    def _log(self, line):
        try:
            with open(LOG_PATH, "a") as log:
                log.write(line + "\n")
        except OSError:
            pass
 
    def do_POST(self):
        if not self._authorized():
            self._send(
                401,
                json.dumps(
                    {
                        "error": {
                            "message": "Invalid API key provided",
                            "type": "invalid_request_error",
                        }
                    }
                ),
            )
            return
 
        if self.path.endswith("/embeddings"):
            self._embeddings()
        elif self.path.endswith("/chat/completions"):
            self._generate("chat")
        elif self.path.endswith("/completions"):
            self._generate("completions")
        elif self.path.endswith("/bad_request"):
            self._send(
                400,
                json.dumps({"error": {"message": "Invalid request: unknown model"}}),
            )
        elif self.path.endswith("/server_error"):
            self._send(500, "upstream exploded", content_type="text/plain")
        elif self.path.endswith("/message_error"):
            self._send(200, json.dumps({"message": "model overloaded, retry later"}))
        elif self.path.endswith("/plain_error"):
            self._send(200, json.dumps({"error": "quota exceeded for this key"}))
        elif self.path.endswith("/array_error"):
            self._send(200, json.dumps({"error": ["bad input", "second reason"]}))
        elif self.path.endswith("/slow"):
            time.sleep(3)
            self._embeddings()
        else:
            self._send(404, json.dumps({"error": {"message": "unknown endpoint"}}))
 
    def _generate(self, shape):
        request = self._read_json()
        model = request.get("model", "")
        keys = ",".join(sorted(request.keys()))
        auth = self.headers.get("Authorization", "")
        key = auth[len("Bearer "):] if auth.startswith("Bearer ") else ""
 
        if shape == "completions":
            prompt = request.get("prompt", "")
            self._log(
                "completions key=%s model=%s keys=%s prompt=%s"
                % (key, model, keys, prompt)
            )
            answer = {"choices": [{"text": "completion of: " + prompt}]}
        else:
            messages = request.get("messages", [])
            prompt = messages[-1].get("content", "") if messages else ""
            self._log(
                "chat key=%s model=%s keys=%s prompt=%s"
                % (key, model, keys, prompt)
            )
            answer = {
                "choices": [
                    {
                        "message": {
                            "role": "assistant",
                            "content": "reply to: " + prompt,
                        }
                    }
                ]
            }
        self._send(200, json.dumps({"object": "completion", **answer}))
 
    def _embeddings(self):
        request = self._read_json()
        inputs = request.get("input", [])
        model = request.get("model", "")
        keys = ",".join(sorted(request.keys()))
        auth = self.headers.get("Authorization", "")
        key = auth[len("Bearer "):] if auth.startswith("Bearer ") else ""
        self._log("embeddings key=%s model=%s keys=%s" % (key, model, keys))
 
        data = []
        for index, text in enumerate(inputs):
            embedding = [float(len(text)), float(index + 1), 0.25]
            data.append(
                {"object": "embedding", "index": index, "embedding": embedding}
            )
        self._send(
            200, json.dumps({"object": "list", "model": model, "data": data})
        )
 
 
def main():
    server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
    shutdown = lambda *_: threading.Thread(
        target=server.shutdown, daemon=True
    ).start()
    signal.signal(signal.SIGTERM, shutdown)
    timer = threading.Timer(120, server.shutdown)
    timer.daemon = True
    timer.start()
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        timer.cancel()
        server.server_close()
 
 
if __name__ == "__main__":
    main()