# fake Telegram Bot API + fake OpenAI streaming endpoint for tests. # argv: port, file the model asks to write, log of sent messages, answer word. # # The first update asks for work; the model answers with a write tool call. # When the gateway asks for approval with an inline keyboard, the fake sends: # - a question (must be told to wait), # - a callback from a stranger (must be ignored), # - the real callback (yes/no), which resolves the approval. import http.server, json, os, re, sys, threading, time LOCK = threading.Lock() INITIAL = sys.argv[5] if len(sys.argv) > 5 else "schreib die datei" updates = [{"update_id": 1, "message": {"text": INITIAL, "chat": {"id": 42}, "from": {"id": 7}}}] next_uid = [2] sent = [] TARGET = sys.argv[2] ANSWER = sys.argv[4] if len(sys.argv) > 4 else "ok" FAILS = [2] # "wiederholen": the first two calls answer HTTP 500 KAPUTT = [1] # "kaputt": the first request sends a tool call with broken JSON def add_update(text, frm=7): with LOCK: updates.append({"update_id": next_uid[0], "message": {"text": text, "chat": {"id": 42}, "from": {"id": frm}}}) next_uid[0] += 1 def add_callback(data, frm=7): with LOCK: updates.append({"update_id": next_uid[0], "callback_query": { "id": "cb%d" % next_uid[0], "from": {"id": frm}, "message": {"message_id": 100, "chat": {"id": 42}}, "data": data}}) next_uid[0] += 1 class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass def reply(self, obj, ctype="application/json"): b = obj if isinstance(obj, bytes) else json.dumps(obj).encode() self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) def body(self): n = int(self.headers.get("Content-Length", 0)) return self.rfile.read(n) def do_GET(self): if "/models" in self.path: # the OpenAI /v1/models route: /model probe reads this return self.reply({"data": [{"id": "m"}, {"id": "other"}]}) if "/getUpdates" in self.path: off = int(re.search(r"offset=(-?\d+)", self.path).group(1)) for _ in range(10): with LOCK: got = [u for u in updates if u["update_id"] >= off] if got: break time.sleep(0.2) return self.reply({"ok": True, "result": got}) self.reply({"ok": True, "result": []}) def do_POST(self): raw = self.body() ctype = self.headers.get("Content-Type", "") if (("/sendPhoto" in self.path or "/sendDocument" in self.path) and ctype.startswith("multipart/")): kind = "photo-file" if "/sendPhoto" in self.path else "document-file" cap = re.search(rb'name="caption"\r\n\r\n(.*?)\r\n', raw, re.S) fn = re.search(rb'filename="([^"]*)"', raw) with open(sys.argv[3], "a") as f: f.write("%s: %s caption=%s\n" % ( kind, fn.group(1).decode() if fn else "", cap.group(1).decode() if cap else "")) return self.reply({"ok": True, "result": {"message_id": 102}}) if "/setMyCommands" in self.path: req = json.loads(raw) with open(sys.argv[3], "a") as f: for c in req.get("commands", []): f.write("cmd: %s\n" % c.get("command", "")) return self.reply({"ok": True, "result": True}) if ("/answerCallbackQuery" in self.path or "/editMessageReplyMarkup" in self.path or "/setChatMenuButton" in self.path or "/sendChatAction" in self.path): return self.reply({"ok": True, "result": True}) if "/sendPhoto" in self.path: req = json.loads(raw) with open(sys.argv[3], "a") as f: f.write("photo: %s caption=%s\n" % ( req.get("photo", ""), req.get("caption", ""))) return self.reply({"ok": True, "result": {"message_id": 101}}) if "/sendMessage" in self.path: req = json.loads(raw) text = req.get("text", "") markup = req.get("reply_markup") with open(sys.argv[3], "a") as f: f.write(text.replace("\n", " | ") + "\n") if req.get("parse_mode"): # the gateway renders markdown as HTML for Telegram f.write("mode: %s\n" % req["parse_mode"]) if markup is not None: f.write("markup: " + json.dumps( markup, separators=(",", ":")) + "\n") # /menu: the inline keyboard arrives; press Status. The status # text itself starts with "Status (", so this does not loop. if text.startswith("MenĂ¼"): add_callback("status") # /model: the menu arrives, press the second provider (the tests # run with SPLINTER_LOCALE=de) if "Waehle ein Modell" in text: add_callback("model:far") if text.startswith("Modell: other (Provider far"): # only once the switch is confirmed: sent together with the # button, the turn could be read before the button was add_update("hallo") # /connect: one answer per question if "Neuer Provider" in text: add_update("testprov") elif "Endpoint?" in text: # the fake is its own OpenAI endpoint, so the test turn in # /connect has somewhere to go add_update("http://127.0.0.1:%s/v1/chat/completions" % sys.argv[1]) elif "Welches Modell" in text: add_update("llama3") elif "Umgebungsvariable" in text: add_update("-") # /model probe: the menu of served models arrives, press the first cb = [b.get("callback_data", "") for row in (markup or {}).get( "inline_keyboard", []) for b in row] if any(c.startswith("mm:") for c in cb): add_callback("mm:0") m = re.match(r"Frage (\d+)/", text) if m: add_update("antwort-%s" % m.group(1)) # the `ask` tool: the question arrives with its answer hint. Match # on the question, not on the hint -- the hint is translated and # this fake runs under SPLINTER_LOCALE=de in the gateway test. if "Which colour should the login page be?" in text: # ANSWER is the operator's reply. "/cancel" is a real answer # word here too: the gateway must treat it as the way out of # the question, not hand it to the model as a decision. add_update(ANSWER) m = re.match(r"Zustimmung (\d+):", text) if m: add_update("was machst du?") # must be told to wait add_callback("ack:%s:yes" % m.group(1), frm=99) # stranger add_callback("ack:%s:%s" % ( m.group(1), "yes" if ANSWER == "ok" else "no")) return self.reply({"ok": True, "result": {"message_id": 100}}) req = json.loads(raw) has_tool = any(m.get("role") == "tool" for m in req.get("messages", [])) system = " ".join((m.get("content") or "") for m in req.get("messages", []) if m.get("role") == "system") last_user = "" for m in reversed(req.get("messages", [])): if m.get("role") == "user": last_user = m.get("content") or "" break answer = "ok" if "wiederholen" in last_user and FAILS[0] > 0: # a provider that is briefly broken: the harness must retry and # put the reason in the transcript, not in the input line FAILS[0] -= 1 self.send_response(500) self.send_header("Content-Length", "0") self.end_headers() return if "INTERVIEW_COMPLETE" in system: # the model-driven interview: a summary and the marker; the # gateway strips it and writes USER.txt answer = "Testprofil: mag C99.\nINTERVIEW_COMPLETE" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "wiederholen" in last_user: answer = "antwort nach dem retry" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "single word ok" in last_user: # /connect's test turn answer = "ok" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "codebild" in last_user: # an image inside code is text, not a photo answer = "`![x](https://example.org/x.png)`\n" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "lokales bild" in last_user: p = os.path.join(os.path.dirname(sys.argv[3]), "pic.png") with open(p, "wb") as f: f.write(b"\x89PNG\r\n\x1a\n" + b"rest") answer = "Siehe:\n\n![Lokal](%s)\n" % p chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "kein bild" in last_user: p = os.path.join(os.path.dirname(sys.argv[3]), "notimg.txt") with open(p, "w") as f: f.write("nur text") answer = "Datei:\n\n![Kein Bild](%s)\n" % p chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "viele zeilen" in last_user: answer = "".join("Zeile %03d\n" % i for i in range(1, 121)) chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "frag den operator" in last_user: # the `ask` tool: a question with options on the first request, # then the answer the tool returned is echoed back as the answer if has_tool: last = [m for m in req.get("messages", []) if m.get("role") == "tool"] got = last[-1].get("content", "") if last else "" answer = "antwort war: " + str(got) chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] else: chunks = [{"choices": [{"delta": {"tool_calls": [{ "index": 0, "id": "c1", "type": "function", "function": {"name": "ask", "arguments": json.dumps({ "question": "Which colour should the login page be?", "options": ["green", "blue"]})}}]}}]}] elif "bild" in last_user: answer = "Hier:\n\n![Ein Bild](https://example.org/b.png)\n\nEnde\n" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "markdown" in last_user: answer = "**fett** und `code`\n" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "tabelle" in last_user: # a markdown table: the chat must draw columns, not pipes answer = "| a | b |\n|---|---|\n| 1 | 22 |\n" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "kaputt" in last_user and KAPUTT[0] > 0: # a model that sends a tool call whose arguments are not JSON: # the turn must correct it, and the operator must see that it # is retrying instead of looking at a silent chat. Only the # first request is broken; the correction note is not "kaputt", # so the second one falls through to the normal tool call. KAPUTT[0] -= 1 chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1", "type": "function", "function": { "name": "run", "arguments": "{\"command\":"}}]}}]}, {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}] elif has_tool: chunks = [{"choices": [{"delta": {"content": "fertig"}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] else: args = json.dumps({"path": TARGET, "content": "vom gateway\n"}) chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1", "type": "function", "function": {"name": "write", "arguments": args}}]}}]}, {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}] if not req.get("stream"): # the non-streaming flavour, e.g. provider tests from /connect return self.reply({"choices": [{"index": 0, "message": { "role": "assistant", "content": answer}, "finish_reason": "stop"}]}) # the meter: context, cache share and tok/s in the status bar chunks.append({"choices": [], "usage": {"prompt_tokens": 1290, "completion_tokens": 50, "prompt_tokens_details": {"cached_tokens": 800}}}) b = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n" self.reply(b.encode(), "text/event-stream") http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()