#!/usr/bin/env python3 """Probe the gateway's SSE stream: chunk count, first chunk, total time. argv: port, user text. It fails when the answer arrives in one piece at the end instead of streaming while the upstream delivers it. """ import json import socket import sys import time if len(sys.argv) < 3: print("usage: stream_probe.py PORT TEXT") sys.exit(2) port = int(sys.argv[1]) text = sys.argv[2] body = json.dumps({"model": "x", "stream": True, "messages": [{"role": "user", "content": text}]}).encode() req = ("POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\n" "Content-Type: application/json\r\nContent-Length: %d\r\n" "Connection: close\r\n\r\n" % len(body)).encode() + body s = socket.create_connection(("127.0.0.1", port)) start = time.monotonic() s.sendall(req) seen = [] done = None buf = b"" while True: chunk = s.recv(4096) if not chunk: break buf += chunk while b"\n\n" in buf: line, buf = buf.split(b"\n\n", 1) if not line.startswith(b"data: "): continue payload = line[6:] if payload == b"[DONE]": done = time.monotonic() continue obj = json.loads(payload) for choice in obj.get("choices", []): if choice.get("delta", {}).get("content"): seen.append(time.monotonic()) if len(seen) < 3: print("only %d content chunks" % len(seen)) sys.exit(1) if seen[0] - start > 1.2: print("first chunk after %.2fs" % (seen[0] - start)) sys.exit(1) if done is None or done - seen[0] < 1.2: print("stream arrived at once") sys.exit(1) print("streaming: %d chunks over %.2fs" % (len(seen), done - start))