The final answer replaced the whole streamed entry, so 'I will read the file' vanished. The fake Telegram sent the follow-up turn together with the model button, so the turn could be read first (flaky test). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
209 lines
9.8 KiB
Python
209 lines
9.8 KiB
Python
# 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"
|
|
|
|
|
|
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
|
|
"/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")
|
|
# /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))
|
|
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", []))
|
|
last_user = ""
|
|
for m in reversed(req.get("messages", [])):
|
|
if m.get("role") == "user":
|
|
last_user = m.get("content") or ""
|
|
break
|
|
answer = "ok"
|
|
if "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 = "``\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\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\n" % p
|
|
chunks = [{"choices": [{"delta": {"content": answer}}]},
|
|
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
|
|
elif "bild" in last_user:
|
|
answer = "Hier:\n\n\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 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"}]})
|
|
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()
|