- stream:true uses the provider's send_stream and writes each text delta as a chat.completion.chunk as it arrives, instead of one chunk at the end. The SSE headers and the role chunk go out before the upstream call, so a slow provider still gives the caller a live connection. - caller tool calls are sent as one tool_calls delta at the end of the step, when their names and arguments are complete; filtered gw_ calls are renumbered 0,1,... so strict accumulators see no gap. Local gw_ calls stay invisible. - stream_options.include_usage asks the provider for usage and adds the summed token counts in a final chunk before [DONE]. Usage is now summed over every upstream round, for the non-stream reply too. - an error after the first byte becomes an SSE error object plus [DONE]; a bad request is still an ordinary HTTP 400. SIGPIPE is ignored and TCP_NODELAY set, so a caller that closes early cannot kill the gateway. - tests: fake_gateway.py has a slow stream, tests/stream_probe.py measures that chunks arrive while the upstream streams, usage is checked, and the mixed reply keeps index 0 after filtering. make check green.
55 lines
1.7 KiB
Python
Executable File
55 lines
1.7 KiB
Python
Executable File
#!/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))
|