Files
lotherk 9af7695064 gateway streams: the answer grows while the provider talks
- 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.
2026-11-16 14:06:54 +00:00

119 lines
5.0 KiB
Python

# fake upstream for tests/test_gateway_openai.sh
# argv: port, read_path, write_path
# It answers the gateway's upstream requests: a gw_ tool call (executed by the
# gateway), a caller tool call (returned to the test client), or a final text.
import http.server, json, sys, time
def sse(w, obj):
w(("data: " + json.dumps(obj) + "\n\n").encode())
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"x")
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
req = json.loads(self.rfile.read(n))
msgs = req.get("messages", [])
last = msgs[-1] if msgs else {}
user = ""
for m in msgs:
if m.get("role") == "user":
user = m.get("content") or ""
stream = bool(req.get("stream"))
self.include_usage = bool(
req.get("stream_options", {}).get("include_usage"))
if "slowstream" in user:
return self.reply(stream, content="eins zwei drei vier fünf",
slow=True)
if "params" in user:
return self.reply(stream, content="PARAMS t=%s p=%s m=%s" % (
req.get("temperature"), req.get("top_p"),
req.get("max_tokens")))
if last.get("role") == "tool":
return self.reply(stream,
content="ERGEBNIS: " +
(last.get("content") or "")[:300])
if "gw-read" in user:
return self.reply(stream, call=("gw_read",
json.dumps({"path":
sys.argv[2]})))
if "gw-write" in user:
return self.reply(stream, call=("gw_write", json.dumps(
{"path": sys.argv[3], "content": "geschrieben\n"})))
if "caller" in user:
return self.reply(stream, call=("caller_tool", '{"x": 1}'))
if "mixed" in user:
return self.reply(stream, call=("gw_echo",
'{"text": "mixed-local"}'),
second=("caller_tool", '{"x": 2}'))
if "stream" in user:
return self.reply(stream, content="gestreamt")
return self.reply(stream, call=("gw_echo",
'{"text": "hallo-vom-gw"}'))
def reply(self, stream, content="", call=None, second=None, slow=False):
self.send_response(200)
if stream:
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
w = self.wfile.write
if slow:
for word in content.split(" "):
sse(w, {"choices": [{"delta": {"content": word + " "}}]})
self.wfile.flush()
time.sleep(0.4)
content = ""
if call:
nm, args = call
sse(w, {"choices": [{"delta": {"tool_calls": [{
"index": 0, "id": "c1", "type": "function",
"function": {"name": nm, "arguments": args}}]}}]})
if second:
nm, args = second
sse(w, {"choices": [{"delta": {"tool_calls": [{
"index": 1, "id": "c2", "type": "function",
"function": {"name": nm, "arguments": args}}]}}]})
else:
sse(w, {"choices": [{"delta": {"content": content}}]})
if content:
sse(w, {"choices": [{"delta": {"content": content}}]})
sse(w, {"choices": [{"delta": {},
"finish_reason": "stop"}]})
if self.include_usage:
sse(w, {"choices": [], "usage": {"prompt_tokens": 11,
"completion_tokens": 7}})
w(b"data: [DONE]\n\n")
self.wfile.flush()
return
msg = {"role": "assistant",
"content": content if content else None}
if call:
nm, args = call
msg["tool_calls"] = [{"id": "c1", "type": "function",
"function": {"name": nm,
"arguments": args}}]
if second:
nm, args = second
msg["tool_calls"].append(
{"id": "c2", "type": "function",
"function": {"name": nm, "arguments": args}})
body = json.dumps({"choices": [{"index": 0, "message": msg}],
"usage": {"prompt_tokens": 11,
"completion_tokens": 7}}).encode()
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])),
H).serve_forever()