From 9d81236b354f692e8678e5c30decefa1a4189231 Mon Sep 17 00:00:00 2001 From: Hermes Date: Sat, 7 Nov 2026 15:11:12 +0000 Subject: [PATCH] junction: Bilder nur in den Nachrichten, Grenzen aus der API des Endpunkts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ein Scan über den ganzen Rumpf machte jede Anfrage mit Werkzeugen zur Bildanfrage: Hermes schickt das Schema von vision_analyze mit, darin steht der Parameter image_url. Die Anfrage landete damit in der Bildkette, wo ein kleiner lokaler Knoten am Kontext scheitert und der einzige Cloud-Knoten bei Überlast 429 liefert — der Client sah "provider unavailable", obwohl die Textkette daneben gesund war. Gesucht wird jetzt nur in messages: ein type-Feld mit image_url, input_image oder image, oder image_url direkt vor einem Objekt/einer Zeichenkette. Escapte Erwähnungen in Werkzeugausgaben treffen bewusst nicht (dort steht ein Backslash zwischen type und Doppelpunkt). Ein Rumpf ohne messages-Array fällt auf den alten Scan zurück — lieber ein Bild zu viel als eines, das beim Textmodell landet. Zweitens: veröffentlicht die Modellliste keine Grenzen, fragt junction die eigene API des Endpunkts. ollama.com nennt in /api/show model_info[".context_length"] — kimi-k2.6 etwa 262144 statt der angenommenen 128000. Erst ein Modell als Probe; antwortet es nicht, spart das die übrigen Anfragen. Gelesen, nicht geschätzt. Tests: ein Werkzeug-Schema, das image_url beschreibt, bleibt Text; eine zitierte Bild-Antwort in einer Werkzeugausgabe bleibt Text; ein echtes Bild geht weiter in die Bildkette; und eine nur über /api/show veröffentlichte Grenze schlägt die Endpunktzahl (1.000.000 gegen 1000). README beschreibt beides und nennt die Prüfungen jetzt beim Namen. make test: PASS, 130 Prüfungen. --- README.md | 34 ++++++++++++++++++++++-- src/compress.c | 8 +++--- src/compress.h | 4 +++ src/junction.c | 58 ++++++++++++++++++++++++++++------------ src/models.c | 64 ++++++++++++++++++++++++++++++++++++++++++++- tests/ctx-vision.sh | 47 +++++++++++++++++++++++++++++++++ 6 files changed, 193 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index db23ea0..368d41c 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ A worked, annotated configuration for a mixed local/cloud setup is in ```bash make # -> ./junction (TLS auto-detected via openssl headers) make J_WITH_TLS=0 # dependency-free build: http:// upstreams only -make test # stub endpoints, no network, no models (~40 s) +make test # stub endpoints, no network, no models (~2.5 min) sudo make install # /usr/local/bin + /usr/local/share/junction ./junction --config junction.conf [--port 8090] @@ -143,6 +143,31 @@ req [for ] [path ] [need >N | .context_length"]`, which is where its real windows live. Only when +both are silent does the endpoint's `context` key apply. Nothing in that chain is +estimated, and `need` still reads only the budget the client declared. + ## Keys Global: `listen`, `connect_timeout_ms`, `offline_hold_s`, `max_body_bytes`, @@ -272,7 +297,12 @@ failover, hook retry, `still_working`, block rules, catch-all, model rewrite, `no_matching_rule`, config errors, chunked request decoding (byte-exact body), cache miss/hit/flush/bypass, header passthrough and injection, TLS listener, https upstream, and that certificate verification actually refuses a self-signed peer. -Pass = `PASS` (49 checks), including two that would have caught the two mistakes this +The suite also pins the two distinctions that are easy to get wrong: an image counts +only inside `messages` (a tool schema naming `image_url` and an escaped image part in a +tool result both stay text, while a real image part still reaches the vision chain), +and a limit published only in the endpoint's own API (`/api/show`) still beats the +number in the endpoint block. +Pass = `PASS` (130 checks), including two that would have caught the two mistakes this design invites: a serial stub making a concurrent router look serialised, and a "waiting" comment leaking into a caller that never asked for a stream. diff --git a/src/compress.c b/src/compress.c index f270ca0..ef7cc28 100644 --- a/src/compress.c +++ b/src/compress.c @@ -258,8 +258,10 @@ static int jc_object_fields(const char *s, size_t n, size_t obj_start, size_t ob return have_content && *is_tool; } -/* Findet im Top-Level-Objekt das Array "messages" und liefert dessen Elementgrenzen. */ -static int jc_find_messages(const char *s, size_t n, size_t *arr_start, size_t *arr_end) +/* Findet im Top-Level-Objekt das Array "messages" und liefert dessen Elementgrenzen. + * Öffentlich, weil auch die Bilderkennung nur in den Nachrichten suchen darf und den + * Bereich nicht ein zweites Mal zerlegen soll. */ +int jcomp_find_messages(const char *s, size_t n, size_t *arr_start, size_t *arr_end) { size_t i = 0; skip_ws(s, n, &i); @@ -300,7 +302,7 @@ int jcomp_messages(const char *body, size_t len, int keep_last, size_t min_bytes if (!body || !len || !out || !out_len) return -1; size_t arr_s, arr_e; - if (jc_find_messages(body, len, &arr_s, &arr_e)) return -1; + if (jcomp_find_messages(body, len, &arr_s, &arr_e)) return -1; /* Elemente zählen, damit "die letzten N bleiben" auch bei wenigen Nachrichten gilt. */ int nmsg = 0; diff --git a/src/compress.h b/src/compress.h index 5e1e1c1..29d7f79 100644 --- a/src/compress.h +++ b/src/compress.h @@ -22,4 +22,8 @@ typedef struct { int jcomp_messages(const char *body, size_t len, int keep_last, size_t min_bytes, char **out, size_t *out_len, jcomp_stats *st); +/* Grenzen des Top-Level-Arrays "messages" im Rumpf: [*arr_start, *arr_end) zeigt auf + * die einschließenden Klammern, 0 = gefunden, -1 = kein solches Array. */ +int jcomp_find_messages(const char *body, size_t len, size_t *arr_start, size_t *arr_end); + #endif diff --git a/src/junction.c b/src/junction.c index e295fee..5176e92 100644 --- a/src/junction.c +++ b/src/junction.c @@ -192,25 +192,51 @@ static long declared_max_tokens(const char *body) return mt; } -/* Trägt die Anfrage ein Bild? Gesucht wird nach den drei Formen, die in - * OpenAI-kompatiblen Rümpfen vorkommen: content-Teil image_url, Responses-API - * input_image, und type=image. Ein Textmodell, das so einen Rumpf bekommt, - * antwortet oft mit leerem Inhalt statt mit einem Fehler — deshalb muss die - * Zustellung vorher entschieden werden, nicht hinterher bemerkt. - */ +/* Sucht im Bereich [b, e) nach einem Bild-Inhalt. Erkannt wird ein "type"-Feld mit + * dem Wert image_url, input_image oder image. Clients, die den Typ weglassen, schicken + * "image_url" direkt gefolgt von einem Objekt oder einer Zeichenkette — auch das zählt. + * Escapte Erwähnungen in Werkzeugausgaben ("\"type\":\"image_url\"") treffen bewusst + * nicht: zwischen `type` und dem Doppelpunkt steht dort ein Backslash. */ +static int region_has_image(const char *b, const char *e) +{ + for (const char *p = strstr(b, "\"type\""); p && p < e; p = strstr(p + 6, "\"type\"")) { + const char *v = p + 6; + while (v < e && (*v == ':' || isspace((unsigned char)*v))) v++; + if (v >= e || *v != '"') continue; + v++; + if (!strncmp(v, "image_url\"", 10)) return 1; + if (!strncmp(v, "input_image\"", 12)) return 1; + if (!strncmp(v, "image\"", 6)) return 1; + } + for (const char *p = strstr(b, "\"image_url\""); p && p < e; + p = strstr(p + 11, "\"image_url\"")) { + const char *v = p + 11; + while (v < e && (*v == ':' || isspace((unsigned char)*v))) v++; + if (v < e && (*v == '{' || *v == '"')) return 1; + } + return 0; +} + +/* Trägt die Anfrage ein Bild? Ein Textmodell, das so einen Rumpf bekommt, antwortet oft + * mit leerem Inhalt statt mit einem Fehler — deshalb muss die Zustellung vorher + * entschieden werden, nicht hinterher bemerkt. + * + * Gesucht wird nur in den Nachrichten, nicht im ganzen Rumpf. Ein Rumpf-Scan machte jede + * Anfrage mit Werkzeugen zu einer Bildanfrage, weil Werkzeug-Schemata Parameter namens + * `image_url` beschreiben (Hermes' vision_analyze tut das): die Anfrage landete damit in + * der Bildkette, wo ein kleiner lokaler Knoten am Kontext scheitert und der einzige + * Cloud-Knoten bei Ueberlast 429 liefert — der Client sah "provider unavailable", obwohl + * die Textkette daneben gesund war. Fehlt ein messages-Array (andere Rumpfform), wird + * weiter der ganze Rumpf geprüft: lieber ein Bild zu viel als eines, das beim + * Textmodell landet. */ static int body_has_image(const char *body) { if (!body) return 0; - if (strstr(body, "\"image_url\"")) return 1; - if (strstr(body, "\"input_image\"")) return 1; - const char *p = body; - while ((p = strstr(p, "\"type\"")) != NULL) { - const char *v = p + 6; - while (*v && (*v == ':' || isspace((unsigned char)*v))) v++; - if (!strncmp(v, "\"image\"", 7)) return 1; - p += 6; - } - return 0; + size_t len = strlen(body); + size_t as = 0, ae = 0; + if (jcomp_find_messages(body, len, &as, &ae) == 0) + return region_has_image(body + as, body + ae); + return region_has_image(body, body + len); } /* Geschätzte Prompt-Größe in Token. diff --git a/src/models.c b/src/models.c index c71b08b..7455d22 100644 --- a/src/models.c +++ b/src/models.c @@ -170,6 +170,44 @@ done: return found; } +/* Manche Endpunkte veröffentlichen ihre Grenzen nicht in der OpenAI-Liste, sondern + * in ihrer eigenen API. ollama.com tut das: /api/show liefert + * model_info[".context_length"] — kimi-k2.6 etwa 262144, nicht 128000. + * Das ist gelesen, nicht geschätzt. Fehlt der Endpunkt, kommt 0 zurück. */ +static long publish_context_length(const char *root, const char *model, + const j_endpoint *ep) +{ + char cmd[J_MODELS_CMD]; + int off = snprintf(cmd, sizeof cmd, "curl -sS -m 6 -X POST "); + const char *key = ep->api_key_env[0] ? getenv(ep->api_key_env) : NULL; + if (key && *key) + off += snprintf(cmd + off, sizeof cmd - (size_t)off, + "-H 'Authorization: Bearer %s' ", key); + off += snprintf(cmd + off, sizeof cmd - (size_t)off, + "-H 'Content-Type: application/json' -d '{\"model\":\"%s\"}' " + "'%s/api/show' 2>/dev/null", model, root); + if (off <= 0 || (size_t)off >= sizeof cmd) return 0; + + FILE *f = popen(cmd, "r"); + if (!f) return 0; + char buf[8192]; + size_t len = fread(buf, 1, sizeof buf - 1, f); + pclose(f); + if (len == 0) return 0; + buf[len] = '\0'; + + /* "…context_length":262144 — das Feld heißt je nach Architektur anders + * ("kimi-k2.context_length", "llama.context_length"), der Schwanz ist gleich. */ + const char *end = buf + len; + for (const char *p = buf; (p = find_in(p, end, "context_length")) != NULL; p += 14) { + const char *colon = find_in(p, end, ":"); + if (!colon) continue; + long v = long_after(colon, end); + if (v > 0) return v; + } + return 0; +} + /* Holt /models. Header und Schlüssel sind die des Endpunkts — ohne die * antwortet ein Cloudflare-geschützter Anbieter mit 403 statt mit einer Liste. */ static int fetch_json(const j_endpoint *ep, char **out, size_t *out_len) @@ -255,7 +293,31 @@ void j_models_refresh_all(void) CFG.log_prefix, ep->name); continue; } - fprintf(stderr, "[%s] models: %s %d Modelle", CFG.log_prefix, ep->name, n); + /* Veröffentlicht die Liste keine Grenzen, fragt junction die eigene API des + * Endpunkts (ollama.com: /api/show). Erst ein Modell als Probe: antwortet es + * nicht, sind die übrigen Anfragen nur Wartezeit. */ + int filled = 0; + if (ep->models[0].ctx == 0) { + char root[J_URL_MAX]; + snprintf(root, sizeof root, "%s", ep->base); + size_t rl = strlen(root); + while (rl > 0 && root[rl - 1] == '/') root[--rl] = '\0'; + if (rl >= 3 && !strcmp(root + rl - 3, "/v1")) root[rl - 3] = '\0'; + + long probe = publish_context_length(root, ep->models[0].id, ep); + if (probe > 0) { + ep->models[0].ctx = probe; + filled = 1; + for (int k = 1; k < ep->model_count; k++) { + if (ep->models[k].ctx > 0) continue; + long v = publish_context_length(root, ep->models[k].id, ep); + if (v > 0) { ep->models[k].ctx = v; filled++; } + } + } + } + + fprintf(stderr, "[%s] models: %s %d Modelle%s", CFG.log_prefix, ep->name, n, + filled ? " (Grenzen aus /api/show)" : ""); for (int k = 0; k < ep->model_count && k < 3; k++) fprintf(stderr, "%s%s ctx=%ld out=%ld", k ? "," : " ·", ep->models[k].id, ep->models[k].ctx, ep->models[k].out); diff --git a/tests/ctx-vision.sh b/tests/ctx-vision.sh index 742d4db..35a62c1 100644 --- a/tests/ctx-vision.sh +++ b/tests/ctx-vision.sh @@ -60,6 +60,23 @@ R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ -d "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"kurz\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/png;base64,$IMG\"}}]}],\"max_tokens\":8}" "$BASE") contains "$R" "served by SLOW" "base64 payload does not inflate the estimate into the wrong rule" +# 4b. Ein Werkzeug-Schema, das einen Parameter `image_url` BESCHREIBT, ist kein Bild. +# Hermes schickt bei jeder Anfrage das Schema von vision_analyze mit; ein Scan über +# den ganzen Rumpf machte daraus eine Bildanfrage, und die landete in der Bildkette. +R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"kurz"}],"tools":[{"type":"function","function":{"name":"vision_analyze","parameters":{"type":"object","properties":{"image_url":{"type":"string","description":"Image URL"}},"required":["image_url"]}}}],"max_tokens":8}' "$BASE") +contains "$R" "served by GATED" "a tool schema naming image_url is not an image request" + +# 4c. Dasselbe für eine Werkzeugausgabe, die den Bild-Teil als Text zitiert (escapt). +R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"kurz"},{"role":"tool","content":"{\"type\":\"image_url\",\"image_url\":{\"url\":\"x\"}}"}],"max_tokens":8}' "$BASE") +contains "$R" "served by GATED" "an escaped image part inside a tool result stays text" + +# 4d. Und mit Werkzeugen im Rumpf geht ein echtes Bild weiterhin an die Bildkette. +R=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":"was ist das"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo="}}]}],"tools":[{"type":"function","function":{"name":"vision_analyze","parameters":{"type":"object","properties":{"image_url":{"type":"string"}}}}}],"max_tokens":8}' "$BASE") +contains "$R" "served by SLOW" "a real image part still wins over the tool schema" + # 5. Ein Text-Endpunkt wird für ein Bild gar nicht erst versucht cat > "$TMP/ctx2.conf" </dev/null; sleep 0.3 done + +# 9. Zweite Quelle: die eigene API des Endpunkts. +# Die OpenAI-Liste schweigt (kein limit), aber /api/show nennt 1.000.000 — +# ollama.com macht das so. Der Endpunkt-Block sagt 1000. Der Prompt hat ~5000. +P_SHOW=$((PORT+28)) +P_SHOWJ=$((PORT+29)) +STUB_SHOW_CTX=1000000 tests/stub $P_SHOW "SHOWCTX" & PIDS+=($!) +sleep 0.3 +cat > "$TMP/show.conf" < "$TMP/show.log" 2>&1 & PIDS+=($!) +# Die Grenze kommt aus einem zweiten Abruf; kurz warten, statt zu raten. +for i in $(seq 1 40); do + grep -q "Grenzen aus /api/show" "$TMP/show.log" && break + sleep 0.1 +done +BIGP=$(python3 -c "print('wort ' * 4000)") +R=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \ + -d "{\"model\":\"SHOWCTX\",\"messages\":[{\"role\":\"user\",\"content\":\"$BIGP\"}],\"max_tokens\":8}" \ + "http://127.0.0.1:$P_SHOWJ/v1/chat/completions") +contains "$R" "served by SHOWCTX" "a limit published only in the endpoint's own API counts too"