Compare commits

..
8 Commits
Author SHA1 Message Date
Ilker ManapandClaude Opus 5.5 55d5e13534 Pictures, 3D models, a vision model and workflows as tools at /mcp
An agent driving Blender made its concepts, meshes and render reviews
through a tool server of the game's own, which called this gateway; the
gateway's MCP server offered only the memory notes. It now offers
generate_image, generate_mesh, review_images, run_workflow, job_status and
gateway_status beside them, each only where a model for it is here.

Each tool makes its request of the client API as the caller, through the
handler Handler built, key check and all: allowlists, limits, licences
left out, budgets and accounting apply as to any request, and a job is
the caller's. What a tool makes is kept as the caller's file and answered
by id and download URL, since a server over HTTP cannot write to the
caller's disk; a picture comes with a 512 px preview, and whole where no
file can be kept. A picture to work from is a file id, a data URL or
base64; one sent to the vision model is shrunk to 1280 px.

A mesh takes minutes. A client that takes a stream is answered as
server-sent events, with notifications/progress for its token while the
job is queued, waiting for the GPU and running, and waits up to ten
minutes; one that does not waits 50 seconds and gets the job id, which
job_status asks after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:11:09 +02:00
Ilker ManapandClaude Opus 5.5 7c53380e68 Extended thinking on /v1/messages: a model's reasoning as thinking blocks
CI / test (push) Successful in 9m12s
Claude Code and the Anthropic SDKs asking for extended thinking got the
answer alone: a reasoning model's reasoning_content was dropped. Asked for,
it comes back as a thinking block before the text — streamed as
thinking_delta events and closed with a signature before the text begins —
and the model is told to think through its chat template
(enable_thinking); disabled tells it not to. Not asked for, it is left out
as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 11:05:02 +02:00
Ilker ManapandClaude Opus 5.5 0460f52dd2 Jobs run side by side, one per model at a time
CI / test (push) Successful in 10m28s
One job at a time, a 3D job waiting for the card held up another model's
job that could have run (seen on the PoC, BACKLOG H7). The leader's worker
claims jobs while fewer than eight run, passing over the models that have
one running, and starts each in its own goroutine; one ending wakes it for
the next. Lease and leader-only rules are as they were.

BACKLOG: H5–H7 marked, H8 (presets) and H9 (what the PoC taught) written.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 10:06:20 +02:00
Ilker ManapandClaude Opus 5.5 efffdb66b7 An embedding model is served for embedding, with many slots
ctl model serve served one as a chat model: no --embedding, four slots, a
512-token batch, embeddings unset, and a chat smoke test it could not
pass. A GGUF that pools (<arch>.pooling_type), or --embeddings, gets
--embedding, 32 slots of 1024 tokens unless sized otherwise, a batch that
holds a whole passage, the embeddings capability, and one vector asked for
as its smoke test (canaries and updates too). An import of a hundred
thousand chunks had gone at the pace of four slots with the card a third
busy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 09:19:57 +02:00
Ilker ManapandClaude Opus 5.5 f5eb6963af An upgrade that leaves nodes behind says which
A site's nodes stayed a release behind after its control plane was
upgraded, with nothing printed to say so. ctl upgrade checks every node's
version once the waves are done, fails naming any not on the release, and
says when the control plane has no nodes registered. llmgw upgrade on a
control plane, which looks like the cluster's upgrade and is not, says how
many nodes it left behind and the command that upgrades them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 09:01:09 +02:00
Ilker ManapandClaude Opus 5.5 1e7086e13e How long an on-demand model holds a card is a live setting
On one card shared by flux and sf3d, a mesh asked for after a picture
waited out the picture model's five minutes of protection and two of idle.
on_demand.evict_after_idle and on_demand.min_lifetime set those for the
cluster, in force on the leader as they change; unset keeps 2m and 5m.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 08:58:38 +02:00
Ilker ManapandClaude Opus 5.5 a9a2360f44 pages.js is loaded by its versioned address
CI / test (push) Successful in 11m15s
Five pages named /_static/pages.js outright, cached for a day, so a
browser kept the old script after an upgrade — the one holding refreshes
off while a form is filled in among them. They take it through asset, as
the rest do, whose address changes with its contents.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 08:15:44 +02:00
Ilker ManapandClaude Opus 5.5 e78075876b A form being filled in is not refreshed away
CI / test (push) Failing after 7m30s
The cluster and node pages swap their live part every few seconds, and the
forms inside it went with it: what was typed, an open choice, the focus.
Filling one in raced the clock. The swap now waits while a field in the
live part has the focus or a form in it has been typed into and not sent;
sending it, or leaving the page, ends that. The mirror page's reload
during a download goes through the same check instead of http-equiv.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 08:13:08 +02:00
47 changed files with 2026 additions and 54 deletions

No files matched your search

