# fake OpenAI endpoint: the first request of a turn asks the operator a question # with the `ask` tool, the next one answers with what came back. # argv: port, options (comma separated, may be empty) import http.server, json, sys def ev(d): return ("data: " + json.dumps(d) + "\n\n").encode() OPTS = [o for o in (sys.argv[2].split(",") if len(sys.argv) > 2 else []) if o] class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass def do_POST(self): n = int(self.headers.get("Content-Length", 0)) req = json.loads(self.rfile.read(n)) last = req["messages"][-1] self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() w = self.wfile.write if last["role"] == "tool": w(ev({"choices": [{"delta": {"content": "answer was: " + str(last.get("content", ""))}}]})) else: args = {"question": "Which colour should the login page be?"} if OPTS: args["options"] = OPTS w(ev({"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1", "type": "function", "function": { "name": "ask", "arguments": json.dumps(args)}}]}}]})) w(b"data: [DONE]\n\n") http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()