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.
This commit is contained in:
lotherk committed 2026-11-16 14:06:54 +00:00
1 parent dd135f3b33
commit 9af7695064
10 files changed
+450 -113

No files matched your search

+16
View File
@@ -62,6 +62,22 @@ message, including the mixed-reply case, stays within the OpenAI chat shape.
Bodies may arrive with `Content-Length` or `Transfer-Encoding: chunked`; only
one request per connection is read, then the connection closes.
## Streaming
With `"stream": true` the gateway uses the provider's streaming transport and
forwards each text delta as a `chat.completion.chunk` event while it arrives -
the caller sees the answer grow instead of waiting for the last token. The
caller's tool calls are sent as one `tool_calls` delta at the end of the step,
because a name is only complete when the provider has finished it; local
`gw_*` calls stay invisible. `"stream_options":{"include_usage":true}` adds a
final usage chunk before `[DONE]`, with the token counts summed over every
upstream round of the request.
If the provider fails after the stream has started, the stream carries an
`{"error":...}` object and `[DONE]`; a request that was invalid before the
first byte is still an ordinary HTTP 400. The gateway ignores SIGPIPE, so a
caller that closes its stream early cannot kill the server.
## Examples
A local tool, executed by splinter, from the caller's point of view an ordinary
+7
View File
@@ -12,6 +12,13 @@ Stream.
## Erledigt
- **Echtes Gateway-Streaming 2026-11-16**: `stream:true` nutzt den
Streaming-Transport des Providers und schickt Text-Deltas sofort als
`chat.completion.chunk`; Caller-Tool-Calls kommen als ein Delta am Ende des
Schritts, `stream_options.include_usage` liefert die summierten Token-Zahlen
vor `[DONE]`. Fehler nach dem ersten Byte kommen als SSE-`error`; SIGPIPE ist
ignoriert. Test: `tests/stream_probe.py` prueft, dass die Chunks waehrend des
Upstream-Streams ankommen (nicht als ein Block am Ende).
- **Session-Titel 2026-11-16**: `.meta` traegt `title` (erste User-Zeile,
ueberschreibbar per `/rename [ID] TITEL`); `sessions` liefert ihn als
`title`, `/sessions` zeigt ihn. `/rm ID` entfernt JSONL, Sidecars und
+2
View File
@@ -162,6 +162,8 @@ struct sp_gen_opts {
double top_p;
int have_max_tokens;
long max_tokens;
/* streaming: ask the provider for a final usage chunk */
int include_usage;
};
struct sp_transport {
+13
View File
@@ -200,6 +200,19 @@ read_chunked(struct http_src *src, struct sp_buf *body, size_t body_max)
}
}
int
sp_http_begin_stream(int fd)
{
static const char hdr[] =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"Cache-Control: no-cache\r\n"
"X-Accel-Buffering: no\r\n"
"Connection: close\r\n\r\n";
return sp_http_write_all(fd, hdr, sizeof(hdr) - 1);
}
int
sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
size_t body_max)
+5
View File
@@ -26,6 +26,11 @@ int sp_http_bearer_is(const char *auth, const char *token);
/* one complete reply; type is the Content-Type, body is NUL-terminated */
void sp_http_reply(int fd, int code, const char *reason, const char *type,
const char *body);
/*
* Start an event stream: status 200, text/event-stream, no Content-Length,
* then the caller writes frames and closes the socket.
*/
int sp_http_begin_stream(int fd);
/* headers into hdr, exactly Content-Length bytes into body; 0 or -1 */
int sp_http_read_request(int fd, char *hdr, size_t cap,
struct sp_buf *body, size_t body_max);
+3
View File
@@ -63,6 +63,9 @@ sp_openai_request_opts(const struct sp_conv *conv, const char *model,
sp_buf_puts(out, streaming ? "\",\"stream\":true"
: "\",\"stream\":false") != 0 ||
gen_fields(out, gen) != 0 ||
(streaming && gen != NULL && gen->include_usage &&
sp_buf_puts(out, ",\"stream_options\":"
"{\"include_usage\":true}") != 0) ||
sp_buf_puts(out, ",\"messages\":[") != 0)
return -1;
+315 -110
View File
@@ -40,6 +40,7 @@
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
@@ -421,7 +422,7 @@ parse_messages(const mcp_json *req, struct sp_conv *conv, struct sp_buf *err)
static void
calls_json(const struct sp_reply *r, int only_caller, struct sp_buf *out)
{
size_t i;
size_t i, slot = 0;
int first = 1;
sp_buf_puts(out, "[");
@@ -435,7 +436,11 @@ calls_json(const struct sp_reply *r, int only_caller, struct sp_buf *out)
sp_buf_puts(out, ",");
first = 0;
sp_buf_puts(out, "{\"index\":");
sp_buf_printf(out, "%zu", i);
/*
* Filtered calls leave no gap: streaming clients key their
* accumulator by this index and expect 0, 1, ...
*/
sp_buf_printf(out, "%zu", slot++);
sp_buf_puts(out, ",\"id\":\"");
(void)sp_json_escape(out, c->id != NULL ? c->id : "call");
sp_buf_puts(out, "\",\"type\":\"function\",\"function\":{\"name\":\"");
@@ -559,9 +564,16 @@ error_json(struct sp_buf *b, const char *msg)
sp_buf_puts(b, "\",\"type\":\"invalid_request_error\"}}");
}
static void
usage_fields(struct sp_buf *b, long tin, long tout)
{
sp_buf_printf(b, "\"prompt_tokens\":%ld,\"completion_tokens\":%ld,"
"\"total_tokens\":%ld", tin, tout, tin + tout);
}
static void
completion_json(struct sp_buf *out, const char *id, const char *model,
const char *content, const struct sp_reply *rep, const char *calls)
const char *content, long tin, long tout, const char *calls)
{
char created[32];
@@ -583,73 +595,158 @@ completion_json(struct sp_buf *out, const char *id, const char *model,
}
sp_buf_puts(out, "},\"finish_reason\":\"");
sp_buf_puts(out, calls != NULL ? "tool_calls" : "stop");
sp_buf_puts(out, "\"}],\"usage\":{\"prompt_tokens\":");
sp_buf_printf(out, "%ld,\"completion_tokens\":%ld,\"total_tokens\":%ld}}",
rep != NULL ? rep->tokens_in : 0,
rep != NULL ? rep->tokens_out : 0,
rep != NULL ? rep->tokens_in + rep->tokens_out : 0);
sp_buf_puts(out, "\"}],\"usage\":{");
usage_fields(out, tin, tout);
sp_buf_puts(out, "}}");
}
static void
sse_event(struct sp_buf *out, const char *payload)
/* ------------------------------------------------------------ the stream */
/* what the upstream callback needs, and what it already sent */
struct gw_stream {
int fd;
const char *id;
const char *model;
long created;
int got_text;
int failed;
};
static int
sse_raw(int fd, const char *json)
{
sp_buf_puts(out, "data: ");
sp_buf_puts(out, payload);
sp_buf_puts(out, "\n\n");
if (sp_http_write_all(fd, "data: ", 6) != 0 ||
sp_http_write_all(fd, json, strlen(json)) != 0 ||
sp_http_write_all(fd, "\n\n", 2) != 0)
return -1;
return 0;
}
static void
completion_sse(struct sp_buf *out, const char *id, const char *model,
const char *content, const struct sp_reply *rep, const char *calls)
/*
* One chat.completion.chunk. `role`, `content` and `calls` are optional; a
* chunk may carry content and caller tool calls together (the mixed reply).
*/
static int
sse_chunk(int fd, const char *id, const char *model, long created,
const char *role, const char *content, const char *calls,
const char *finish)
{
char created[32];
struct sp_buf b;
int first = 1, rc;
(void)rep; /* usage is not part of the SSE chunks */
snprintf(created, sizeof(created), "%ld", (long)time(NULL));
sp_buf_clear(out);
{
struct sp_buf chunk;
sp_buf_init(&chunk);
sp_buf_printf(&chunk, "{\"id\":\"%s\",\"object\":"
"\"chat.completion.chunk\",\"created\":%s,\"model\":\"",
id, created);
(void)sp_json_escape(&chunk, model != NULL ? model : "");
sp_buf_puts(&chunk, "\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"");
/*
* A mixed reply carries text (the local observations) and the
* caller's calls in one delta; OpenAI allows both on a chunk.
*/
if (content != NULL && *content != '\0') {
sp_buf_puts(&chunk, ",\"content\":\"");
(void)sp_json_escape(&chunk, content);
sp_buf_puts(&chunk, "\"");
} else if (calls == NULL) {
sp_buf_puts(&chunk, ",\"content\":\"\"");
}
if (calls != NULL) {
sp_buf_puts(&chunk, ",\"tool_calls\":");
sp_buf_puts(&chunk, calls);
}
sp_buf_puts(&chunk, "},\"finish_reason\":null}]}");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
sp_buf_free(&chunk);
if (sp_buf_init(&b) != 0)
return -1;
sp_buf_puts(&b, "{\"id\":\"");
(void)sp_json_escape(&b, id);
sp_buf_printf(&b, "\",\"object\":\"chat.completion.chunk\","
"\"created\":%ld,\"model\":\"", created);
(void)sp_json_escape(&b, model != NULL ? model : "");
sp_buf_puts(&b, "\",\"choices\":[{\"index\":0,\"delta\":{");
if (role != NULL) {
sp_buf_puts(&b, "\"role\":\"");
(void)sp_json_escape(&b, role);
sp_buf_puts(&b, "\"");
first = 0;
}
{
struct sp_buf chunk;
sp_buf_init(&chunk);
sp_buf_printf(&chunk, "{\"id\":\"%s\",\"object\":"
"\"chat.completion.chunk\",\"created\":%s,\"model\":\"",
id, created);
(void)sp_json_escape(&chunk, model != NULL ? model : "");
sp_buf_printf(&chunk, "\",\"choices\":[{\"index\":0,\"delta\":{},"
"\"finish_reason\":\"%s\"}]}",
calls != NULL ? "tool_calls" : "stop");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
sp_buf_free(&chunk);
if (content != NULL) {
if (!first)
sp_buf_puts(&b, ",");
sp_buf_puts(&b, "\"content\":\"");
(void)sp_json_escape(&b, content);
sp_buf_puts(&b, "\"");
first = 0;
}
sse_event(out, "[DONE]");
if (calls != NULL) {
if (!first)
sp_buf_puts(&b, ",");
sp_buf_puts(&b, "\"tool_calls\":");
sp_buf_puts(&b, calls);
}
sp_buf_puts(&b, "},\"finish_reason\":");
if (finish != NULL) {
sp_buf_puts(&b, "\"");
(void)sp_json_escape(&b, finish);
sp_buf_puts(&b, "\"");
} else
sp_buf_puts(&b, "null");
sp_buf_puts(&b, "}]}");
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
sp_buf_free(&b);
return rc;
}
static int
sse_usage(int fd, const char *id, const char *model, long created, long tin,
long tout)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
sp_buf_puts(&b, "{\"id\":\"");
(void)sp_json_escape(&b, id);
sp_buf_printf(&b, "\",\"object\":\"chat.completion.chunk\","
"\"created\":%ld,\"model\":\"", created);
(void)sp_json_escape(&b, model != NULL ? model : "");
sp_buf_puts(&b, "\",\"choices\":[],\"usage\":{");
usage_fields(&b, tin, tout);
sp_buf_puts(&b, "}}");
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
sp_buf_free(&b);
return rc;
}
static int
sse_error(int fd, const char *msg)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
error_json(&b, msg != NULL ? msg : "error");
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
sp_buf_free(&b);
return rc;
}
static int
sse_done(int fd)
{
return sp_http_write_all(fd, "data: [DONE]\n\n", 14);
}
/* the upstream's text deltas go straight to the caller; thinking does not */
static void
gw_stream_cb(void *ctx, int kind, const char *text)
{
struct gw_stream *s = ctx;
if (s->failed || kind != SP_STREAM_TEXT || text == NULL ||
*text == '\0')
return;
if (sse_chunk(s->fd, s->id, s->model, s->created, NULL, text, NULL,
NULL) != 0)
s->failed = 1;
else
s->got_text = 1;
}
/* tool calls, finish reason, optional usage, [DONE] - in that order */
static int
stream_finish(int fd, const char *id, const char *model, long created,
const char *calls, const char *finish, int want_usage, long tin,
long tout)
{
if (calls != NULL && sse_chunk(fd, id, model, created, NULL, NULL,
calls, NULL) != 0)
return -1;
if (sse_chunk(fd, id, model, created, NULL, NULL, NULL, finish) != 0)
return -1;
if (want_usage && sse_usage(fd, id, model, created, tin, tout) != 0)
return -1;
return sse_done(fd);
}
/* ------------------------------------------------------------ one request */
@@ -702,7 +799,9 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
struct gw_tools tools;
struct sp_buf err, answer, payload;
struct sp_gen_opts gen;
int stream;
long created = (long)time(NULL);
long tokens_in = 0, tokens_out = 0;
int stream, want_usage = 0, headers_sent = 0;
unsigned long seq = ++g_seq;
char id[80];
const char *model;
@@ -739,8 +838,27 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
model = req_model != NULL && *req_model != '\0' ? req_model : o->model;
stream = mcp_arg_bool(req, "stream", 0);
parse_gen(req, &gen);
if (stream) {
const mcp_json *so = mcp_arg(req, "stream_options");
want_usage = so != NULL && mcp_arg_bool(so, "include_usage", 0);
gen.include_usage = want_usage;
}
snprintf(id, sizeof(id), "chatcmpl-%ld-%lu", (long)getpid(), seq);
/*
* Everything is parsed and the tool table is built before the first
* byte of the stream: a bad request is still a clean HTTP 400.
*/
if (stream) {
if (sp_http_begin_stream(fd) != 0)
goto out;
headers_sent = 1;
if (sse_chunk(fd, id, model, created, "assistant", "", NULL,
NULL) != 0)
goto out;
}
{
size_t max_steps = o->max_steps > 0 ? o->max_steps : GW_STEPS;
int step;
@@ -750,6 +868,7 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
&gen);
struct sp_reply rep;
struct sp_buf uerr;
struct gw_stream sc;
size_t i, nlocal = 0, nclient = 0;
int rc;
@@ -759,8 +878,17 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
goto upstream_bad;
}
memset(&rep, 0, sizeof(rep));
memset(&sc, 0, sizeof(sc));
sc.fd = fd;
sc.id = id;
sc.model = model;
sc.created = created;
sp_buf_init(&uerr);
rc = tr.send(tr.ctx, &conv, &rep, &uerr);
if (stream && tr.send_stream != NULL)
rc = tr.send_stream(tr.ctx, &conv, &rep, &uerr,
gw_stream_cb, &sc);
else
rc = tr.send(tr.ctx, &conv, &rep, &uerr);
sp_transport_dispose(&tr);
if (rc != 0) {
sp_buf_printf(&err, "upstream: %s",
@@ -771,6 +899,26 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
goto upstream_bad;
}
sp_buf_free(&uerr);
tokens_in += rep.tokens_in > 0 ? rep.tokens_in : 0;
tokens_out += rep.tokens_out > 0 ? rep.tokens_out : 0;
if (sc.failed) {
/* the caller went away mid-stream */
sp_reply_free(&rep);
goto out;
}
/*
* A transport without a working callback, or a stream
* that carried no text: send the answer we have, so a
* quiet upstream never looks like an empty answer.
*/
if (stream && !sc.got_text && rep.content != NULL &&
*rep.content != '\0') {
if (sse_chunk(fd, id, model, created, NULL,
rep.content, NULL, NULL) != 0) {
sp_reply_free(&rep);
goto out;
}
}
for (i = 0; i < rep.ncalls; i++) {
if (rep.calls[i].name != NULL &&
strncmp(rep.calls[i].name, GW_PREFIX,
@@ -781,15 +929,22 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
}
if (nlocal == 0 && nclient == 0) {
/* the answer */
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model,
answer.p, &rep, NULL);
else
if (stream) {
if (stream_finish(fd, id, model,
created, NULL, "stop", want_usage,
tokens_in, tokens_out) != 0) {
sp_reply_free(&rep);
goto out;
}
} else {
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer,
rep.content);
completion_json(&payload, id, model,
answer.p, &rep, NULL);
answer.p, tokens_in, tokens_out,
NULL);
}
sp_reply_free(&rep);
break;
}
@@ -799,12 +954,11 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
sp_buf_init(&notes);
/*
* Local calls belong to this host. With no
* caller calls they continue the loop and the
* caller only sees the answer; a mixed reply
* cannot be continued here (its caller calls
* still need results), so it goes back with
* the local observations in the content and
* the caller's calls in tool_calls.
* caller calls they continue the loop; a mixed
* reply cannot be continued here (its caller
* calls still need results), so the caller's
* calls go out in tool_calls and the local
* observations in the content.
*/
if (nclient == 0) {
sp_buf_init(&local);
@@ -845,27 +999,45 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
sp_buf_init(&calls);
calls_json(&rep, 1, &calls);
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer,
rep.content);
if (notes.len > 0) {
if (answer.len > 0)
if (stream) {
if (notes.len > 0 &&
sse_chunk(fd, id, model,
created, NULL, notes.p, NULL,
NULL) != 0) {
sp_buf_free(&calls);
sp_buf_free(&notes);
sp_reply_free(&rep);
goto out;
}
if (stream_finish(fd, id, model,
created, calls.p,
"tool_calls", want_usage,
tokens_in, tokens_out) != 0) {
sp_buf_free(&calls);
sp_buf_free(&notes);
sp_reply_free(&rep);
goto out;
}
} else {
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer,
"\n\n");
sp_buf_puts(&answer,
"local gateway tools ran on "
"the splinter host:\n");
sp_buf_puts(&answer, notes.p);
}
if (stream)
completion_sse(&payload, id,
model, answer.p, &rep,
calls.p);
else
rep.content);
if (notes.len > 0) {
if (answer.len > 0)
sp_buf_puts(&answer,
"\n\n");
sp_buf_puts(&answer,
"local gateway tools "
"ran on the splinter "
"host:\n");
sp_buf_puts(&answer,
notes.p);
}
completion_json(&payload, id,
model, answer.p, &rep,
calls.p);
model, answer.p, tokens_in,
tokens_out, calls.p);
}
sp_buf_free(&calls);
sp_buf_free(&notes);
sp_reply_free(&rep);
@@ -884,15 +1056,23 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
sp_buf_init(&calls);
calls_json(&rep, 0, &calls);
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model,
answer.p, &rep, calls.p);
else
if (stream) {
if (stream_finish(fd, id, model, created,
calls.p, "tool_calls", want_usage,
tokens_in, tokens_out) != 0) {
sp_buf_free(&calls);
sp_reply_free(&rep);
goto out;
}
} else {
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer,
rep.content);
completion_json(&payload, id, model,
answer.p, &rep, calls.p);
answer.p, tokens_in, tokens_out,
calls.p);
}
sp_buf_free(&calls);
}
sp_reply_free(&rep);
@@ -904,17 +1084,31 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
goto upstream_bad;
}
}
sp_http_reply(fd, 200, "OK", stream ? "text/event-stream" :
"application/json", payload.p != NULL ? payload.p : "{}");
if (!stream)
sp_http_reply(fd, 200, "OK", "application/json",
payload.p != NULL ? payload.p : "{}");
goto out;
bad:
error_json(&payload, err.p != NULL ? err.p : "bad request");
sp_http_reply(fd, 400, "Bad Request", "application/json", payload.p);
if (headers_sent) {
(void)sse_error(fd, err.p != NULL ? err.p : "bad request");
(void)sse_done(fd);
} else {
error_json(&payload, err.p != NULL ? err.p : "bad request");
sp_http_reply(fd, 400, "Bad Request", "application/json",
payload.p);
}
goto out;
upstream_bad:
error_json(&payload, err.p != NULL ? err.p : "upstream failed");
sp_http_reply(fd, 502, "Bad Gateway", "application/json", payload.p);
if (headers_sent) {
(void)sse_error(fd, err.p != NULL ? err.p : "upstream failed");
(void)sse_done(fd);
} else {
error_json(&payload,
err.p != NULL ? err.p : "upstream failed");
sp_http_reply(fd, 502, "Bad Gateway", "application/json",
payload.p);
}
out:
sp_buf_free(&payload);
sp_buf_free(&answer);
@@ -1051,6 +1245,11 @@ sp_openai_serve(const struct sp_gateway_opts *o, struct sp_buf *err)
close(s);
return -1;
}
/*
* A caller that closes its stream early must not kill the gateway with
* SIGPIPE; the write returns EPIPE and the request ends.
*/
(void)signal(SIGPIPE, SIG_IGN);
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_signal;
sigemptyset(&sa.sa_mask);
@@ -1070,6 +1269,12 @@ sp_openai_serve(const struct sp_gateway_opts *o, struct sp_buf *err)
break;
}
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
{
int one_tcp = 1;
(void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
&one_tcp, sizeof(one_tcp));
}
serve_one(fd, o, token);
close(fd);
}
+20 -3
View File
@@ -2,11 +2,11 @@
# 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
import http.server, json, sys, time
def sse(w, obj):
w.write(("data: " + json.dumps(obj) + "\n\n").encode())
w(("data: " + json.dumps(obj) + "\n\n").encode())
class H(http.server.BaseHTTPRequestHandler):
@@ -28,6 +28,11 @@ class H(http.server.BaseHTTPRequestHandler):
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"),
@@ -54,12 +59,18 @@ class H(http.server.BaseHTTPRequestHandler):
return self.reply(stream, call=("gw_echo",
'{"text": "hallo-vom-gw"}'))
def reply(self, stream, content="", call=None, second=None):
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": [{
@@ -72,9 +83,15 @@ class H(http.server.BaseHTTPRequestHandler):
"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}
+54
View File
@@ -0,0 +1,54 @@
#!/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))
+15
View File
@@ -110,6 +110,7 @@ checkgrep 'ERGEBNIS: client-result' "$D/caller2.json"
post "$P1" '{"model":"x","messages":[{"role":"user","content":"mixed"}]}' \
"$D/mixed.json"
checkgrep '"name":"caller_tool"' "$D/mixed.json"
checkgrep '"index":0,"id":"c2"' "$D/mixed.json"
checkgrep 'mixed-local' "$D/mixed.json"
checkgrep '"finish_reason":"tool_calls"' "$D/mixed.json"
@@ -155,6 +156,20 @@ curl -sN -X POST "http://127.0.0.1:$P1/v1/chat/completions" \
checkgrep 'gestreamt' "$D/stream.txt"
checkgrep '\[DONE\]' "$D/stream.txt"
# ... and with include_usage the caller gets the provider's counts
curl -sN -X POST "http://127.0.0.1:$P1/v1/chat/completions" \
-H 'Content-Type: application/json' \
-d '{"model":"x","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"stream bitte"}]}' \
> "$D/usage.txt"
checkgrep '"usage"' "$D/usage.txt"
checkgrep '"prompt_tokens":11' "$D/usage.txt"
checkgrep '"completion_tokens":7' "$D/usage.txt"
# the answer really arrives in pieces instead of one chunk at the end
python3 -I tests/stream_probe.py "$P1" slowstream > "$D/probe.txt" 2>&1
check test $? -eq 0
checkgrep 'streaming: ' "$D/probe.txt"
# a token is required when one is configured
check test "$(curl -s -o /dev/null -w '%{http_code}' -X POST \
"http://127.0.0.1:$P3/v1/chat/completions" -H 'Content-Type: application/json' \