+19 -3
View File
@@ -1385,7 +1385,7 @@ gate, so no token is on the node.
- Done when: SF3D runs on cuda01 with nothing installed into the engine's
venv by hand (the hand install of 2026-10-10 removed first).
### H5. Licence on every output (S)
### H5. Licence on every output (S) — done 2026-10-14: the whole licence in GLB asset.extras and PNG iTXt; video and audio not yet
- `License` gains `id` (SPDX where there is one, else a lowercase name:
stability-community, tencent-hunyuan-community), `commercial` (unset is
not said), `excluded_regions` (ISO 3166 codes, `EU` for the union),
@@ -1398,7 +1398,7 @@ gate, so no token is on the node.
audio formats in their metadata where ffmpeg is at hand on the router,
otherwise beside it in the job's answer only — said in the docs.
### H6. Licence choices (S) — the other session's (llmgw-b7), at the user's request
### H6. Licence choices (S) — done 2026-10-11 (4bbac08), live on the PoC
The user asked (2026-10-11) for the choice to be a person's: on their
profile they pick the licences they will not use, and their keys and
portal session neither see those models in `/v1/models` nor may call
@@ -1407,13 +1407,29 @@ them (403, saying which licence). Matched on `license.id`, and on
store table is migration 0046. A site-wide or team-wide default can sit
on top of it later.
### H7. A job worker per model, not one for all (S)
### H7. A job worker per model, not one for all (S) — done 2026-10-14: one job per model at a time, eight in all
The worker runs one job at a time: a job waiting for the card holds up a
job for another model that could run now (seen on the PoC, 2026-10-10).
Jobs are claimed and run concurrently up to a limit per model (or per
environment, after H3) and a cluster-wide cap, with the lease and
leader-only rules of G1 kept.
### H8. Presets that add themselves (S) — done 2026-10-13 (v0.14.5)
flux-schnell and triposr come with llmgw (`ctl model add <preset>`), and
the leader adds them on demand where a node fits one, the cluster installs
ComfyUI and the catalog makes nothing of that kind (`presets.auto`); a
preset removed is declined and not added back. The cluster page and the
console show and add them.
### H9. Small things learned on the PoC (2026-10-14)
- Done: `albedo_match` on sf3d (its delighting made dark objects light);
`on_demand.evict_after_idle` / `min_lifetime` as live settings; an
upgrade that leaves nodes behind says which; `ctl model serve` serves an
embedding model for embedding; refreshes wait while a form is filled in.
- Open: llmgw's `/mcp` with picture, 3D, VLM and workflow tools, so a
client needs no server of its own (asked by the game team); the shared
ComfyUI replica (H3's placement side).
## D. Facts worth knowing before starting
- Admin API: `127.0.0.1:9090`, no auth, `ctlClient` in `internal/cli/ctl.go`.
+47
View File
@@ -26,6 +26,53 @@ APIs change between minors without a deprecation period.
## Unreleased
### Added
- **Pictures, 3D models, vision and workflows as MCP tools** at `/mcp`,
beside the memory notes, each offered only where the gateway has a model
for it: `generate_image` (with `concept`, `side` and `texture` styles),
`generate_mesh` (from a picture or a prompt), `review_images` (a vision
model, to a JSON schema), `run_workflow`, `job_status` and
`gateway_status`. Each makes its request under the caller's key, so
allowlists, limits, licences and budgets apply and it is charged like
any request; what it makes is kept as the caller's file and answered by
id and download URL. A client that takes a stream gets
`notifications/progress` while a mesh is made and waits up to ten
minutes; one that does not, 50 seconds, then the job id.
- **Extended thinking on `/v1/messages`**: `thinking: {type: "enabled"}`
tells a model that thinks by its chat template to (`enable_thinking`),
and its reasoning comes back as `thinking` blocks before the text,
streamed as `thinking_delta` events; `disabled` tells it not to. Not
asked for, the reasoning is left out as before.
- **How long on-demand models hold a card** is a setting, in force on the
leader within seconds: `on_demand.evict_after_idle` (2m unless set) and
`on_demand.min_lifetime` (5m). On one card shared by a picture model and
a 3D model, 1m each brings the wait between a picture and its mesh to
about a minute.
### Fixed
- Jobs ran one at a time, so a 3D job waiting for the card held up another
model's job that could have run. They run side by side, one per model at
a time and eight in all, on the leader as before.
- `llmgw ctl model serve` served an embedding model as a chat model: no
`--embedding`, four slots, a 512-token batch, `embeddings` unset and a
"say hello" smoke test it could not pass. A model whose GGUF says it
pools (or `--embeddings`) is served for embedding: 32 slots of 1024
tokens unless sized otherwise, a batch that holds a whole passage, and
one vector asked for as its smoke test.
- `llmgw ctl upgrade` checks every node's version once the waves are done
and fails naming any not on the release, and says when the control plane
has no nodes registered; `llmgw upgrade` on a control plane says how many
nodes it left behind and the command that upgrades them. A site's nodes
stayed a release behind with nothing to say so.
- The cluster and node pages swapped their live part every few seconds,
forms and all, so filling one in raced the clock: what was typed, an
open choice and the focus were lost. The refresh now waits while a field
in it has the focus or a form in it has been typed into and not sent;
the mirror page's reload during a download waits the same way.
## v0.14.5 — 2026-10-14
Picture and 3D models that add themselves where a card fits them, with a
+4
View File
@@ -10413,6 +10413,10 @@
"type": "boolean",
"description": "Tools says the model makes tool calls the engine returns as calls: it is written into the catalog, where clients and editors read it. Check a running replica with llmgw ctl tool-check before saying so."
},
"embeddings": {
"type": "boolean",
"description": "Embeddings serves it as an embedding model, which its GGUF header says by itself for most: --embedding, many slots, a batch that holds a whole passage, /v1/embeddings."
},
"cpu_cores": {
"type": "integer",
"description": "CPUCores is what a replica computes on; zero takes half the smallest node it fits on."
+1 -1
View File
@@ -82,7 +82,7 @@
"/mcp": {
"post": {
"operationId": "postMcp",
"summary": "The gateway's MCP server: the memory notes as tools",
"summary": "The gateway's MCP server: the memory notes, and pictures, 3D models, vision and workflows, as tools",
"tags": [
"mcp"
],
+36
View File
@@ -534,6 +534,42 @@ curl https://llm.example.com/mcp \
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
```
**Pictures, 3D models, vision and workflows.** Where the gateway has the
models for them, the same server offers more tools — only those it has a
model for:
| Tool | Does |
|---|---|
| `generate_image` | A picture from a prompt. `style` adds what a picture for a mesh wants: `concept` (one object, three-quarter view, grey background), `side` (an exact side view), `texture` (a seamless tile) or `none`. Answers the PNG's `file_id`, `url` and `seed`, with a 512 px preview to look at. |
| `generate_mesh` | A GLB from a picture — `image` is a `file-…` id (a `generate_image` result, say), a data URL or base64 — or from a `prompt`, for which a concept picture is made first. `seed`, `resolution`, `texture_resolution`, and any other input the model's workflow declares in `inputs`. Answers the GLB's `file_id`, `url` and licence. |
| `review_images` | Asks a vision model about one to four pictures (each shrunk to 1280 px on its long side); `json_schema` makes it answer that JSON. |
| `run_workflow` | Runs a ComfyUI workflow from the inputs its catalog entry declares, and answers its result file. |
| `job_status` | Where a mesh or a workflow run stands, and its file when done; `wait_seconds` waits for it. |
| `gateway_status` | The picture, 3D, vision and workflow models, whether each is loaded on a GPU now, a workflow's inputs, and your last jobs. |
Each tool makes its request of the gateway under your key, so your
allowlist, limits, left-out licences and budget apply, and it is charged
and listed like any other request. What it makes is kept as your file for
as long as job results are: fetch it from `url` with the same key (`curl -H
"Authorization: Bearer $LLMGW_API_KEY" -o rock.glb <url>`). A tool server
over HTTP cannot write to your disk, so an agent that needs the file
locally — to import it in Blender — fetches it, or goes through a small
local bridge that does.
A mesh takes from half a minute to a few minutes. A client that takes the
answer as a stream (`Accept: text/event-stream`, as Claude Code does) is
answered that way: `notifications/progress` for the call's
`progressToken` while it runs — queued, waiting for the GPU, the node and
its percent — then the result, and the call waits up to ten minutes. One
answered in one piece waits 50 seconds; a job not done by then is answered
with its `job_id`, to ask after with `job_status`. `wait_seconds` (up to
900) sets either.
```
claude mcp add --transport http llmgw https://llm.example.com/mcp \
--header "Authorization: Bearer $LLMGW_API_KEY"
```
### Licences you leave out
A model's licence is in `/v1/models` (`license`: its `id`, `name`, whether
+31
View File
@@ -205,6 +205,8 @@ rather than repeated.
| `no_passwords` | `bool` | [OIDC](#oidc) |
| `mirror` | `string` | [Offline](#offline) |
| `checksums` | `string` | [Offline](#offline) |
| `evict_after_idle` | `time.Duration` | [OnDemandSettings](#ondemandsettings) |
| `min_lifetime` | `time.Duration` | [OnDemandSettings](#ondemandsettings) |
| `nvidia_smi` | `string` | [Options](#options) |
| `ib_root` | `string` | [Options](#options) |
| `prefer_nvml` | `bool` | [Options](#options) |
@@ -346,6 +348,7 @@ rather than repeated.
| `serving` | `ServingSettings` | [Server](#server) |
| `firewall` | `FirewallSettings` | [Server](#server) |
| `presets` | `PresetSettings` | [Server](#server) |
| `on_demand` | `OnDemandSettings` | [Server](#server) |
| `agents` | `AgentSettings` | [Server](#server) |
| `firewall_networks` | `[]string` | [Server](#server) |
| `backup_recipients` | `[]string` | [Server](#server) |
@@ -1912,6 +1915,25 @@ kept by llmgw bundle import and llmgw bundle trust; every engine file
a node fetches from the mirror is checked against it. Read again
whenever it changes. Empty is /etc/llmgw/offline.sha256.
## OnDemandSettings
### `evict_after_idle`
`time.Duration`
EvictAfterIdle is how long an on-demand replica must go unasked-for
before a model that wants its card may have it. Zero keeps 2m.
### `min_lifetime`
`time.Duration`
MinLifetime is how long a replica that has just come up is safe from
that, so two models do not take turns paying for loads. Zero keeps
5m. On one card shared by a picture model and a 3D model, 1m each
brings the wait between a picture and its mesh to about a minute.
Both are in force on the leader within seconds.
## Options
### `nvidia_smi`
@@ -2984,6 +3006,15 @@ Presets is how the models that come with llmgw reach the catalog.
Takes a [PresetSettings](#presetsettings) block.
### `on_demand`
`OnDemandSettings`
OnDemand is how models that load when asked for take turns on the
cards.
Takes a [OnDemandSettings](#ondemandsettings) block.
### `agents`
`AgentSettings`
+2
View File
@@ -245,6 +245,8 @@ var liveSettings = []string{
"agents",
// Read by the leader's presets pass each time it runs.
"presets",
// Handed to the reconciler as they change.
"on_demand",
// Read by server init, node add and backups, not by the server.
"backup_recipients", "backup_copy_to",
}
+20
View File
@@ -268,6 +268,26 @@ func upgradeNodes(ctx context.Context, out io.Writer, client func() *ctlClient,
}
fmt.Fprintf(out, "%d node(s) upgraded to %s in %s, %d already on it\n",
done, v, time.Since(start).Round(time.Second), skipped)
// Checked at the end, against what the control plane says now: a node
// that is not on the version is said by name, and the command fails. A
// site's nodes stayed a release behind with nothing printed to say so.
if len(nodes) == 0 {
fmt.Fprintln(out, "This control plane has no nodes registered, so none were upgraded.")
}
var now []adminapi.NodeView
if err := client().get(ctx, "/api/v1/nodes", &now); err == nil {
var behind []string
for _, n := range now {
if (len(only) == 0 || slices.Contains(only, n.ID)) && n.AgentVersion != v {
behind = append(behind, fmt.Sprintf("%s (%s, %s)", n.ID, orUnknown(n.AgentVersion), n.State))
}
}
if len(behind) > 0 {
slices.Sort(behind)
return fmt.Errorf("not on %s: %s\nrun this again to try them, or `llmgw ctl logs NODE` for why",
v, strings.Join(behind, ", "))
}
}
// The one machine this does not reach. Said every time, because it is
// exactly the kind of thing that stays three versions behind unnoticed.
fmt.Fprintf(out, "The model mirror's host is not upgraded by this; on it, run:\n"+
+51
View File
@@ -150,3 +150,54 @@ func TestABinaryInstalledByHandIsNotAServerRunningIt(t *testing.T) {
}
}
}
func TestAnUpgradeThatFindsNoNodesSaysSo(t *testing.T) {
// A site's nodes stayed a release behind with nothing printed to say
// that none had been reached.
f := &fakeFleet{versions: map[string]string{}}
srv := f.server(t)
var out bytes.Buffer
if err := upgradeNodes(t.Context(), &out, func() *ctlClient { return newCtlClient(srv.URL) }, "v1.0.1", nil, time.Second, 1); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "no nodes registered") {
t.Errorf("output:\n%s", out.String())
}
}
func TestAnUpgradeFailsNamingANodeLeftBehind(t *testing.T) {
// A node that joins, or comes back on its old binary, while the waves
// run is found at the end rather than passed over.
f := &fakeFleet{versions: map[string]string{"a": "v1.0.0"}}
srv := f.server(t)
late := func() *ctlClient {
f.mu.Lock()
if len(f.told) == 1 {
f.versions["late"] = "v1.0.0"
}
f.mu.Unlock()
return newCtlClient(srv.URL)
}
var out bytes.Buffer
err := upgradeNodes(t.Context(), &out, late, "v1.0.1", nil, 5*time.Second, 1)
if err == nil || !strings.Contains(err.Error(), "late (v1.0.0, ready)") {
t.Errorf("err %v", err)
}
}
func TestUpgradingAControlPlaneAloneSaysItsNodesWereNot(t *testing.T) {
f := &fakeFleet{versions: map[string]string{"p-g1": "v1.0.0", "p-g3": "v1.0.1"}}
srv := f.server(t)
var out bytes.Buffer
nodesLeftBehind(t.Context(), &out, newCtlClient(srv.URL), "v1.0.1")
if !strings.Contains(out.String(), "1 of 2 node(s) are not on v1.0.1") ||
!strings.Contains(out.String(), "ctl upgrade v1.0.1 --skip-control-plane") {
t.Errorf("output:\n%s", out.String())
}
out.Reset()
f.versions["p-g1"] = "v1.0.1"
nodesLeftBehind(t.Context(), &out, newCtlClient(srv.URL), "v1.0.1")
if out.Len() != 0 {
t.Errorf("said something with every node on the version: %s", out.String())
}
}
+2
View File
@@ -60,6 +60,8 @@ func newModelServeCmd(client func() *ctlClient) *cobra.Command {
f.StringVar(&req.Quant, "quant", "", "the quantisation to serve (default: the one that suits the cluster best)")
f.StringVar(&req.File, "file", "", "the file to serve, instead of choosing by --quant")
f.StringVar(&req.Projector, "projector", "", "a vision model's mmproj file, fetched and loaded beside it")
f.BoolVar(&req.Embeddings, "embeddings", false, "serve it as an embedding model (its GGUF header says so for most): "+
"--embedding, 32 slots of 1024 tokens unless --ctx-pool or --context-length says otherwise")
f.StringVar(&req.Format, "format", "gguf", "gguf, run by llama.cpp, or safetensors: the original weights, run by vLLM on GPUs")
f.BoolVar(&req.CPU, "cpu", false, "run it on the CPU, whatever the plan says")
f.StringVar(&req.GPUClass, "gpu-class", "", "run it on GPUs of this class, whatever the plan says")
+28
View File
@@ -1,8 +1,11 @@
package cli
import (
"context"
"errors"
"fmt"
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
"io"
"os"
"os/exec"
"runtime"
@@ -70,6 +73,9 @@ func newSelfUpgradeCmd() *cobra.Command {
if strings.TrimSpace(string(b)) == "active" {
if steady++; steady >= 3 {
fmt.Fprintf(out, "%s restarted and running\n", service)
if service == "llmgw-server" {
nodesLeftBehind(cmd.Context(), out, newCtlClient("127.0.0.1:9090"), v)
}
return nil
}
} else {
@@ -85,3 +91,25 @@ func newSelfUpgradeCmd() *cobra.Command {
c.Flags().StringVar(&service, "service", "", "the systemd unit to restart afterwards, e.g. llmgw-mirror")
return c
}
// nodesLeftBehind says, after a control plane alone was upgraded, that its
// nodes were not, and how they are: this command looks like the cluster's
// upgrade and is not, and a site's nodes stayed a release behind after it.
func nodesLeftBehind(ctx context.Context, out io.Writer, c *ctlClient, v string) {
var nodes []adminapi.NodeView
_ = c.patient(20*time.Second).get(ctx, "/api/v1/nodes", &nodes)
behind := 0
for _, n := range nodes {
if n.AgentVersion != v {
behind++
}
}
switch {
case len(nodes) == 0:
fmt.Fprintf(out, "This upgraded this machine only. The nodes are upgraded from the leading "+
"control plane with:\n sudo llmgw ctl upgrade %s --skip-control-plane\n", v)
case behind > 0:
fmt.Fprintf(out, "This upgraded this machine only: %d of %d node(s) are not on %s. On the leading "+
"control plane, run:\n sudo llmgw ctl upgrade %s --skip-control-plane\n", behind, len(nodes), v, v)
}
}
+4
View File
@@ -264,6 +264,7 @@ func newServerCmd() *cobra.Command {
agentSvc = svc
// Stopped by the operators (llmgw stop): nothing placed.
ctl.Reconciler().SetStopped(cfg.Serving.Stopped)
ctl.Reconciler().SetEvictionTimes(cfg.OnDemand.EvictAfterIdle, cfg.OnDemand.MinLifetime)
// Whether nodes keep llmgw's firewall, as the settings say now.
svc.SetFirewall(func() *llmgwv1.Firewall {
c := current.Load()
@@ -778,6 +779,9 @@ func newServerCmd() *cobra.Command {
fwPub.Kick()
}
}
if slices.ContainsFunc(changed, func(c string) bool { return strings.HasPrefix(c, "on_demand") }) && admin != nil {
admin.Reconciler().SetEvictionTimes(next.OnDemand.EvictAfterIdle, next.OnDemand.MinLifetime)
}
if slices.ContainsFunc(changed, func(c string) bool { return strings.HasPrefix(c, "agents") }) && agentSvc != nil {
// A moment apart per node, so off this goroutine.
go agentSvc.BroadcastAgentSettings()
+1 -1
View File
@@ -107,7 +107,7 @@ var Routes = []Route{
{Method: "GET", Path: "/v1/memory/{key}", Summary: "A note", Response: MemoryNote{}},
{Method: "GET", Path: "/v1/memory", Summary: "The project's notes", Response: MemoryList{}},
{Method: "DELETE", Path: "/v1/memory/{key}", Summary: "Forget a note"},
{Method: "POST", Path: "/mcp", Summary: "The gateway's MCP server: the memory notes as tools",
{Method: "POST", Path: "/mcp", Summary: "The gateway's MCP server: the memory notes, and pictures, 3D models, vision and workflows, as tools",
Request: MCPRequest{}, Response: anyJSON},
{Method: "GET", Path: "/me", Summary: "The caller: its key, its place in the tree, its limits and what it has used",
Response: Me{}},
+4
View File
@@ -161,6 +161,10 @@ type Server struct {
// Presets is how the models that come with llmgw reach the catalog.
Presets PresetSettings `koanf:"presets"`
// OnDemand is how models that load when asked for take turns on the
// cards.
OnDemand OnDemandSettings `koanf:"on_demand"`
// Agents are the nodes' agent settings: agent.yaml's keys but those an
// agent needs to start, for every node (default) and for one
// (nodes.<id>). Sent to the agents as they change; an agent whose
+18
View File
@@ -0,0 +1,18 @@
package config
import "time"
// OnDemandSettings is how models that load when asked for take turns on the
// cards: on a site with fewer cards than such models, the wait between one
// and the next.
type OnDemandSettings struct {
// EvictAfterIdle is how long an on-demand replica must go unasked-for
// before a model that wants its card may have it. Zero keeps 2m.
EvictAfterIdle time.Duration `koanf:"evict_after_idle"`
// MinLifetime is how long a replica that has just come up is safe from
// that, so two models do not take turns paying for loads. Zero keeps
// 5m. On one card shared by a picture model and a 3D model, 1m each
// brings the wait between a picture and its mesh to about a minute.
// Both are in force on the leader within seconds.
MinLifetime time.Duration `koanf:"min_lifetime"`
}
+1 -1
View File
@@ -92,7 +92,7 @@ func (s *Server) addCandidate(ctx context.Context, j *Job, p prepared, cn catalo
s.step(j, "smoke test", Running, "asking "+r.ID+" to say hello")
var reply string
var tps float64
if reply, tps, err = s.smoke(ctx, r, cand); err == nil {
if reply, tps, err = s.smoke(ctx, r, cand, s.embeds(cand)); err == nil {
s.step(j, "smoke test", Done, fmt.Sprintf("answered at %.1f tokens/s: %q", tps, reply))
} else {
s.step(j, "smoke test", Failed, err.Error())
+86 -4
View File
@@ -153,6 +153,13 @@ type Request struct {
// is written into the catalog, where clients and editors read it. Check
// a running replica with llmgw ctl tool-check before saying so.
Tools bool `json:"tools,omitempty"`
// Embeddings serves it as an embedding model, which its GGUF header
// says by itself for most: --embedding, many slots, a batch that holds
// a whole passage, /v1/embeddings.
Embeddings bool `json:"embeddings,omitempty"`
// sized is the caller having said --ctx-pool or --context-length, which
// an embedding model's defaults then leave alone.
sized bool
// CPUCores is what a replica computes on; zero takes half the smallest
// node it fits on.
CPUCores int `json:"cpu_cores,omitempty"`
@@ -268,6 +275,7 @@ func (s *Server) Start(req Request) (Job, error) {
if req.GuardFormat != "" && req.Replicas == 0 {
return Job{}, errors.New("a judge model must always run: give it --replicas 1 or more, not --on-demand")
}
req.sized = req.CtxPool > 0 || req.ContextLength > 0
if req.CtxPool <= 0 {
req.CtxPool = 16384
}
@@ -473,6 +481,16 @@ func (s *Server) run(j *Job) {
}
header = v.Header
}
if header.Embedding {
req.Embeddings = true
}
if req.Embeddings && !req.sized {
// Many passages at once rather than four: an import of a hundred
// thousand chunks went at the pace of four slots with the card a
// third busy.
req.ContextLength, req.CtxPool = embedSlotTokens, embedSlotTokens*embedSlots
}
j.Request = req
memGB := int((header.MemoryBytes(set.Bytes, req.CtxPool) + 1<<30 - 1) >> 30)
basis := fmt.Sprintf("weights %.1f GB + KV cache %.1f GB for %d tokens + engine",
gb(set.Bytes), gb(int64(req.CtxPool)*header.KVBytesPerToken()), req.CtxPool)
@@ -587,10 +605,24 @@ func profilesFor(layout []modelplan.Option, req Request, memGB, cores int) []cat
// slots of 8192, and the gateway, told 32768, sent requests the engine then
// refused.
func llamaArgs(req Request) []string {
return []string{"--ctx-size", strconv.Itoa(req.CtxPool),
args := []string{"--ctx-size", strconv.Itoa(req.CtxPool),
"--parallel", strconv.Itoa(max(1, req.CtxPool/req.ContextLength))}
if req.Embeddings {
// A passage is embedded in one batch: with the default 512, one of
// 516 tokens was refused.
n := strconv.Itoa(req.ContextLength)
args = append([]string{"--embedding"}, append(args, "--batch-size", n, "--ubatch-size", n)...)
}
return args
}
// An embedding model's slots, when its caller did not size them: passages
// of up to a thousand tokens, thirty-two at a time.
const (
embedSlotTokens = 1024
embedSlots = 32
)
// maxOutput is the longest answer the catalog allows: a quarter of the
// context, from 1024 to 8192. 1024 everywhere cut an editor's agent off in
// the middle of the file it was writing.
@@ -620,7 +652,7 @@ func (s *Server) addAndStart(ctx context.Context, j *Job, repo hf.Repo, set hf.F
RoutingProfile: "chat", ContextLength: req.ContextLength, MaxOutput: maxOutput(req.ContextLength),
Profiles: profs,
Scaling: catalog.Scaling{Min: req.Replicas, Max: max(req.Replicas, 1)},
Capabilities: catalog.Capabilities{Vision: req.Projector != "", Tools: req.Tools},
Capabilities: catalog.Capabilities{Vision: req.Projector != "", Tools: req.Tools, Embeddings: req.Embeddings},
Origin: &catalog.Origin{Repo: repo.ID, Revision: repo.Revision, Files: originFiles(set)},
}
if req.GuardFormat != "" {
@@ -655,7 +687,7 @@ func (s *Server) addAndStart(ctx context.Context, j *Job, repo hf.Repo, set hf.F
// 6. Does it answer.
s.step(j, "smoke test", Running, "asking "+rep.ID+" to say hello")
reply, tps, err := s.smoke(ctx, rep, name)
reply, tps, err := s.smoke(ctx, rep, name, req.Embeddings)
if err != nil {
s.fail(j, "smoke test", err)
return
@@ -859,7 +891,10 @@ func (s *Server) waitReady(ctx context.Context, j *Job, name string, hardware bo
}
// smoke sends one short request straight to the replica, with its engine key.
func (s *Server) smoke(ctx context.Context, r reconciler.Replica, name string) (string, float64, error) {
func (s *Server) smoke(ctx context.Context, r reconciler.Replica, name string, embeddings bool) (string, float64, error) {
if embeddings {
return s.smokeEmbeddings(ctx, r, name)
}
body, _ := json.Marshal(map[string]any{
"model": name,
"max_tokens": 32,
@@ -989,3 +1024,50 @@ func pickSafetensors(repo hf.Repo, _ Request) (hf.FileSet, error) {
}
return set, nil
}
// smokeEmbeddings asks an embedding model for one vector, and says its
// length: an embedding model does not chat.
func (s *Server) smokeEmbeddings(ctx context.Context, r reconciler.Replica, name string) (string, float64, error) {
body, _ := json.Marshal(map[string]any{"model": name, "input": "hello"})
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
strings.TrimRight(r.Endpoint, "/")+"/v1/embeddings", bytes.NewReader(body))
if err != nil {
return "", 0, err
}
req.Header.Set("Content-Type", "application/json")
if k := s.deps.Fleet.EngineKey(r.ID); k != "" {
req.Header.Set("Authorization", "Bearer "+k)
}
resp, err := s.deps.HTTP.Do(req)
if err != nil {
return "", 0, err
}
defer resp.Body.Close()
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if resp.StatusCode != http.StatusOK {
return "", 0, fmt.Errorf("the replica answered %s: %s", resp.Status, strings.TrimSpace(string(b)))
}
var out struct {
Data []struct {
Embedding []float64 `json:"embedding"`
} `json:"data"`
}
if err := json.Unmarshal(b, &out); err != nil || len(out.Data) == 0 || len(out.Data[0].Embedding) == 0 {
return "", 0, fmt.Errorf("the replica answered no vector: %s", strings.TrimSpace(string(b)))
}
return fmt.Sprintf("a vector of %d dimensions", len(out.Data[0].Embedding)), 0, nil
}
// embeds is whether the catalog serves name as an embedding model, for a
// smoke test of one already there (a canary, an update).
func (s *Server) embeds(name string) bool {
if s.deps.Current == nil {
return false
}
for _, m := range s.deps.Current() {
if m.Name == name {
return m.Capabilities.Embeddings
}
}
return false
}
@@ -397,3 +397,18 @@ func TestOnlyTheLastFinishedJobsAreRemembered(t *testing.T) {
t.Error("the oldest finished job is still remembered")
}
}
func TestAnEmbeddingModelIsServedForEmbedding(t *testing.T) {
// Four slots and a 512-token batch: an import went at four passages a
// pass, and one passage of 516 tokens was refused.
args := strings.Join(llamaArgs(Request{Embeddings: true, ContextLength: embedSlotTokens,
CtxPool: embedSlotTokens * embedSlots}), " ")
for _, want := range []string{"--embedding", "--ctx-size 32768", "--parallel 32", "--batch-size 1024", "--ubatch-size 1024"} {
if !strings.Contains(args, want) {
t.Errorf("%q not in %q", want, args)
}
}
if args := strings.Join(llamaArgs(Request{ContextLength: 4096, CtxPool: 16384}), " "); strings.Contains(args, "embedding") {
t.Errorf("a chat model got %q", args)
}
}
+1 -1
View File
@@ -689,7 +689,7 @@ func (s *Server) replace(ctx context.Context, j *Job, name string) error {
}
s.step(j, "replicas", Done, fmt.Sprintf("%d replaced", len(old)))
s.step(j, "smoke test", Running, "asking "+ready[0].ID+" to say hello")
reply, tps, err := s.smoke(ctx, ready[0], name)
reply, tps, err := s.smoke(ctx, ready[0], name, s.embeds(name))
if err != nil {
s.step(j, "smoke test", Failed, err.Error())
return err
+33 -2
View File
@@ -120,7 +120,7 @@ func (r *Reconciler) evictable(wantedBy string) []evictionCandidate {
continue
}
idle := now.Sub(rep.LastUsedAt)
if idle < r.cfg.EvictionGrace {
if idle < r.evictionGrace() {
continue
}
// A replica that has only just started is left alone however idle it
@@ -128,7 +128,7 @@ func (r *Reconciler) evictable(wantedBy string) []evictionCandidate {
// otherwise take turns evicting each other, paying a model load each
// time — and a load is expensive enough that waiting is strictly
// better than winning.
if !rep.ReadyAt.IsZero() && now.Sub(rep.ReadyAt) < r.cfg.MinLifetime {
if !rep.ReadyAt.IsZero() && now.Sub(rep.ReadyAt) < r.minLifetime() {
continue
}
nodes := map[string]struct{}{}
@@ -156,3 +156,34 @@ func (r *Reconciler) EvictionReason(model string) string {
}
return "nothing idle enough to stop"
}
// evictionGrace is how long an on-demand replica must go unasked-for before
// another model may have its card: the cluster's setting, else the
// configuration's.
func (r *Reconciler) evictionGrace() time.Duration {
if d := time.Duration(r.evictGrace.Load()); d > 0 {
return d
}
return r.cfg.EvictionGrace
}
// minLifetime is how long a replica is safe from eviction once it is up.
func (r *Reconciler) minLifetime() time.Duration {
if d := time.Duration(r.minLife.Load()); d > 0 {
return d
}
return r.cfg.MinLifetime
}
// SetEvictionTimes puts the cluster's on_demand settings in force: how long
// an idle on-demand replica keeps its card, and how long a new one is safe.
// Zero keeps the configuration's.
//
// On one card shared by several models these are the wait between them: a
// 3D job after a picture waited out five minutes of a picture model it no
// longer needed.
func (r *Reconciler) SetEvictionTimes(afterIdle, minLifetime time.Duration) {
r.evictGrace.Store(int64(afterIdle))
r.minLife.Store(int64(minLifetime))
r.Notify()
}
+3 -3
View File
@@ -205,9 +205,9 @@ func (r *Reconciler) WaitFor(model string) (heldBy string, eta time.Duration, ok
// Evicted sooner, when it is no higher a class than the model
// waiting; one put first is waited for to its idle timeout.
if catalog.ClassRank(other.EffectiveClass()) <= catalog.ClassRank(m.EffectiveClass()) {
evict := rep.LastUsedAt.Add(r.cfg.EvictionGrace)
if !rep.ReadyAt.IsZero() && rep.ReadyAt.Add(r.cfg.MinLifetime).After(evict) {
evict = rep.ReadyAt.Add(r.cfg.MinLifetime)
evict := rep.LastUsedAt.Add(r.evictionGrace())
if !rep.ReadyAt.IsZero() && rep.ReadyAt.Add(r.minLifetime()).After(evict) {
evict = rep.ReadyAt.Add(r.minLifetime())
}
if evict.Before(h.release) {
h.release = evict
+2 -2
View File
@@ -249,7 +249,7 @@ func (r *Reconciler) victims(m catalog.Model) []victim {
aboveMin := i < above
tier := -1
switch {
case rank < myRank && other.Scaling.OnDemand() && idleFor(rep, now) >= r.cfg.EvictionGrace:
case rank < myRank && other.Scaling.OnDemand() && idleFor(rep, now) >= r.evictionGrace():
tier = 0
case rank < myRank && aboveMin:
tier = 2
@@ -275,7 +275,7 @@ func (r *Reconciler) victims(m catalog.Model) []victim {
}
// Just started: stopping it throws away a model load that has
// only now been paid for.
if !rep.ReadyAt.IsZero() && now.Sub(rep.ReadyAt) < r.cfg.MinLifetime {
if !rep.ReadyAt.IsZero() && now.Sub(rep.ReadyAt) < r.minLifetime() {
continue
}
if len(nodesOf(rep)) > 1 {
@@ -264,6 +264,9 @@ type Reconciler struct {
// because it is state about this moment and not about what the model is.
// A model nobody has wanted has no entry and is simply not running.
wanted map[string]time.Time
// evictGrace and minLife are the cluster's on_demand settings, as
// durations; zero keeps cfg's.
evictGrace, minLife atomic.Int64
// coldStart is how long each model's last replica took from placed to
// ready, for telling a request waiting on it about how long it waits.
coldStart map[string]time.Duration
@@ -1763,6 +1763,31 @@ func mustResolve(t *testing.T, h *harness, name string) catalog.Model {
return m
}
func TestTheClustersOnDemandSettingsShortenTheWaitForACard(t *testing.T) {
// One card, a picture model and a 3D model: a mesh after a picture
// waited out five minutes of the picture model's protection.
h := newHarness(t, testModel(1), gpuNode("1", 4))
h.r.cat.Store(twoOnDemandModels(t))
h.r.Want("llama")
h.r.Reconcile(t.Context())
h.markReady()
reps := h.r.Replicas()
h.r.RecordUsage(map[string]time.Time{reps[0].ID: h.clock.now()})
h.advance(90 * time.Second)
if got := h.r.evictable("second"); len(got) != 0 {
t.Fatalf("offered at 90 s with the defaults: %+v", got)
}
h.r.SetEvictionTimes(30*time.Second, time.Minute)
if got := h.r.evictable("second"); len(got) != 1 {
t.Errorf("not offered at 90 s with 30 s idle and 1 min lifetime: %+v", got)
}
// Zero goes back to the configuration's.
h.r.SetEvictionTimes(0, 0)
if got := h.r.evictable("second"); len(got) != 0 {
t.Errorf("offered after the settings were cleared: %+v", got)
}
}
func TestAFreshlyStartedReplicaIsNotEvicted(t *testing.T) {
// What stops two models on a cluster with room for one from taking turns
// evicting each other, paying a model load each time. A load is expensive
+5
View File
@@ -260,6 +260,10 @@ var Reference = []Block{
{Key: "mirror", Type: "string", Doc: "Mirror is the mirror's file address, as nodes reach it:\nhttp://10.0.0.5:8081 — the port model files are served on, not the\nmanagement API. Set, the cluster is offline: nodes install engines\nfrom it and never from their publishers, releases come from it unless\nreleases names another place, and no registry is asked whether a\nmodel has newer weights. Python engines (vLLM, SGLang) come from PyPI,\nwhich no bundle carries; on an offline node they are installed by hand.", Nested: ""},
{Key: "checksums", Type: "string", Doc: "Checksums is the file of engine checksums this control plane trusts,\nkept by llmgw bundle import and llmgw bundle trust; every engine file\na node fetches from the mirror is checked against it. Read again\nwhenever it changes. Empty is /etc/llmgw/offline.sha256.", Nested: ""},
}},
{Package: "config", Name: "OnDemandSettings", Title: "OnDemandSettings", Doc: "", Fields: []Field{
{Key: "evict_after_idle", Type: "time.Duration", Doc: "EvictAfterIdle is how long an on-demand replica must go unasked-for\nbefore a model that wants its card may have it. Zero keeps 2m.", Nested: ""},
{Key: "min_lifetime", Type: "time.Duration", Doc: "MinLifetime is how long a replica that has just come up is safe from\nthat, so two models do not take turns paying for loads. Zero keeps\n5m. On one card shared by a picture model and a 3D model, 1m each\nbrings the wait between a picture and its mesh to about a minute.\nBoth are in force on the leader within seconds.", Nested: ""},
}},
{Package: "discovery", Name: "Options", Title: "Options", Doc: "", Fields: []Field{
{Key: "nvidia_smi", Type: "string", Doc: "NvidiaSMI is the path to nvidia-smi; empty means look it up on PATH.\nWorth configuring on nodes where the driver lives outside the default\npaths, which containerized driver installs often do.", Nested: ""},
{Key: "ib_root", Type: "string", Doc: "IBRoot is the sysfs InfiniBand directory.", Nested: ""},
@@ -442,6 +446,7 @@ var Reference = []Block{
{Key: "serving", Type: "ServingSettings", Doc: "Serving stops and starts the whole cluster's service (llmgw stop, llmgw\nstart).", Nested: "config.ServingSettings"},
{Key: "firewall", Type: "FirewallSettings", Doc: "Firewall turns llmgw's firewall on every machine on or off.", Nested: "config.FirewallSettings"},
{Key: "presets", Type: "PresetSettings", Doc: "Presets is how the models that come with llmgw reach the catalog.", Nested: "config.PresetSettings"},
{Key: "on_demand", Type: "OnDemandSettings", Doc: "OnDemand is how models that load when asked for take turns on the\ncards.", Nested: "config.OnDemandSettings"},
{Key: "agents", Type: "AgentSettings", Doc: "Agents are the nodes' agent settings: agent.yaml's keys but those an\nagent needs to start, for every node (default) and for one\n(nodes.<id>). Sent to the agents as they change; an agent whose\nsettings changed starts again on them, its engines serving\nthroughout.", Nested: "config.AgentSettings"},
{Key: "firewall_networks", Type: "[]string", Doc: "FirewallNetworks are networks, besides those each machine reaches the\ncluster on, that llmgw's internal ports answer: a monitoring host on\nanother subnet, nodes behind a router. Written into every machine's\nfirewall by `server init`, `node add` and `server add`.", Nested: ""},
{Key: "backup_recipients", Type: "[]string", Doc: "BackupRecipients encrypt every archive `llmgw server backup` writes, to\nwhoever holds one of their keys: age recipients (age1…) or SSH public\nkeys (ssh-ed25519 …, ssh-rsa …), as `age` takes them. An archive holds\nthe certificate authority's key and every secret in the store, and is\ncopied off the machine; encrypted, the copy is safe wherever it lands.\nEmpty writes archives unencrypted, readable by root only.", Nested: ""},
+1
View File
@@ -36,6 +36,7 @@ var Sources = []string{
"internal/config/firewall.go",
"internal/config/serving.go",
"internal/config/presets.go",
"internal/config/ondemand.go",
"internal/config/agents.go",
"internal/mail/mail.go",
"internal/notify/notify.go",
+6
View File
@@ -41,6 +41,10 @@ type Header struct {
// them; otherwise a head is EmbeddingLength / HeadCount.
KeyLength uint64
ValueLength uint64
// Embedding is whether the model pools its tokens into one vector
// (<arch>.pooling_type set and not none): an embedding model, which
// llama.cpp serves with --embedding and does not chat.
Embedding bool
}
// KVBytesPerToken is what one token of context costs in llama.cpp's default
@@ -265,6 +269,8 @@ func Read(r io.Reader) (Header, error) {
h.KeyLength = num
case "attention.value_length":
h.ValueLength = num
case "pooling_type":
h.Embedding = num > 0
}
}
// The tokenizer's arrays — megabytes of vocabulary — come after the
+25
View File
@@ -163,3 +163,28 @@ func TestArraysNestedDeepAreRefused(t *testing.T) {
t.Errorf("ten thousand nested arrays: %v", err)
}
}
func TestAnEmbeddingModelIsKnownByItsPooling(t *testing.T) {
build := func(pooling uint32) []byte {
var b bytes.Buffer
w := func(v any) { _ = binary.Write(&b, binary.LittleEndian, v) }
str := func(s string) { w(uint64(len(s))); b.WriteString(s) }
u32 := func(k string, v uint32) { str(k); w(uint32(tUint32)); w(v) }
b.WriteString("GGUF")
w(uint32(3))
w(uint64(0))
w(uint64(3))
str("general.architecture")
w(uint32(tString))
str("bert")
u32("bert.block_count", 24)
u32("bert.pooling_type", pooling)
return b.Bytes()
}
if h, err := Read(bytes.NewReader(build(2))); err != nil || !h.Embedding {
t.Errorf("CLS pooling: %+v %v", h, err)
}
if h, err := Read(bytes.NewReader(build(0))); err != nil || h.Embedding {
t.Errorf("no pooling: %+v %v", h, err)
}
}
+6 -2
View File
@@ -359,7 +359,9 @@ func (r *Router) Handler() http.Handler {
}
if r.auth == nil {
return r.refuseWhileStopped(r.refuseLoops(mux))
h := r.refuseWhileStopped(r.refuseLoops(mux))
r.selfHandler.Store(&h)
return h
}
exempt := []string{"/health", "/ready", "/leader", "/v1/openapi.json", "/", "/about", "/_static/", "/_lang/", "/claim/",
"/signup", "/login", "/login/", "/logout", "/profile", "/profile/", "/scim/",
@@ -373,7 +375,9 @@ func (r *Router) Handler() http.Handler {
// Wrapping the whole mux rather than checking inside each handler: adding a
// route must not be able to add an unauthenticated one by omission. Health
// stays open because a load balancer has no key.
return r.refuseWhileStopped(r.refuseLoops(auth.Middleware(r.auth, r.log, exempt...)(mux)))
h := r.refuseWhileStopped(r.refuseLoops(auth.Middleware(r.auth, r.log, exempt...)(mux)))
r.selfHandler.Store(&h)
return h
}
// refuseWhileStopped answers every request for a model with 503 while the
+29
View File
@@ -360,3 +360,32 @@ func TestAStandbyLeavesJobsToTheLeader(t *testing.T) {
t.Errorf("the leader did not serve it: %v", got)
}
}
func TestAJobWaitingForTheCardDoesNotHoldUpAnotherModelsJob(t *testing.T) {
// One at a time, an sf3d job waiting for the card held up a job for a
// model that could have run.
c := newJobComfy(t)
rt, secret := jobRouter(t, c)
rt.cfg.ActivationWait = 10 * time.Millisecond
rt.SetActivator(&waitingActivator{fakeActivator: fakeActivator{onDemand: map[string]bool{"sleepy": true}},
heldBy: "flux", eta: time.Hour})
now := time.Now()
put := func(id, model, body string, at time.Time) {
if err := rt.store.PutJob(t.Context(), store.Job{ID: id, Owner: "project:" + mustProjectOf(t, rt, "key-1"),
KeyID: "key-1", Endpoint: imagesPath, Model: model, Input: []byte(body), Status: store.JobQueued,
CreatedAt: at, ExpiresAt: at.Add(jobWindow)}); err != nil {
t.Fatal(err)
}
}
put("job_wait", "sleepy", `{"model":"sleepy","prompt":"a cube"}`, now.Add(-time.Minute))
put("job_go", "flux", `{"model":"flux","prompt":"a cube"}`, now)
rt.wakeJobs()
got := waitJob(t, rt.Handler(), secret, "job_go", jobDone)
if got["status"] != "completed" {
t.Errorf("the other model's job: %v", got)
}
if w, _ := rt.store.JobByID(t.Context(), "job_wait"); w.Status != store.JobRunning {
t.Errorf("the waiting job is %s", w.Status)
}
}
+38 -2
View File
@@ -10,6 +10,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
"gitea.mynodes.xyz/ilker/llmgw/internal/auth"
@@ -27,6 +28,10 @@ const (
jobCancelCheck = 2 * time.Second
// jobMaxResult bounds what one job may answer: a mesh, a short video.
jobMaxResult = 256 << 20
// jobsPerModel is how many of one model's jobs run at once: its engine
// works through them in turn anyway. jobsAtOnce bounds them all.
jobsPerModel = 1
jobsAtOnce = 8
)
// jobUnplacedGrace is how long a job keeps asking for a model said to fit
@@ -52,10 +57,28 @@ func (r *Router) runJobs(ctx context.Context) {
owner := fmt.Sprintf("%s:%d:%s", host, os.Getpid(), newID(""))
t := time.NewTicker(jobPoll)
defer t.Stop()
// Jobs run side by side, one per model at a time and jobsAtOnce in all:
// one at a time, a job waiting for the card held up another model's job
// that could have run.
var mu sync.Mutex
running := map[string]int{}
total := 0
for {
for r.leading() {
mu.Lock()
if total >= jobsAtOnce {
mu.Unlock()
break
}
var skip []string
for m, n := range running {
if n >= jobsPerModel {
skip = append(skip, m)
}
}
mu.Unlock()
now := time.Now()
j, ok, err := r.store.ClaimJob(ctx, owner, now, now.Add(jobLease))
j, ok, err := r.store.ClaimJob(ctx, owner, now, now.Add(jobLease), skip...)
if err != nil {
if ctx.Err() == nil {
r.log.Warn("could not look for jobs to serve", "err", err)
@@ -65,7 +88,20 @@ func (r *Router) runJobs(ctx context.Context) {
if !ok {
break
}
r.workJob(ctx, owner, j)
mu.Lock()
running[j.Model]++
total++
mu.Unlock()
go func(j store.Job) {
r.workJob(ctx, owner, j)
mu.Lock()
if running[j.Model]--; running[j.Model] <= 0 {
delete(running, j.Model)
}
total--
mu.Unlock()
r.wakeJobs() // room for the next
}(j)
}
// A job's record outlives its file by nothing: both go at the
// retention.
+937
View File
@@ -0,0 +1,937 @@
package router
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
_ "image/jpeg" // a picture sent to look at may be a JPEG
"image/png"
"net/http"
"slices"
"strconv"
"strings"
"sync"
"time"
"gitea.mynodes.xyz/ilker/llmgw/internal/auth"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
// --- MCP: pictures, 3D models, looking at pictures, workflows ---
//
// The gateway's own models offered as tools, so an agent — Claude Code
// driving Blender, say — makes a concept, a mesh from it and has a render
// looked at without a tool server of its own. Each tool makes its request
// of the gateway as the caller would, under the caller's key: the same
// allowlist, limits, licences left out, guardrails and accounting. What it
// makes is kept as a file of the caller's, said by id and by the address
// it is fetched from with the same key, since a tool server over HTTP
// cannot write to the caller's disk.
const (
// mcpBody bounds a tool call: up to four pictures to look at, as base64.
mcpBody = 64 << 20
// previewEdge is the long side of the picture shown to the agent beside
// the file: enough to see it, not a megapixel of tokens.
previewEdge = 512
// lookEdge is the long side of a picture sent to a vision model:
// 1280x720 is about 940 tokens.
lookEdge = 1280
// mcpWaitStreamed is how long a call answered as a stream waits for its
// job, saying how far along it is meanwhile; mcpWaitPlain how long one
// answered in one piece does, under the minute a proxy allows.
mcpWaitStreamed = 10 * time.Minute
mcpWaitPlain = 50 * time.Second
mcpWaitMax = 15 * time.Minute
mcpPoll = 2 * time.Second
)
// The prompt endings of generate_image's styles: what a picture a mesh is
// made from wants, and a surface that tiles.
var imageStyles = map[string]string{
"none": "",
"concept": ", single object centered, orthographic three-quarter view, flat even studio lighting, no shadows, " +
"no background elements, plain flat grey background, clean silhouette, game asset concept, high detail, no text, no watermark",
"side": ", single object, exact side view (profile), orthographic, flat even studio lighting, no shadows, " +
"plain flat grey background, clean silhouette, game asset concept, high detail, no text, no watermark",
"texture": ", seamless tileable texture, top-down orthographic, flat even lighting, no shadows, no perspective, no text",
}
// mcpMediaInstructions is said to an agent when it connects and the gateway
// has something to make pictures or 3D models with.
const mcpMediaInstructions = "Pictures, 3D models and a model that looks at pictures, on this gateway's own GPUs. " +
"A typical loop: generate_image (style concept) -> generate_mesh from its file_id -> import the GLB -> render -> " +
"review_images against the concept -> fix. Results are files: fetch them from their url with your API key. " +
"AI meshes suit rocks, debris and background props; hard-surface hero assets are usually better built by hand " +
"from the concept. A GPU holds one of these models at a time and switching costs a cold start, so batch calls " +
"of the same kind; gateway_status says which is loaded."
// mediaModels are the gateway's models by what they do, by name, deduplicated
// from the aliases that also resolve to them.
type mediaModels struct{ images, meshes, vision, workflows []string }
func (r *Router) mediaModels() mediaModels {
var out mediaModels
seen := map[string]bool{}
for _, m := range r.modelMap() {
if seen[m.Name] || m.IsGuard() {
continue
}
seen[m.Name] = true
if m.MakesImages() {
out.images = append(out.images, m.Name)
}
if m.MakesMeshes() {
out.meshes = append(out.meshes, m.Name)
}
if m.Capabilities.Vision {
out.vision = append(out.vision, m.Name)
}
if len(m.ComfyInputs()) > 0 {
out.workflows = append(out.workflows, m.Name)
}
}
for _, l := range [][]string{out.images, out.meshes, out.vision, out.workflows} {
slices.Sort(l)
}
return out
}
func (mm mediaModels) any() bool {
return len(mm.images)+len(mm.meshes)+len(mm.vision)+len(mm.workflows) > 0
}
// defaultOf is the model a tool uses when the call names none: the one the
// tool is best known with when the gateway has it, else the first.
func defaultOf(models []string, preferred ...string) string {
for _, p := range preferred {
if slices.Contains(models, p) {
return p
}
}
if len(models) == 0 {
return ""
}
return models[0]
}
func enumOrNone(models []string) map[string]any {
s := map[string]any{"type": "string"}
if len(models) > 0 {
s["enum"] = models
}
return s
}
// mediaTools are the tools for what the gateway's models can do: none for
// what it has no model for.
func (r *Router) mediaTools() []map[string]any {
mm := r.mediaModels()
var tools []map[string]any
fileArg := map[string]any{"type": "string",
"description": "A picture: a /v1/files id (file-…), a data URL, or base64"}
wait := map[string]any{"type": "integer", "minimum": 0, "maximum": int(mcpWaitMax.Seconds()),
"description": "Most seconds to wait for it before answering with the job to ask after (job_status)"}
if len(mm.images) > 0 {
tools = append(tools, map[string]any{
"name": "generate_image",
"description": "Make a picture from a prompt (~15 s warm, longer when the GPU must switch models). " +
"Keeps the PNG as a file and answers its file_id, url and seed, with a small preview. " +
"style: 'concept' (one object, 3/4 view, grey background: good for generate_mesh), 'side' " +
"(exact side view: best meshes for vehicles), 'texture' (seamless tileable surface), 'none' (the prompt as is).",
"inputSchema": map[string]any{
"type": "object",
"required": []string{"prompt"},
"properties": map[string]any{
"prompt": map[string]any{"type": "string"},
"style": map[string]any{"type": "string", "enum": []string{"none", "concept", "side", "texture"}, "default": "none"},
"size": map[string]any{"type": "integer", "description": "Square side in px, a multiple of 16, 256-2048", "default": 1024},
"seed": map[string]any{"type": "integer"},
"negative_prompt": map[string]any{"type": "string"},
"model": enumOrNone(mm.images),
},
},
})
}
if len(mm.meshes) > 0 {
tools = append(tools, map[string]any{
"name": "generate_mesh",
"description": "Make a 3D model (GLB) from a picture of one object on a plain background — the gateway " +
"cuts the background out itself — or from a prompt, for which a concept picture is made first. " +
"Takes 30 s to a few minutes; waits for it, saying how far along it is when the client takes a stream. " +
"Answers the GLB's file_id and url, and its licence. The mesh is about 1 m across, its orientation arbitrary.",
"inputSchema": map[string]any{
"type": "object",
"properties": map[string]any{
"image": fileArg,
"prompt": map[string]any{"type": "string", "description": "Used when no image is given"},
"model": enumOrNone(mm.meshes),
"seed": map[string]any{"type": "integer"},
"resolution": map[string]any{"type": "integer", "description": "The model's own grid, a multiple of 32 (TripoSR: 256 is enough)"},
"texture_resolution": map[string]any{"type": "integer", "minimum": 512, "maximum": 2048,
"description": "For a model that textures its mesh (sf3d): the texture's side in px"},
"inputs": map[string]any{"type": "object",
"description": "Any other input the model's workflow declares (gateway_status lists them): remesh, vertex_count, foreground_ratio, albedo_match…"},
"wait_seconds": wait,
},
},
})
}
if len(mm.vision) > 0 {
tools = append(tools, map[string]any{
"name": "review_images",
"description": "Ask a vision model about 1-4 pictures — a render beside its concept, say. A cheap critic " +
"for render-and-fix loops. json_schema makes it answer strict JSON. A cold start can take minutes " +
"when the GPU was making pictures.",
"inputSchema": map[string]any{
"type": "object",
"required": []string{"images", "question"},
"properties": map[string]any{
"images": map[string]any{"type": "array", "items": fileArg, "minItems": 1, "maxItems": 4},
"question": map[string]any{"type": "string"},
"json_schema": map[string]any{"type": "object", "description": "JSON Schema the answer must follow"},
"model": enumOrNone(mm.vision),
},
},
})
}
if len(mm.workflows) > 0 {
tools = append(tools, map[string]any{
"name": "run_workflow",
"description": "Run a ComfyUI workflow the gateway serves, with the inputs its catalog entry declares " +
"(gateway_status lists them). A file input is a /v1/files id, a data URL or base64. Answers its result file.",
"inputSchema": map[string]any{
"type": "object",
"required": []string{"model", "inputs"},
"properties": map[string]any{
"model": enumOrNone(mm.workflows),
"inputs": map[string]any{"type": "object"},
"wait_seconds": wait,
},
},
})
}
if mm.any() {
tools = append(tools,
map[string]any{
"name": "job_status",
"description": "Where a 3D model or workflow run stands, and its result file when done. wait_seconds waits for it to finish.",
"inputSchema": map[string]any{
"type": "object",
"required": []string{"job_id"},
"properties": map[string]any{"job_id": map[string]any{"type": "string"}, "wait_seconds": wait},
},
},
map[string]any{
"name": "gateway_status",
"description": "The gateway's picture, 3D, vision and workflow models: whether each is loaded on a GPU now, " +
"and a workflow's inputs; and your last few jobs. Use it to batch calls and avoid cold starts.",
"inputSchema": map[string]any{"type": "object", "properties": map[string]any{}},
})
}
return tools
}
// mediaCall is one tool call: who made it, and how to tell them how far it
// has got.
type mediaCall struct {
req *http.Request
progress func(percent float64, message string)
// streamed is a call whose answer is a stream, which may wait longer.
streamed bool
}
func (c mediaCall) wait(asked *int) time.Duration {
d := mcpWaitPlain
if c.streamed {
d = mcpWaitStreamed
}
if asked != nil {
d = min(time.Duration(*asked)*time.Second, mcpWaitMax)
}
return d
}
// isMediaTool is whether a tool is one of these.
func isMediaTool(name string) bool {
switch name {
case "generate_image", "generate_mesh", "review_images", "run_workflow", "job_status", "gateway_status":
return true
}
return false
}
// callMediaTool runs one of the tools. As with the notes, a failure is a
// tool result with isError set, which the model gets to read.
func (r *Router) callMediaTool(c mediaCall, name string, args json.RawMessage) map[string]any {
var res map[string]any
var err error
switch name {
case "generate_image":
res, err = r.toolGenerateImage(c, args)
case "generate_mesh":
res, err = r.toolGenerateMesh(c, args)
case "review_images":
res, err = r.toolReviewImages(c, args)
case "run_workflow":
res, err = r.toolRunWorkflow(c, args)
case "job_status":
res, err = r.toolJobStatus(c, args)
case "gateway_status":
res, err = r.toolGatewayStatus(c)
default:
err = errors.New("unknown tool " + name)
}
if err != nil {
return toolText(err.Error(), true)
}
return res
}
// self makes a request of the gateway's client API as the caller: their key,
// their agent name, and the context the call was made in.
func (r *Router) self(c mediaCall, method, path string, body any) (int, http.Header, []byte, error) {
h := r.selfHandler.Load()
if h == nil {
return 0, nil, nil, errors.New("the gateway's API is not mounted here")
}
var rd *bytes.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return 0, nil, nil, err
}
rd = bytes.NewReader(b)
} else {
rd = bytes.NewReader(nil)
}
out, err := http.NewRequestWithContext(c.req.Context(), method, path, rd)
if err != nil {
return 0, nil, nil, err
}
for _, k := range []string{"Authorization", "X-Api-Key", agentHeader, "X-Forwarded-For", "X-Real-Ip"} {
if v := c.req.Header.Get(k); v != "" {
out.Header.Set(k, v)
}
}
out.RemoteAddr = c.req.RemoteAddr
if body != nil {
out.Header.Set("Content-Type", "application/json")
}
// A picture or a mesh comes back whole: past the 1 MiB a judge's
// answer is held to.
w := &bufferWriter{header: http.Header{}, max: mcpBody * 2}
(*h).ServeHTTP(w, out)
status := w.status
if status == 0 {
status = http.StatusOK
}
return status, w.header, w.buf.Bytes(), nil
}
// selfJSON is self for an answer in JSON, a failure said as the API said it.
func (r *Router) selfJSON(c mediaCall, method, path string, body, into any) (http.Header, error) {
status, h, b, err := r.self(c, method, path, body)
if err != nil {
return nil, err
}
if status >= 300 {
return h, fmt.Errorf("%s %s: %d %s", method, path, status, errorMessage(b))
}
if into == nil {
return h, nil
}
return h, json.Unmarshal(b, into)
}
// fileURL is where a file is fetched from, with the caller's key, as the
// caller reached the gateway.
func fileURL(req *http.Request, id string) string {
scheme := "http"
if req.TLS != nil {
scheme = "https"
}
if p := req.Header.Get("X-Forwarded-Proto"); p != "" {
scheme = strings.TrimSpace(strings.Split(p, ",")[0])
}
host := req.Host
if h := req.Header.Get("X-Forwarded-Host"); h != "" {
host = strings.TrimSpace(strings.Split(h, ",")[0])
}
return scheme + "://" + host + "/v1/files/" + id + "/content"
}
// keepFile keeps what a tool made as the caller's file, for as long as a
// job's result is kept.
func (r *Router) keepFile(c mediaCall, name string, content []byte) (store.File, error) {
p, ok := auth.FromContext(c.req.Context())
if !ok || r.store == nil {
return store.File{}, errors.New("this gateway keeps no files (it runs without authentication or a store)")
}
if r.noStore(callerSubject(c.req)) {
return store.File{}, errors.New("the gateway's policy for this caller keeps nothing, so no file is kept")
}
_, _, _, days := r.batchCfg()
now := time.Now()
f := store.File{ID: newID("file-"), Owner: ownerOf(p), Purpose: purposeJobOutput, Filename: name,
Bytes: int64(len(content)), CreatedAt: now, ExpiresAt: now.AddDate(0, 0, days)}
return f, r.store.PutFile(c.req.Context(), f, content)
}
// picture reads a picture argument: a file of the caller's by id, a data URL,
// or base64.
func (r *Router) picture(c mediaCall, s string) ([]byte, error) {
s = strings.TrimSpace(s)
switch {
case s == "":
return nil, errors.New("no picture given")
case strings.HasPrefix(s, "file-"):
p, ok := auth.FromContext(c.req.Context())
if !ok || r.store == nil {
return nil, errors.New("this gateway keeps no files: send the picture as base64 or a data URL")
}
f, err := r.store.FileByID(c.req.Context(), s)
if errors.Is(err, store.ErrNotFound) || err == nil && f.Owner != ownerOf(p) {
return nil, fmt.Errorf("no file %s of yours", s)
}
if err != nil {
return nil, err
}
return r.store.FileContent(c.req.Context(), s)
case strings.HasPrefix(s, "data:"):
_, after, ok := strings.Cut(s, ";base64,")
if !ok {
return nil, errors.New("a data URL without base64 in it")
}
s = after
}
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return nil, errors.New("the picture is neither a file id, a data URL nor base64")
}
return b, nil
}
func dataURL(png []byte) string {
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
}
// shrink returns a picture as a PNG whose long side is at most edge.
func shrink(pic []byte, edge int) ([]byte, error) {
src, format, err := image.Decode(bytes.NewReader(pic))
if err != nil {
return nil, fmt.Errorf("not a picture this gateway reads (PNG or JPEG): %w", err)
}
b := src.Bounds()
w, h := b.Dx(), b.Dy()
if max(w, h) <= edge {
if format == "png" {
return pic, nil
}
edge = max(w, h) // only re-encoded
}
scale := float64(edge) / float64(max(w, h))
dw, dh := max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
dst := image.NewNRGBA(image.Rect(0, 0, dw, dh))
// Each pixel the average of the box of pixels it stands for.
for y := range dh {
y0, y1 := b.Min.Y+y*h/dh, b.Min.Y+max((y+1)*h/dh, y*h/dh+1)
for x := range dw {
x0, x1 := b.Min.X+x*w/dw, b.Min.X+max((x+1)*w/dw, x*w/dw+1)
var sr, sg, sb, sa, n uint64
for yy := y0; yy < y1; yy++ {
for xx := x0; xx < x1; xx++ {
cr, cg, cb, ca := src.At(xx, yy).RGBA()
sr, sg, sb, sa, n = sr+uint64(cr), sg+uint64(cg), sb+uint64(cb), sa+uint64(ca), n+1
}
}
// Premultiplied sums, back to straight colour.
if sa == 0 {
continue
}
dst.SetNRGBA(x, y, color.NRGBA{
R: uint8(sr * 0xff / sa), G: uint8(sg * 0xff / sa), B: uint8(sb * 0xff / sa), A: uint8(sa / n >> 8),
})
}
}
var out bytes.Buffer
if err := png.Encode(&out, dst); err != nil {
return nil, err
}
return out.Bytes(), nil
}
// --- the tools ---
func (r *Router) toolGenerateImage(c mediaCall, raw json.RawMessage) (map[string]any, error) {
var a struct {
Prompt string `json:"prompt"`
Style string `json:"style"`
NegativePrompt string `json:"negative_prompt"`
Model string `json:"model"`
Size int `json:"size"`
Seed *int64 `json:"seed"`
}
if err := decodeArgs(raw, &a); err != nil {
return nil, err
}
res, _, err := r.makeImage(c, a.Prompt, a.Style, a.NegativePrompt, a.Model, a.Size, a.Seed)
if err != nil {
return nil, err
}
return res, nil
}
// makeImage makes a picture and keeps it: the tool's answer, and the PNG.
func (r *Router) makeImage(c mediaCall, prompt, style, negative, model string, size int, seed *int64) (map[string]any, []byte, error) {
if strings.TrimSpace(prompt) == "" {
return nil, nil, errors.New("prompt is required")
}
if style == "" {
style = "none"
}
suffix, ok := imageStyles[style]
if !ok {
return nil, nil, fmt.Errorf("style %q: concept, side, texture or none", style)
}
if model == "" {
model = defaultOf(r.mediaModels().images, "flux-schnell")
}
if size == 0 {
size = 1024
}
body := map[string]any{"model": model, "prompt": prompt + suffix, "n": 1,
"size": fmt.Sprintf("%dx%d", size, size), "response_format": "b64_json"}
if seed != nil {
body["seed"] = *seed
}
if negative != "" {
body["negative_prompt"] = negative
}
c.progress(5, "making the picture with "+model)
var out struct {
Data []struct {
B64 string `json:"b64_json"`
} `json:"data"`
}
h, err := r.selfJSON(c, http.MethodPost, imagesPath, body, &out)
if err != nil {
return nil, nil, err
}
if len(out.Data) == 0 {
return nil, nil, errors.New(model + " made no picture")
}
pic, err := base64.StdEncoding.DecodeString(out.Data[0].B64)
if err != nil {
return nil, nil, err
}
info := map[string]any{"model": model, "width": size, "height": size}
if s, err := strconv.ParseInt(h.Get("x-llmgw-seed"), 10, 64); err == nil {
info["seed"] = s
}
if m, ok := r.modelMap()[model]; ok && m.License != nil {
info["license"] = m.License
}
content := []map[string]any{}
if f, err := r.keepFile(c, "image-"+strings.TrimPrefix(newID(""), "-")+".png", pic); err == nil {
info["file_id"], info["url"], info["bytes"] = f.ID, fileURL(c.req, f.ID), f.Bytes
} else {
// Nowhere to keep it: the picture itself, whole.
info["note"] = err.Error() + "; the picture is in this answer at full size"
content = append(content, map[string]any{"type": "image", "mimeType": "image/png", "data": out.Data[0].B64})
}
text, _ := json.Marshal(info)
content = append([]map[string]any{{"type": "text", "text": string(text)}}, content...)
if _, kept := info["file_id"]; kept {
if small, err := shrink(pic, previewEdge); err == nil {
content = append(content, map[string]any{"type": "image", "mimeType": "image/png",
"data": base64.StdEncoding.EncodeToString(small)})
}
}
return map[string]any{"content": content, "isError": false}, pic, nil
}
func (r *Router) toolGenerateMesh(c mediaCall, raw json.RawMessage) (map[string]any, error) {
var a struct {
Image, Prompt, Model string
Seed *int64
Resolution int
TextureResolution int `json:"texture_resolution"`
Inputs map[string]any
WaitSeconds *int `json:"wait_seconds"`
}
if err := decodeArgs(raw, &a); err != nil {
return nil, err
}
mm := r.mediaModels()
if a.Model == "" {
a.Model = defaultOf(mm.meshes, "sf3d", "triposr")
}
m, ok := r.modelMap()[a.Model]
if !ok || !m.MakesMeshes() {
return nil, fmt.Errorf("%q makes no 3D models here; these do: %s", a.Model, strings.Join(mm.meshes, ", "))
}
extra := map[string]any{}
var pic []byte
var err error
switch {
case a.Image != "":
if pic, err = r.picture(c, a.Image); err != nil {
return nil, err
}
case a.Prompt != "":
res, made, err := r.makeImage(c, a.Prompt, "concept", "", "", 0, nil)
if err != nil {
return nil, fmt.Errorf("the concept picture: %w", err)
}
pic = made
var info map[string]any
if json.Unmarshal([]byte(res["content"].([]map[string]any)[0]["text"].(string)), &info) == nil {
extra["concept_file_id"], extra["concept_seed"] = info["file_id"], info["seed"]
}
default:
return nil, errors.New("an image, or a prompt to make one from")
}
// A model whose workflow declares its inputs takes them at the
// workflows' path, every one it names; one that does not, the 3D path's
// seed and grid.
path, body := meshesPath, map[string]any{"model": a.Model, "image": dataURL(pic)}
if declared := m.ComfyInputs(); len(declared) > 0 {
names := map[string]string{}
var image string
for _, in := range declared {
names[in.Name] = in.Type
if image == "" && in.Type == "image" {
image = in.Name
}
}
if image == "" {
return nil, fmt.Errorf("%s's workflow takes no picture", a.Model)
}
inputs := map[string]any{image: dataURL(pic)}
for k, v := range a.Inputs {
inputs[k] = v
}
// A textured mesh's resolution is its texture's; a grid's, the grid's.
if _, ok := names["resolution"]; ok {
switch {
case a.TextureResolution > 0:
inputs["resolution"] = a.TextureResolution
case a.Resolution > 0:
inputs["resolution"] = a.Resolution
}
}
path, body = workflowsPath, map[string]any{"model": a.Model, "inputs": inputs}
if a.Seed != nil {
body["seed"] = *a.Seed
}
} else {
if a.Seed != nil {
body["seed"] = *a.Seed
}
if a.Resolution > 0 {
body["resolution"] = a.Resolution
}
}
var job struct {
ID string `json:"id"`
}
if _, err := r.selfJSON(c, http.MethodPost, path, body, &job); err != nil {
return nil, err
}
c.progress(10, "queued as "+job.ID)
return r.waitJob(c, job.ID, c.wait(a.WaitSeconds), extra)
}
func (r *Router) toolRunWorkflow(c mediaCall, raw json.RawMessage) (map[string]any, error) {
var a struct {
Model string
Inputs map[string]any
WaitSeconds *int `json:"wait_seconds"`
}
if err := decodeArgs(raw, &a); err != nil {
return nil, err
}
m, ok := r.modelMap()[a.Model]
if !ok || len(m.ComfyInputs()) == 0 {
return nil, fmt.Errorf("%q runs no workflow here; these do: %s", a.Model, strings.Join(r.mediaModels().workflows, ", "))
}
// A file input given as a file id goes as it is: the API takes those.
var job struct {
ID string `json:"id"`
}
if _, err := r.selfJSON(c, http.MethodPost, workflowsPath, map[string]any{"model": a.Model, "inputs": a.Inputs}, &job); err != nil {
return nil, err
}
c.progress(10, "queued as "+job.ID)
return r.waitJob(c, job.ID, c.wait(a.WaitSeconds), nil)
}
func (r *Router) toolJobStatus(c mediaCall, raw json.RawMessage) (map[string]any, error) {
var a struct {
JobID string `json:"job_id"`
WaitSeconds *int `json:"wait_seconds"`
}
if err := decodeArgs(raw, &a); err != nil {
return nil, err
}
if a.JobID == "" {
return nil, errors.New("job_id is required")
}
d := time.Duration(0)
if a.WaitSeconds != nil {
d = c.wait(a.WaitSeconds)
}
return r.waitJob(c, a.JobID, d, nil)
}
// jobView is the part of a job a tool says.
type jobView struct {
ID string `json:"id"`
Model string `json:"model"`
Status string `json:"status"`
Progress json.RawMessage `json:"progress"`
OutputFileID *string `json:"output_file_id"`
ContentType *string `json:"content_type"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
License json.RawMessage `json:"license"`
}
// waitJob asks after a job until it is done or d has passed, saying how far
// along it is, and answers where it stands: its file when done.
func (r *Router) waitJob(c mediaCall, id string, d time.Duration, extra map[string]any) (map[string]any, error) {
deadline := time.Now().Add(d)
var j jobView
for {
if _, err := r.selfJSON(c, http.MethodGet, workflowsPath+"/"+id, nil, &j); err != nil {
return nil, err
}
if store.JobDone(j.Status) || !time.Now().Before(deadline) {
break
}
pct, msg := jobProgress(j)
c.progress(pct, msg)
select {
case <-c.req.Context().Done():
return nil, c.req.Context().Err()
case <-time.After(mcpPoll):
}
}
info := map[string]any{"job_id": j.ID, "model": j.Model, "status": j.Status}
for k, v := range extra {
if v != nil {
info[k] = v
}
}
if len(j.License) > 0 && string(j.License) != "null" {
info["license"] = j.License
}
switch {
case j.Status == store.JobCompleted && j.OutputFileID != nil:
info["file_id"], info["url"] = *j.OutputFileID, fileURL(c.req, *j.OutputFileID)
if j.ContentType != nil {
info["content_type"] = *j.ContentType
}
if r.store != nil {
if f, err := r.store.FileByID(c.req.Context(), *j.OutputFileID); err == nil {
info["bytes"] = f.Bytes
}
}
case store.JobDone(j.Status):
if j.Error != nil {
info["error"] = j.Error.Message
}
b, _ := json.Marshal(info)
return toolText(string(b), true), nil
default:
info["progress"] = j.Progress
info["next"] = "not done yet: call job_status with this job_id (and wait_seconds) to wait for it"
}
b, _ := json.Marshal(info)
return toolText(string(b), false), nil
}
// jobProgress reads a job's progress as a percent and a phrase.
func jobProgress(j jobView) (float64, string) {
var p struct {
State string `json:"state"`
Ahead int `json:"ahead"`
Percent float64 `json:"percent"`
Node string `json:"node_class"`
HeldBy string `json:"held_by"`
}
_ = json.Unmarshal(j.Progress, &p)
switch {
case p.State == "queued":
return 10, fmt.Sprintf("%s: queued, %d ahead", j.ID, p.Ahead)
case p.State == "waiting_gpu":
return 10, j.ID + ": waiting for the GPU, held by " + p.HeldBy
case p.State == "running":
return 10 + 0.9*p.Percent, fmt.Sprintf("%s: %s %.0f%%", j.ID, p.Node, p.Percent)
}
return 10, j.ID + ": " + j.Status
}
func (r *Router) toolReviewImages(c mediaCall, raw json.RawMessage) (map[string]any, error) {
var a struct {
Images []string
Question string
JSONSchema map[string]any `json:"json_schema"`
Model string
}
if err := decodeArgs(raw, &a); err != nil {
return nil, err
}
if len(a.Images) == 0 || len(a.Images) > 4 {
return nil, errors.New("one to four images")
}
if strings.TrimSpace(a.Question) == "" {
return nil, errors.New("question is required")
}
if a.Model == "" {
a.Model = defaultOf(r.mediaModels().vision, "vlm")
}
if a.Model == "" {
return nil, errors.New("no model here looks at pictures")
}
parts := []map[string]any{{"type": "text", "text": a.Question}}
for i, s := range a.Images {
pic, err := r.picture(c, s)
if err != nil {
return nil, fmt.Errorf("image %d: %w", i+1, err)
}
small, err := shrink(pic, lookEdge)
if err != nil {
return nil, fmt.Errorf("image %d: %w", i+1, err)
}
parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": dataURL(small)}})
}
body := map[string]any{"model": a.Model, "messages": []map[string]any{{"role": "user", "content": parts}}}
if a.JSONSchema != nil {
body["response_format"] = map[string]any{"type": "json_schema",
"json_schema": map[string]any{"name": "answer", "schema": a.JSONSchema, "strict": true}}
}
c.progress(10, "asking "+a.Model)
var out struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if _, err := r.selfJSON(c, http.MethodPost, "/v1/chat/completions", body, &out); err != nil {
return nil, err
}
if len(out.Choices) == 0 {
return nil, errors.New(a.Model + " gave no answer")
}
return toolText(out.Choices[0].Message.Content, false), nil
}
func (r *Router) toolGatewayStatus(c mediaCall) (map[string]any, error) {
var models struct {
Data []map[string]any `json:"data"`
}
if _, err := r.selfJSON(c, http.MethodGet, "/v1/models", nil, &models); err != nil {
return nil, err
}
var listed []map[string]any
for _, m := range models.Data {
caps, _ := m["capabilities"].(map[string]any)
if caps["images"] != true && caps["meshes"] != true && caps["vision"] != true && m["workflow"] == nil {
continue
}
e := map[string]any{"id": m["id"], "loaded": m["loaded"], "capabilities": caps}
if w := m["workflow"]; w != nil {
e["workflow"] = w
}
if l := m["license"]; l != nil {
e["license"] = l
}
listed = append(listed, e)
}
out := map[string]any{"models": listed}
var jobs struct {
Data []jobView `json:"data"`
}
if _, err := r.selfJSON(c, http.MethodGet, workflowsPath+"?limit=5", nil, &jobs); err == nil {
recent := make([]map[string]any, 0, len(jobs.Data))
for _, j := range jobs.Data {
recent = append(recent, map[string]any{"id": j.ID, "model": j.Model, "status": j.Status})
}
out["recent_jobs"] = recent
}
return toolJSON(out), nil
}
// decodeArgs reads a tool's arguments, by their JSON names: a field's own
// name in lower case unless its tag says.
func decodeArgs(raw json.RawMessage, into any) error {
if len(raw) == 0 || string(raw) == "null" {
raw = []byte("{}")
}
if err := json.Unmarshal(raw, into); err != nil {
return fmt.Errorf("the arguments: %w", err)
}
return nil
}
// streamWriter answers a tool call as server-sent events: progress
// notifications while it runs, then the answer.
type streamWriter struct {
mu sync.Mutex
w http.ResponseWriter
token json.RawMessage
}
func (s *streamWriter) write(text string) {
s.mu.Lock()
defer s.mu.Unlock()
_, _ = fmt.Fprint(s.w, text)
if f, ok := s.w.(http.Flusher); ok {
f.Flush()
}
}
func (s *streamWriter) event(v any) {
b, _ := json.Marshal(v)
s.write("event: message\ndata: " + string(b) + "\n\n")
}
// keepAlive writes a comment every while until stop is closed: a picture
// whose model starts cold is minutes of nothing said, which a proxy reads as
// a connection gone idle.
func (s *streamWriter) keepAlive(stop <-chan struct{}, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
s.write(": still working\n\n")
}
}
}
func (s *streamWriter) progress(percent float64, message string) {
if len(s.token) == 0 {
return
}
s.event(map[string]any{"jsonrpc": "2.0", "method": "notifications/progress", "params": map[string]any{
"progressToken": s.token, "progress": percent, "total": 100, "message": message}})
}
// acceptsStream is a client that takes a POST's answer as a stream, as the
// streamable HTTP transport lets it.
func acceptsStream(req *http.Request) bool {
return strings.Contains(req.Header.Get("Accept"), "text/event-stream")
}
+266
View File
@@ -0,0 +1,266 @@
package router
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image"
"image/png"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.mynodes.xyz/ilker/llmgw/internal/config"
"gitea.mynodes.xyz/ilker/llmgw/internal/control/catalog"
)
// mcp makes one JSON-RPC call at /mcp and answers its result; streamed, as a
// client that takes server-sent events, it answers the events' data too.
func mcp(t *testing.T, h http.Handler, secret, method string, params any, streamed bool) (map[string]any, []string) {
t.Helper()
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
req := httptest.NewRequest(http.MethodPost, "/mcp", bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
if secret != "" {
req.Header.Set("Authorization", "Bearer "+secret)
}
if streamed {
req.Header.Set("Accept", "application/json, text/event-stream")
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", method, rec.Code, rec.Body.String())
}
body := rec.Body.String()
var events []string
if streamed {
if ct := rec.Header().Get("Content-Type"); ct != "text/event-stream" {
t.Fatalf("a streamed call answered %s: %s", ct, body)
}
for _, line := range strings.Split(body, "\n") {
if d, ok := strings.CutPrefix(line, "data: "); ok {
events = append(events, d)
}
}
if len(events) == 0 {
t.Fatalf("no events: %s", body)
}
body = events[len(events)-1]
}
var resp struct {
Result map[string]any `json:"result"`
Error any `json:"error"`
}
if err := json.Unmarshal([]byte(body), &resp); err != nil || resp.Error != nil {
t.Fatalf("%s: %v %s", method, err, body)
}
return resp.Result, events
}
func toolNames(res map[string]any) []string {
var names []string
for _, tl := range res["tools"].([]any) {
names = append(names, tl.(map[string]any)["name"].(string))
}
return names
}
// resultInfo is a tool result's first text, as the JSON it holds.
func resultInfo(t *testing.T, res map[string]any) map[string]any {
t.Helper()
if res["isError"] == true {
t.Fatalf("the tool failed: %v", res["content"])
}
var info map[string]any
text := res["content"].([]any)[0].(map[string]any)["text"].(string)
if err := json.Unmarshal([]byte(text), &info); err != nil {
t.Fatalf("not JSON: %s", text)
}
return info
}
func TestTheMCPToolsAreWhatTheGatewaysModelsCanDo(t *testing.T) {
c := newMeshComfy(t)
rt, secret := meshRouter(t, c)
h := rt.Handler()
init, _ := mcp(t, h, secret, "initialize", map[string]any{"protocolVersion": "2025-06-18"}, false)
if init["protocolVersion"] != "2025-06-18" || !strings.Contains(init["instructions"].(string), "batch calls") {
t.Errorf("initialize: %v", init)
}
list, _ := mcp(t, h, secret, "tools/list", map[string]any{}, false)
names := strings.Join(toolNames(list), ",")
for _, want := range []string{"remember", "generate_image", "generate_mesh", "job_status", "gateway_status"} {
if !strings.Contains(names, want) {
t.Errorf("no %s in %s", want, names)
}
}
// Nothing here looks at pictures or declares a workflow's inputs.
if strings.Contains(names, "review_images") || strings.Contains(names, "run_workflow") {
t.Errorf("tools for models the gateway has not: %s", names)
}
// A gateway with only text models offers the notes alone.
plain := newTestRouter(t, baseConfig()).Handler()
list, _ = mcp(t, plain, "", "tools/list", map[string]any{}, false)
if got := strings.Join(toolNames(list), ","); got != "remember,recall,forget" {
t.Errorf("a text-only gateway offers %s", got)
}
}
func TestAMeshIsMadeThroughMCPAndKeptAsTheCallersFile(t *testing.T) {
c := newMeshComfy(t)
rt, secret := meshRouter(t, c)
h := rt.Handler()
args := map[string]any{"model": "trellis2", "image": "data:image/png;base64," + testPicture(t), "seed": 3}
for _, streamed := range []bool{false, true} {
res, events := mcp(t, h, secret, "tools/call", map[string]any{"name": "generate_mesh", "arguments": args,
"_meta": map[string]any{"progressToken": "tok"}}, streamed)
info := resultInfo(t, res)
if info["status"] != "completed" || info["license"].(map[string]any)["name"] != "MIT" {
t.Fatalf("streamed %v: %v", streamed, info)
}
id, _ := info["file_id"].(string)
if !strings.HasSuffix(info["url"].(string), "/v1/files/"+id+"/content") {
t.Errorf("url %v", info["url"])
}
// Fetched with the same key, it is the mesh.
code, _, file := call(t, h, secret, http.MethodGet, "/v1/files/"+id+"/content", nil)
if code != http.StatusOK || !strings.HasPrefix(file, "glTF") {
t.Fatalf("the file is not the mesh: %d", code)
}
if streamed && !strings.Contains(strings.Join(events, "\n"), `"progressToken":"tok"`) {
t.Errorf("no progress said while it ran: %v", events)
}
}
// The job went through the client API as the caller: it is theirs.
_, list, _ := call(t, h, secret, http.MethodGet, meshesPath, nil)
if n := len(list["data"].([]any)); n != 2 {
t.Errorf("%d jobs of the caller's, want the two made", n)
}
// Under no key, nothing is made.
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": map[string]any{"name": "generate_mesh", "arguments": args}})
req := httptest.NewRequest(http.MethodPost, "/mcp", bytes.NewReader(b))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("a call with no key: %d", rec.Code)
}
}
func TestAPictureMadeThroughMCPComesWholeWhereNoFileCanBeKept(t *testing.T) {
rt, queued, mu := imageRouter(t)
h := rt.Handler()
res, _ := mcp(t, h, "", "tools/call", map[string]any{"name": "generate_image",
"arguments": map[string]any{"prompt": "a rock", "style": "concept", "size": 512, "seed": 9}}, false)
info := resultInfo(t, res)
if info["seed"] != 9.0 || info["model"] != "flux" || !strings.Contains(info["note"].(string), "keeps no files") {
t.Errorf("info %v", info)
}
content := res["content"].([]any)
if len(content) != 2 || content[1].(map[string]any)["type"] != "image" {
t.Fatalf("the picture is not in the answer: %v", content)
}
if b, _ := base64.StdEncoding.DecodeString(content[1].(map[string]any)["data"].(string)); string(b) != "png-bytes" {
t.Errorf("picture %q", b)
}
mu.Lock()
wf, _ := json.Marshal(*queued)
mu.Unlock()
if !strings.Contains(string(wf), "a rock, single object centered") || !strings.Contains(string(wf), `"width":512`) {
t.Errorf("the style was not added to the prompt: %s", wf)
}
}
func TestAPictureIsShrunkToItsLongSide(t *testing.T) {
var b bytes.Buffer
_ = png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2000, 1000)))
out, err := shrink(b.Bytes(), 512)
if err != nil {
t.Fatal(err)
}
im, err := png.Decode(bytes.NewReader(out))
if err != nil || im.Bounds().Dx() != 512 || im.Bounds().Dy() != 256 {
t.Fatalf("%v %v", im.Bounds(), err)
}
b.Reset()
_ = png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 100, 50)))
if out, _ := shrink(b.Bytes(), 512); !bytes.Equal(out, b.Bytes()) {
t.Error("a small PNG was re-encoded")
}
}
func TestAWorkflowRunsThroughMCPFromItsDeclaredInputs(t *testing.T) {
wav := testWAV()
c := newRunComfy(t, wav, "song_00001_.wav")
rt, secret, _ := runRouter(t, c, songWorkflow, catalog.OutputAudio)
h := rt.Handler()
list, _ := mcp(t, h, secret, "tools/list", map[string]any{}, false)
if !strings.Contains(strings.Join(toolNames(list), ","), "run_workflow") {
t.Fatalf("no run_workflow for a model that declares its inputs: %v", toolNames(list))
}
res, _ := mcp(t, h, secret, "tools/call", map[string]any{"name": "run_workflow", "arguments": map[string]any{
"model": "ace", "inputs": map[string]any{"tags": "synthwave", "cover": "data:image/png;base64," + testPicture(t)}}}, false)
info := resultInfo(t, res)
if info["status"] != "completed" || info["content_type"] != "audio/wav" {
t.Fatalf("%v", info)
}
if _, _, file := call(t, h, secret, http.MethodGet, "/v1/files/"+info["file_id"].(string)+"/content", nil); file != string(wav) {
t.Error("the file is not the song")
}
// A run refused says why, as the API did.
res, _ = mcp(t, h, secret, "tools/call", map[string]any{"name": "run_workflow", "arguments": map[string]any{
"model": "ace", "inputs": map[string]any{"cover": "data:image/png;base64," + testPicture(t)}}}, false)
if res["isError"] != true || !strings.Contains(fmt.Sprint(res["content"]), "tags") {
t.Errorf("a run missing a required input: %v", res)
}
}
func TestPicturesAreLookedAtByAVisionModelShrunkAndToASchema(t *testing.T) {
e := newFakeEngine(t, "vlm")
cfg := baseConfig(config.Endpoint{ID: "a", URL: e.srv.URL, Models: []string{"vlm"}})
vlm := catModel("vlm", nil)
vlm.Capabilities.Vision = true
cfg.Models = []catalog.Model{vlm}
h := newTestRouter(t, cfg).Handler()
var big bytes.Buffer
_ = png.Encode(&big, image.NewRGBA(image.Rect(0, 0, 3000, 1500)))
res, _ := mcp(t, h, "", "tools/call", map[string]any{"name": "review_images", "arguments": map[string]any{
"images": []string{base64.StdEncoding.EncodeToString(big.Bytes())},
"question": "Does the render match the concept?",
"json_schema": map[string]any{"type": "object", "properties": map[string]any{"match": map[string]any{"type": "boolean"}}},
}}, false)
if res["isError"] == true || !strings.Contains(fmt.Sprint(res["content"]), "hi") {
t.Fatalf("%v", res)
}
var sent struct {
ResponseFormat struct {
Type string `json:"type"`
} `json:"response_format"`
Messages []struct {
Content []struct {
Type string `json:"type"`
ImageURL struct {
URL string `json:"url"`
} `json:"image_url"`
} `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(e.last.Load().([]byte), &sent); err != nil {
t.Fatal(err)
}
if sent.ResponseFormat.Type != "json_schema" || len(sent.Messages) != 1 || len(sent.Messages[0].Content) != 2 {
t.Fatalf("sent %+v", sent)
}
b64, _ := strings.CutPrefix(sent.Messages[0].Content[1].ImageURL.URL, "data:image/png;base64,")
pic, _ := base64.StdEncoding.DecodeString(b64)
im, err := png.Decode(bytes.NewReader(pic))
if err != nil || im.Bounds().Dx() != lookEdge || im.Bounds().Dy() != lookEdge/2 {
t.Errorf("the picture sent is %v (%v), not shrunk to %d", im.Bounds(), err, lookEdge)
}
}
+51 -6
View File
@@ -5,6 +5,7 @@ import (
"errors"
"io"
"net/http"
"slices"
"strconv"
"time"
@@ -120,7 +121,8 @@ func (r *Router) handlePutNote(w http.ResponseWriter, req *http.Request) {
Text string `json:"text"`
Tags []string `json:"tags"`
}
raw, err := io.ReadAll(http.MaxBytesReader(w, req.Body, maxMemoryBody))
// Pictures to look at come in the call, as base64.
raw, err := io.ReadAll(http.MaxBytesReader(w, req.Body, mcpBody))
if err != nil || json.Unmarshal(raw, &body) != nil {
writeError(w, http.StatusBadRequest, "invalid_request_error",
`body must be JSON like {"text": "...", "tags": ["..."]}`)
@@ -273,23 +275,66 @@ func (r *Router) handleMCP(w http.ResponseWriter, req *http.Request) {
resp := rpcResponse{JSONRPC: "2.0", ID: rpc.ID}
switch rpc.Method {
case "initialize":
resp.Result = map[string]any{
"protocolVersion": mcpProtocolVer,
result := map[string]any{
"protocolVersion": mcpVersionFor(rpc.Params),
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": "llmgw-memory", "version": "1"},
"serverInfo": map[string]any{"name": "llmgw", "version": "1"},
}
if r.mediaModels().any() {
result["instructions"] = mcpMediaInstructions
}
resp.Result = result
case "ping":
resp.Result = map[string]any{}
case "tools/list":
resp.Result = map[string]any{"tools": mcpTools}
resp.Result = map[string]any{"tools": append(slices.Clone(mcpTools), r.mediaTools()...)}
case "tools/call":
resp.Result = r.callMemoryTool(req, rpc.Params)
var call struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
Meta struct {
ProgressToken json.RawMessage `json:"progressToken"`
} `json:"_meta"`
}
_ = json.Unmarshal(rpc.Params, &call)
if !isMediaTool(call.Name) {
resp.Result = r.callMemoryTool(req, rpc.Params)
break
}
if acceptsStream(req) {
// Answered as a stream: how far along it is while it runs, which
// a mesh's minutes want, then the answer.
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
sw := &streamWriter{w: w, token: call.Meta.ProgressToken}
stop := make(chan struct{})
go sw.keepAlive(stop, 15*time.Second)
resp.Result = r.callMediaTool(mediaCall{req: req, progress: sw.progress, streamed: true}, call.Name, call.Arguments)
close(stop)
sw.event(resp)
return
}
resp.Result = r.callMediaTool(mediaCall{req: req, progress: func(float64, string) {}}, call.Name, call.Arguments)
default:
resp.Error = &rpcError{Code: -32601, Message: "method not found: " + rpc.Method}
}
writeJSON(w, http.StatusOK, resp)
}
// mcpVersionFor is the protocol version answered: the client's, of those
// this server speaks, else its own.
func mcpVersionFor(params json.RawMessage) string {
var p struct {
ProtocolVersion string `json:"protocolVersion"`
}
_ = json.Unmarshal(params, &p)
if slices.Contains([]string{"2025-03-26", "2025-06-18"}, p.ProtocolVersion) {
return p.ProtocolVersion
}
return mcpProtocolVer
}
func toolText(text string, isError bool) map[string]any {
return map[string]any{
"content": []map[string]any{{"type": "text", "text": text}},
+67 -8
View File
@@ -12,9 +12,10 @@ import (
// Anthropic's Messages API (/v1/messages), translated to a chat completion
// on the way in and back on the way out, like the Responses API: so Claude
// Code and Anthropic's SDKs reach the models here. Text, images, tools and
// their results, the system prompt and streaming are translated; extended
// thinking, prompt caching and server tools are not, and are ignored rather
// than refused.
// their results, the system prompt, streaming and extended thinking are
// translated; prompt caching and server tools are not, and are ignored rather
// than refused. Thinking asked for is a model's reasoning_content, given
// back as thinking blocks before the text; not asked for, it is left out.
type msgRequest struct {
Model string `json:"model"`
@@ -34,8 +35,16 @@ type msgRequest struct {
Metadata *struct {
UserID string `json:"user_id"`
} `json:"metadata"`
// Thinking is extended thinking: "enabled" (with a budget the engines
// here do not take) or "disabled".
Thinking *struct {
Type string `json:"type"`
} `json:"thinking"`
}
// thinks is whether the request asked for thinking blocks.
func (in msgRequest) thinks() bool { return in.Thinking != nil && in.Thinking.Type == "enabled" }
type msgMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
@@ -197,6 +206,16 @@ func messagesToChat(in msgRequest) (map[string]any, error) {
if in.Metadata != nil && in.Metadata.UserID != "" {
out["user"] = in.Metadata.UserID
}
// A model that thinks or not as its chat template is told (Qwen3, and
// the reasoning models served the same way) is told what was asked.
if in.Thinking != nil {
switch in.Thinking.Type {
case "enabled":
out["chat_template_kwargs"] = map[string]any{"enable_thinking": true}
case "disabled":
out["chat_template_kwargs"] = map[string]any{"enable_thinking": false}
}
}
var tools []map[string]any
for _, t := range in.Tools {
if t.Type != "" && t.Type != "custom" {
@@ -250,7 +269,7 @@ func (r *Router) handleMessages(w http.ResponseWriter, req *http.Request) {
next.ContentLength = int64(len(upstream))
next.Header.Set("Content-Type", "application/json")
t := &msgTranslator{w: w, model: in.Model, stream: in.Stream, id: newID("msg_")}
t := &msgTranslator{w: w, model: in.Model, stream: in.Stream, id: newID("msg_"), thinking: in.thinks()}
r.handleInference("/v1/chat/completions")(t, next)
t.finish()
}
@@ -309,6 +328,11 @@ type msgTranslator struct {
model string
stream bool
id string
// thinking is whether the reasoning is given as thinking blocks.
thinking bool
// thinkIndex and thinkOpen are the thinking block being streamed.
thinkIndex int
thinkOpen bool
status int
failed bool
@@ -415,6 +439,20 @@ func stopReason(finish string) string {
return "end_turn"
}
// thinkingSignature stands where Anthropic signs a thinking block: the
// thinking here comes from the gateway's own models, and nothing checks it,
// but the SDKs expect the field.
const thinkingSignature = "llmgw"
func (t *msgTranslator) closeThinking() {
if t.thinkOpen {
t.event("content_block_delta", map[string]any{"index": t.thinkIndex,
"delta": map[string]any{"type": "signature_delta", "signature": thinkingSignature}})
t.event("content_block_stop", map[string]any{"index": t.thinkIndex})
t.thinkOpen = false
}
}
func (t *msgTranslator) closeText() {
if t.textOpen {
t.event("content_block_stop", map[string]any{"index": t.textIndex})
@@ -433,8 +471,11 @@ func (t *msgTranslator) chatLine(line string) {
var chunk struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
ToolCalls []struct {
Content string `json:"content"`
// The reasoning, by either name the engines give it.
ReasoningContent string `json:"reasoning_content"`
Reasoning string `json:"reasoning"`
ToolCalls []struct {
Index int `json:"index"`
ID string `json:"id"`
Function struct {
@@ -461,7 +502,18 @@ func (t *msgTranslator) chatLine(line string) {
if ch.FinishReason != "" {
t.stopReason = stopReason(ch.FinishReason)
}
if r := ch.Delta.ReasoningContent + ch.Delta.Reasoning; r != "" && t.thinking {
if !t.thinkOpen {
t.thinkIndex, t.thinkOpen = t.nextBlock, true
t.nextBlock++
t.event("content_block_start", map[string]any{"index": t.thinkIndex,
"content_block": map[string]any{"type": "thinking", "thinking": ""}})
}
t.event("content_block_delta", map[string]any{"index": t.thinkIndex,
"delta": map[string]any{"type": "thinking_delta", "thinking": r}})
}
if d := ch.Delta.Content; d != "" {
t.closeThinking()
if !t.textOpen && t.text.Len() == 0 {
t.textIndex, t.textOpen = t.nextBlock, true
t.nextBlock++
@@ -477,6 +529,7 @@ func (t *msgTranslator) chatLine(line string) {
for _, tc := range ch.Delta.ToolCalls {
c := t.byIndex[tc.Index]
if c == nil {
t.closeThinking()
t.closeText()
for _, o := range t.calls {
if o.open {
@@ -532,6 +585,7 @@ func (t *msgTranslator) finish() {
t.chatLine(rest)
}
t.begin()
t.closeThinking()
t.closeText()
for _, c := range t.calls {
if c.open {
@@ -553,8 +607,10 @@ func (t *msgTranslator) fromChatJSON(b []byte) {
var c struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
Reasoning string `json:"reasoning"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
@@ -578,6 +634,9 @@ func (t *msgTranslator) fromChatJSON(b []byte) {
if len(c.Choices) > 0 {
ch := c.Choices[0]
reason = stopReason(ch.FinishReason)
if r := ch.Message.ReasoningContent + ch.Message.Reasoning; r != "" && t.thinking {
content = append(content, map[string]any{"type": "thinking", "thinking": r, "signature": thinkingSignature})
}
if ch.Message.Content != "" {
content = append(content, map[string]any{"type": "text", "text": ch.Message.Content})
}
+62
View File
@@ -139,3 +139,65 @@ func TestAnAnthropicClientsKeyIsAccepted(t *testing.T) {
t.Errorf("%d %s", rec.Code, rec.Body.String())
}
}
func TestThinkingAskedForComesBackAsThinkingBlocks(t *testing.T) {
// A reasoning model's thoughts were dropped: Claude Code asking for
// extended thinking got the answer alone.
var in msgRequest
_ = json.Unmarshal([]byte(`{"model":"m","max_tokens":10,"thinking":{"type":"enabled","budget_tokens":2048},
"messages":[{"role":"user","content":"hi"}]}`), &in)
chat, _ := messagesToChat(in)
if b, _ := json.Marshal(chat); !strings.Contains(string(b), `"chat_template_kwargs":{"enable_thinking":true}`) {
t.Errorf("the model was not told to think: %s", b)
}
whole := `{"choices":[{"message":{"reasoning_content":"two plus two","content":"4"},"finish_reason":"stop"}],
"usage":{"prompt_tokens":3,"completion_tokens":5}}`
_, h := messagesRouter(t, whole)
body := map[string]any{"model": "m", "max_tokens": 10, "thinking": map[string]any{"type": "enabled", "budget_tokens": 1024},
"messages": []any{map[string]any{"role": "user", "content": "2+2?"}}}
var out struct {
Content []map[string]any `json:"content"`
}
_ = json.Unmarshal(sendMessages(t, h, body).Body.Bytes(), &out)
if len(out.Content) != 2 || out.Content[0]["type"] != "thinking" || out.Content[0]["thinking"] != "two plus two" ||
out.Content[0]["signature"] == nil || out.Content[1]["text"] != "4" {
t.Errorf("content %v", out.Content)
}
// Not asked for, it is left out, as before.
delete(body, "thinking")
_ = json.Unmarshal(sendMessages(t, h, body).Body.Bytes(), &out)
if len(out.Content) != 1 || out.Content[0]["type"] != "text" {
t.Errorf("unasked, content %v", out.Content)
}
}
func TestStreamedThinkingIsItsOwnBlock(t *testing.T) {
stream := "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"two \"}}]}\n\n" +
"data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"plus two\"}}]}\n\n" +
"data: {\"choices\":[{\"delta\":{\"content\":\"4\"},\"finish_reason\":\"stop\"}]}\n\n" +
"data: [DONE]\n\n"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/chat/completions" {
return
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(stream))
}))
t.Cleanup(srv.Close)
rt := newTestRouter(t, baseConfig(config.Endpoint{ID: "a", URL: srv.URL, Models: []string{"m"}}))
rec := sendMessages(t, rt.Handler(), map[string]any{"model": "m", "max_tokens": 10, "stream": true,
"thinking": map[string]any{"type": "enabled", "budget_tokens": 1024},
"messages": []any{map[string]any{"role": "user", "content": "2+2?"}}})
got := rec.Body.String()
for _, s := range []string{`"content_block":{"thinking":"","type":"thinking"},"index":0`,
`"delta":{"thinking":"two ","type":"thinking_delta"}`, `"type":"signature_delta"`,
`"content_block":{"text":"","type":"text"},"index":1`, `"text":"4","type":"text_delta"`} {
if !strings.Contains(got, s) {
t.Errorf("lacks %s in\n%s", s, got)
}
}
if strings.Index(got, "signature_delta") > strings.Index(got, `"text_delta"`) {
t.Error("the thinking block was not closed before the text began")
}
}
+4
View File
@@ -51,6 +51,10 @@ type Router struct {
cfg config.Router
log *slog.Logger
// selfHandler is the client API as Handler built it, key check and all:
// what the MCP tools make their requests through, as the caller.
selfHandler atomic.Pointer[http.Handler]
reg *endpoint.Registry
poller *scrape.Poller
px *proxy.Proxy
+17 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"strings"
"time"
)
@@ -193,13 +194,26 @@ func (s *DB) AllJobs(ctx context.Context, status string, limit int) ([]Job, erro
// ClaimJob takes the lease on the oldest job with work left that no gateway
// holds, for owner until the time given. ok is false when there is none.
func (s *DB) ClaimJob(ctx context.Context, owner string, now, until time.Time) (Job, bool, error) {
//
// Jobs for the models in skip are passed over: a worker running as many of a
// model's jobs as it will at once takes the next job for another model
// rather than waiting behind it.
func (s *DB) ClaimJob(ctx context.Context, owner string, now, until time.Time, skip ...string) (Job, bool, error) {
var id string
args := []any{owner, millis(until), JobQueued, JobRunning, JobCancelling, millis(now)}
notIn := ""
if len(skip) > 0 {
notIn = " AND model NOT IN (?" + strings.Repeat(", ?", len(skip)-1) + ")"
for _, m := range skip {
args = append(args, m)
}
}
args = append(args, millis(now))
err := s.db.QueryRowContext(ctx, `UPDATE jobs SET lease_owner = ?, lease_until = ?
WHERE id = (SELECT id FROM jobs WHERE status IN (?, ?, ?) AND lease_until < ?
WHERE id = (SELECT id FROM jobs WHERE status IN (?, ?, ?) AND lease_until < ?`+notIn+`
ORDER BY created_at LIMIT 1)
AND lease_until < ?
RETURNING id`, owner, millis(until), JobQueued, JobRunning, JobCancelling, millis(now), millis(now)).Scan(&id)
RETURNING id`, args...).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return Job{}, false, nil
}
+21
View File
@@ -120,3 +120,24 @@ func TestAnOperatorSeesEveryOwnersJobs(t *testing.T) {
t.Errorf("%d queued", len(queued))
}
}
func TestAClaimPassesOverTheModelsItIsToldTo(t *testing.T) {
db := openDB(t)
ctx := t.Context()
now := time.Now()
for i, m := range []string{"sf3d", "flux"} {
at := now.Add(time.Duration(i) * time.Second)
if err := db.PutJob(ctx, Job{ID: "job_" + m, Owner: "u", KeyID: "k", Endpoint: "/e", Model: m, Input: []byte("{}"),
Status: JobQueued, CreatedAt: at, ExpiresAt: at.Add(time.Hour)}); err != nil {
t.Fatal(err)
}
}
j, ok, err := db.ClaimJob(ctx, "w", now, now.Add(time.Minute), "sf3d")
if err != nil || !ok || j.Model != "flux" {
t.Errorf("claimed %+v %v %v; sf3d was to be passed over", j.ID, ok, err)
}
j, ok, _ = db.ClaimJob(ctx, "w", now, now.Add(time.Minute))
if !ok || j.Model != "sf3d" {
t.Errorf("then %+v %v", j.ID, ok)
}
}
+4 -4
View File
@@ -239,14 +239,14 @@ func TestThePageReloadsOnlyWhileSomethingIsDownloading(t *testing.T) {
// A reload while nothing is happening would take with it whatever the
// operator was typing into the fetch form.
if strings.Contains(idle, "http-equiv=\"refresh\"") {
if strings.Contains(idle, "name=\"llmgw-refresh\"") {
t.Error("an idle page should not reload itself")
}
busy := mirrorGet(t, mirrorPage(t, &fakeMirror{models: []mirror.Status{
{Model: "m", Version: "v", File: "f", State: mirror.Fetching},
}}, true), "/admin/mirror").Body.String()
if !strings.Contains(busy, "http-equiv=\"refresh\"") {
if !strings.Contains(busy, "name=\"llmgw-refresh\"") {
t.Error("a page with a download running should follow it")
}
}
@@ -680,7 +680,7 @@ func TestEachTabDoesOnlyItsOwnWork(t *testing.T) {
if strings.Contains(held, `name="source" required`) || strings.Contains(held, "Search Hugging Face") {
t.Error("other tabs' forms are on the list")
}
if !strings.Contains(held, `http-equiv="refresh"`) {
if !strings.Contains(held, `name="llmgw-refresh"`) {
t.Error("the list stopped following a download")
}
@@ -688,7 +688,7 @@ func TestEachTabDoesOnlyItsOwnWork(t *testing.T) {
if reg.explored != 1 || !strings.Contains(explore, "Search Hugging Face") {
t.Error("the explorer tab did not explore")
}
if strings.Contains(explore, `id="held"`) || strings.Contains(explore, `http-equiv="refresh"`) {
if strings.Contains(explore, `id="held"`) || strings.Contains(explore, `name="llmgw-refresh"`) {
t.Error("the explorer shows the list, or reloads away a search")
}
// A link from before there were tabs still lands on the explorer.
+1 -1
View File
@@ -92,7 +92,7 @@ func TestAHeldModelOpensToWhereItRunsAndHowMuchRoomIsLeft(t *testing.T) {
if strings.Contains(body, "secret-engine-key") {
t.Error("the engine's key reached the page")
}
if strings.Contains(body, `http-equiv="refresh"`) {
if strings.Contains(body, `name="llmgw-refresh"`) {
t.Error("a page with an open form reloads under the operator")
}
}
+41 -2
View File
@@ -18,11 +18,50 @@
var msg = e.target.getAttribute && e.target.getAttribute('data-confirm');
if (msg && !window.confirm(msg)) { e.preventDefault(); }
});
// A form being filled in is not refreshed away. The live parts of the
// cluster and node pages are swapped whole every few seconds, and a form
// inside one lost what was typed into it, its open choice, its focus:
// filling one in raced the clock. While a field in the refreshing part
// has the focus, or a form in it has been typed into and not sent, it
// waits; sending the form, or leaving the page, ends that.
var edited = [];
document.addEventListener('input', function (e) {
var f = e.target.form || (e.target.closest && e.target.closest('form'));
if (f && edited.indexOf(f) < 0) { edited.push(f); }
});
document.addEventListener('submit', function (e) {
if (!e.defaultPrevented) { edited = []; }
});
function busy(root) {
var a = document.activeElement;
if (a && a !== document.body && root.contains(a) &&
a.matches('input, select, textarea, [contenteditable]')) {
return true;
}
for (var i = 0; i < edited.length; i++) {
if (root.contains(edited[i]) && document.contains(edited[i])) { return true; }
}
return false;
}
// htmx's trigger filters are evaluated JavaScript; this is the same
// "only while visible" without them.
// "only while visible" without them, and "not while being filled in".
document.addEventListener('htmx:beforeRequest', function (e) {
if (document.visibilityState !== 'visible' && e.detail.elt.hasAttribute('data-visible-only')) {
var elt = e.detail.elt;
if (elt.hasAttribute('data-visible-only') &&
(document.visibilityState !== 'visible' || busy(elt))) {
e.preventDefault();
}
});
// A page that reloads itself (<meta name="llmgw-refresh" content="N">)
// does it on the same terms, rather than by http-equiv, which nothing
// can hold off.
var r = document.querySelector('meta[name="llmgw-refresh"]');
var every = r ? parseInt(r.getAttribute('content'), 10) : 0;
if (every > 0) {
setInterval(function () {
if (document.visibilityState === 'visible' && !busy(document.body)) {
window.location.reload();
}
}, every * 1000);
}
})();
+4 -4
View File
@@ -1,10 +1,10 @@
{{define "admin_mirror"}}<!doctype html>
<html lang="{{lang}}"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
{{/* Only while something is downloading. A reload at any other time would
take with it whatever the operator was typing into the form below. */}}
{{if .RefreshSec}}<meta http-equiv="refresh" content="{{.RefreshSec}}">{{end}}
<script defer src="/_static/pages.js"></script>
{{/* Only while something is downloading, and not while a form is being
filled in: pages.js holds the reload off then. */}}
{{if .RefreshSec}}<meta name="llmgw-refresh" content="{{.RefreshSec}}">{{end}}
<script defer src="{{asset "pages.js"}}"></script>
<title>{{t "mirror.title"}} · llmgw</title><link rel="stylesheet" href="{{stylesheet}}">
</head><body><div class="wrap">
<header>
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="stylesheet" href="/_static/katex/katex.min.css">
<script defer src="/_static/katex/katex.min.js"></script>
<script defer src="/_static/katex/auto-render.min.js"></script>
<script defer src="/_static/pages.js"></script>
<script defer src="{{asset "pages.js"}}"></script>
<meta name="csrf" content="{{.CSRF}}">
<meta name="chat-owner" content="{{.User.ID}}">
</head><body><div class="wrap">
+1 -1
View File
@@ -4,7 +4,7 @@
<noscript>{{.RefreshMeta}}</noscript>
<meta name="htmx-config" content='{"allowEval":false}'>
<script src="/_static/htmx-2.0.11.min.js"></script>
<script defer src="/_static/pages.js"></script>
<script defer src="{{asset "pages.js"}}"></script>
<title>llmgw — {{t "dash.title"}}</title><link rel="stylesheet" href="{{stylesheet}}">
</head><body><div class="wrap">
<header>
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="{{lang}}"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{t "images.title"}} · llmgw</title><link rel="stylesheet" href="{{stylesheet}}">
<script defer src="/_static/pages.js"></script>
<script defer src="{{asset "pages.js"}}"></script>
<meta name="csrf" content="{{.CSRF}}">
</head><body><div class="wrap">
<header>
+1 -1
View File
@@ -4,7 +4,7 @@
<noscript>{{.RefreshMeta}}</noscript>
<meta name="htmx-config" content='{"allowEval":false}'>
<script src="/_static/htmx-2.0.11.min.js"></script>
<script defer src="/_static/pages.js"></script>
<script defer src="{{asset "pages.js"}}"></script>
<title>llmgw — {{.Node.ID}}</title><link rel="stylesheet" href="{{stylesheet}}">
</head><body><div class="wrap">
<header>