Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Native image input: --vision-urls fetches public HTTPS image URLs as …
…0.6.6 did

media_fetch.zig follows images_http.py: an https URL on port 443 without
credentials, a fragment, a backslash or controls; every address the host
resolves to public (Python's is_global less 192.0.0.0/24 and
168.63.129.16; IPv6 global unicast only, no 6to4 or Teredo); TLS verified
for the host on the address that was checked; GET with identity encoding;
up to 3 redirects, each checked again; the declared media type JPEG, PNG
or WebP (WebP is then refused by its bytes, as with data URLs); the bytes
within what the request has left of 10 MB an image and 20 MB in all;
10 s a download and 30 s for a request's downloads. std's connect has no
timeout yet: a nonblocking connect and poll bound it, the socket's send
and receive timeouts bound the rest.

The HTTP exchange reads from any reader, so the response rules (redirects
joined and rechecked, status, types, lengths, chunking, encodings, the
deadline) are tested against canned responses; the URL and address rules
are tested directly. Without --vision-urls an https part is refused with
the flag's name, other schemes as 0.6.6 refused them; --vision-urls needs
--vision. tools/zig/vision_urls_served.py checks a served model against
public hosts.
  • Loading branch information
BobClawblaw committed Oct 14, 2026
commit ca7438af4190f8dde80091029b351f7f808b165d
3 changes: 2 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ chat fields that shape the prompt (`tools`, `reasoning_effort`, `chat_template_k
request, images expanded. `/detokenize` takes `tokens` and returns `prompt`.
In the Python 0.6.6 engine, `--vision` lets supported Qwen3.5/3.8 dense checkpoints accept `image_url` content parts
alongside text in user messages and in tool results (`role: "tool"`), such as an agent's screenshots. The native
server reads images for GLM-5.3-Flash on Metal, with data URLs only ([image input](vision.md#the-native-server)).
server reads images for GLM-5.3-Flash on Metal, with data URLs, and public HTTPS URLs under `--vision-urls`
([image input](vision.md#the-native-server)).
See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior.
The native binary refuses `--vision` and answers image parts with HTTP 400.
Unsupported image input, audio, video and non-text output requests receive HTTP 400.
Expand Down
12 changes: 10 additions & 2 deletions docs/vision.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,16 @@ For Qwen, each image request carries its own multimodal rotary positions and con
4,096) for engines that read images; GLM-5.3-Flash on one Mac reads them so far, and other native engines refuse the
flag at startup.

- Images arrive as `image_url` data URLs in user messages and tool results. Remote URLs are refused, since
`--vision-urls` isn't on the native server yet.
- Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs
`--vision`), a part may name a public HTTPS URL instead, fetched as 0.6.6 fetched it: port 443 without credentials
or a fragment; every address the host resolves to public (no private, loopback, link-local, carrier-grade NAT,
documentation, multicast or metadata address, and for IPv6 global unicast only, without 6to4 or Teredo); TLS
verified for the host against the system's certificates, on the address that was checked; up to 3 redirects,
each checked again; a declared `image/jpeg`, `image/png` or `image/webp`, uncompressed; 10 MB an image and 20 MB
a request across data URLs and downloads; 10 s a download and 30 s a request's downloads. The refusals are
0.6.6's words; a TLS failure, like any other failed connection, is "image download failed or timed out". Host
names that aren't ASCII and IPv6 address literals are refused. Without the flag, an HTTPS URL is refused with the
flag's name.
- PNG and JPEG are decoded by the platform's decoder (ImageIO on macOS). WebP is refused by name until a decoder
exists; other formats are refused.
- The limits and the processing are 0.6.6's: EXIF orientation, alpha composited over white, the GLM5-Next processor's
Expand Down
20 changes: 16 additions & 4 deletions tools/zig/vision_served.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks)."""
"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks).

python tools/zig/vision_served.py --url http://127.0.0.1:8000 --images DIR

DIR holds PNG and JPEG test images. Checks: an image request answers, and text or a tool result that quotes the
model's image marker beside a real image is ordinary text (images come from the request's image parts, #511); drafted
equals ``"draft": false`` and concurrent equals alone with images; an image conversation's next turn resumes past
its image, and another image under the same placeholders resumes none of the first one's rows; and the refusals (WebP by name, other formats, an image outside a
user or tool message, too many images, remote URLs without --vision-urls, bad data URLs, a bad detail); tools/zig/vision_urls_served.py
checks a server started with --vision-urls.
"""

from __future__ import annotations

Expand Down Expand Up @@ -107,7 +117,9 @@ def check(label: str, ok: bool, detail: str = "") -> None:
same = sum(x == y for x, y in zip(alone, together))
check("concurrent image requests equal their runs alone", same == len(runs), f"{same} of {len(runs)}")

# the prompt cache keeps state at planned cuts (system, a 256+ token reply): turn three resumes past turn 2's image
# the prompt cache keeps a turn's state at its planned cuts (GLM: the shared system cut, and a reply of 256+ tokens),
# so a conversation's third turn resumes past an image its second turn kept. Image B under the same text and
# placeholder ids resumes at most the text before its image, and answers as a server with nothing kept
system = {"role": "system", "content": " ".join(f"Rule {i}: describe what you see plainly and briefly." for i in range(120))}
q, q2, q3 = "What is shown?", "Say that again in three words.", "And once more."
head = ask([system, user(text(q))], tokens=1)[1]["usage"]["prompt_tokens"] # the text alone: past where an image starts
Expand All @@ -125,7 +137,6 @@ def turns(url: str) -> tuple[list, list]:
code, ra = ask(three_a, tokens=24)
cached_a = ra.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1
check("an image conversation's later turn resumes past its image", code == 200 and cached_a > head, f"cached {cached_a} of {ra.get('usage', {}).get('prompt_tokens')}; the text alone is {head}")
# image B under the same text and placeholder ids resumes at most the text before its image
code, rb = ask(three_b, tokens=24)
cached_b = rb.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1
check("another image under the same placeholders resumes only the text before it", code == 200 and cached_b < head,
Expand All @@ -141,7 +152,8 @@ def turns(url: str) -> tuple[list, list]:
("GIF", [user(image_part(data_url(gif, "image/gif")), text("hi"))], "not PNG or JPEG"),
("an image in an assistant message", [user(text("hi")), {"role": "assistant", "content": [image_part(url_a)]}, user(text("ok"))], "user and tool messages only"),
("too many images", [user(*[image_part(url_a)] * 5, text("hi"))], "at most"),
("a remote URL", [user(image_part("https://example.com/cat.png"), text("hi"))], "data: URL"),
("a remote URL without --vision-urls", [user(image_part("https://example.com/cat.png"), text("hi"))], "--vision-urls"),
("a URL that is neither data nor https", [user(image_part("http://example.com/cat.png"), text("hi"))], "data URLs or public HTTPS URLs"),
("bad base64", [user(image_part("data:image/png;base64,@@@@"), text("hi"))], "encoding"),
("a bad detail", [user(image_part(url_a, "medium"), text("hi"))], "detail"),
("bytes that decode as nothing", [user(image_part(data_url(b"\x89PNG\r\n\x1a\n" + bytes(32), "image/png")), text("hi"))], "could not be decoded"),
Expand Down
109 changes: 109 additions & 0 deletions tools/zig/vision_urls_served.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""Image URLs served end to end on a running ``tensorfold-native --vision --vision-urls`` (#565's URL checks).

python tools/zig/vision_urls_served.py --url http://127.0.0.1:8000

Checks, against public hosts: an HTTPS image URL answers exactly as the same bytes sent as a data URL (the prompt's
tokens and the greedy reply), and so does a URL that redirects to it; a URL and a data URL in one request; and the
refusals images_http.py gave, before any token (HTTP status, content type, a host that resolves to a private
address, a name that is never public, an address literal that isn't public, TLS that doesn't verify, a scheme, port,
credentials or fragment the URL rules refuse, an unresolvable host). The fetch's own rules (redirect limits,
lengths, chunking, encodings, deadlines) are the unit tests in zig/src/server/media_fetch.zig.
"""

from __future__ import annotations

import argparse
import base64
import json
import ssl
import sys
import urllib.error
import urllib.request

IMAGE = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-hero.png"
REDIRECT = "https://github.com/ashhart/TensorFold/raw/main/assets/tensorfold-hero.png" # 302 to IMAGE's host
OTHER = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-cuda-banner.png"


def post(url: str, body: dict) -> tuple[int, dict]:
req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=1800) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")


def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--url", default="http://127.0.0.1:8000")
ap.add_argument("--tokens", type=int, default=48)
args = ap.parse_args()
with urllib.request.urlopen(args.url + "/v1/models") as r:
model = json.loads(r.read())["data"][0]["id"]
try: # python.org's macOS builds ship no CA store until "Install Certificates" runs
import certifi
tls = ssl.create_default_context(cafile=certifi.where())
except ImportError:
tls = ssl.create_default_context()
with urllib.request.urlopen(IMAGE, timeout=30, context=tls) as r:
inline = "data:image/png;base64," + base64.b64encode(r.read()).decode()
failures = 0

def ask(*parts) -> tuple[int, dict]:
return post(args.url, {"model": model, "messages": [{"role": "user", "content": list(parts)}], "max_tokens": args.tokens,
"temperature": 0, "chat_template_kwargs": {"enable_thinking": False}})

def image(url: str) -> dict:
return {"type": "image_url", "image_url": {"url": url}}

def text(t: str) -> dict:
return {"type": "text", "text": t}

def check(label: str, ok: bool, detail: str = "") -> None:
nonlocal failures
failures += not ok
print(f"{'ok ' if ok else 'FAIL'} {label}{': ' + detail if detail else ''}")

def same(label: str, a: tuple[int, dict], b: tuple[int, dict]) -> None:
ok = a[0] == 200 and b[0] == 200 and a[1]["usage"]["prompt_tokens"] == b[1]["usage"]["prompt_tokens"] and \
a[1]["choices"][0]["message"]["content"] == b[1]["choices"][0]["message"]["content"]
detail = f"HTTP {a[0]}/{b[0]}" if a[0] != 200 or b[0] != 200 else \
f"{a[1]['usage']['prompt_tokens']} prompt tokens, {a[1]['choices'][0]['message']['content'][:60]!r}"
if a[0] != 200 or b[0] != 200:
detail += " " + json.dumps(a[1].get("error") or b[1].get("error"))[:120]
check(label, ok, detail)

q = text("Describe this image in one sentence.")
by_data = ask(image(inline), q)
same("an HTTPS image URL answers as its bytes in a data URL", ask(image(IMAGE), q), by_data)
same("a URL that redirects to the image answers the same", ask(image(REDIRECT), q), by_data)
two = ask(image(OTHER), image(inline), text("How do these two images differ?"))
check("a URL and a data URL in one request answer", two[0] == 200, f"HTTP {two[0]} {json.dumps(two[1].get('error', ''))[:100]}")

refusals = [
("an HTTP error", "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/no-such-image.png", "image download returned HTTP 404"),
("a page that isn't an image", "https://example.com/", "image URL content type must be JPEG, PNG or WebP"),
("a host that resolves to a private address", "https://localtest.me/x.png", "image URLs must resolve only to public internet addresses"),
("a private address literal", "https://169.254.169.254/latest/meta-data", "image URLs must resolve only to public internet addresses"),
("localhost", "https://localhost/x.png", "image URLs must use public internet hosts"),
("cloud metadata by name", "https://metadata.google.internal/x.png", "image URLs must use public internet hosts"),
("an expired certificate", "https://expired.badssl.com/", "image download failed or timed out"),
("a certificate for another host", "https://wrong.host.badssl.com/", "image download failed or timed out"),
("a self-signed certificate", "https://self-signed.badssl.com/", "image download failed or timed out"),
("plain HTTP", "http://example.com/x.png", "images require data URLs or public HTTPS URLs"),
("another port", "https://example.com:8443/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"),
("credentials", "https://user:pw@example.com/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"),
("a fragment", "https://example.com/x.png#a", "image URL must be HTTPS on port 443, without credentials or a fragment"),
("a host that never resolves", "https://no-such-host.invalid/x.png", "image host could not be resolved"),
]
for label, url, words in refusals:
code, r = ask(image(url), text("hi"))
message = r.get("error", {}).get("message", json.dumps(r))
check(f"refused {label}", code == 400 and message == words, f"HTTP {code} {message[:100]!r}")
print("PASS" if failures == 0 else f"FAIL: {failures}")
return 0 if failures == 0 else 1


if __name__ == "__main__":
sys.exit(main())
10 changes: 8 additions & 2 deletions zig/src/server/cli.zig
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub const flags = [_]Flag{
.{ .name = "--metrics-open", .kind = .store_true, .native = true },
.{ .name = "--dashboard", .kind = .store_true, .native = true },
.{ .name = "--vision", .kind = .store_true, .native = true },
.{ .name = "--vision-urls", .kind = .store_true },
.{ .name = "--vision-urls", .kind = .store_true, .native = true },
.{ .name = "--vision-offload", .kind = .store_true },
.{ .name = "--vision-max-images", .native = true },
.{ .name = "--vision-image-tokens", .native = true },
Expand Down Expand Up @@ -171,6 +171,7 @@ pub const Args = struct {
policy: []const u8 = "", // every --policy joined by commas
cortheon: bool = false, // Cortheon's program, research before building, and cortheon_search/cortheon_fetch run by the server
vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages
vision_urls: bool = false, // with --vision, public HTTPS image URLs too (media_fetch.zig)
vision_max_images: u32 = 4,
vision_image_tokens: u32 = 4096,
};
Expand Down Expand Up @@ -224,6 +225,7 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou
}
out.model = model orelse return fail(u, a, "the following arguments are required: model", .{});
try ranks(u, a, out);
if (out.vision_urls and !out.vision) return fail(u, a, "--vision-urls needs --vision", .{});
out.alias = alias.items;
out.api_key = keys.items;
return out;
Expand Down Expand Up @@ -278,7 +280,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa
const n = try int(u, a, name, v);
if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v});
out.compact_keep = @intCast(n);
} else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-max-images")) {
} else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-max-images")) {
const n = try int(u, a, name, v);
if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v});
out.vision_max_images = @intCast(n);
Expand Down Expand Up @@ -463,6 +465,10 @@ test "parse and capabilities share the table" {
try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "0" }, &u));
try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "2" }, &u));
try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-keep", "-1" }, &u));
const urls = try parse(a, &.{ "m", "--vision", "--vision-urls" }, &u);
try std.testing.expect(urls.vision and urls.vision_urls);
try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--vision-urls" }, &u));
try std.testing.expectEqualStrings("--vision-urls needs --vision", u.message);
}

test "--device and --segments: CUDA builds serve them, values checked; --speed-up is the Mac build's" {
Expand Down
Loading