Agents and LLMsModels and local inferencereference
Agent image generation and LoRA training
One workstation exposes image generation and LoRA training to its coding agent as MCP (Model Context Protocol) tools: a ComfyUI server for generation, a kohya sd-scripts container for training, and a mode-switching proxy that owns the GPU (graphics processing unit) and runs one workload at a time. The agent can prompt, audit, caption, train and deploy without leaving the harness.
The setup is the single-GPU stack covered in Scheduling one GPU between LLM (large language model), image and training work. Tool shapes and defaults below are read from the MCP server source and the skill files as of 2026-10-20; the trainer command builders were re-read on 2026-10-31. Incident notes come from session history and carry their dates. No figure on this page was measured for it; the throughput numbers behind the GPU-sharing rules are on the bench page.
TL;DR:
- Three ComfyUI tools (
comfyui_generate,comfyui_status,comfyui_history) and seven training tools (train_start,train_status,train_logs,train_cancel,train_list,train_datasets,train_deploy). - The agent never reads a generated image back into context: the base64 inline of one output PNG (Portable Network Graphics) exceeds the model’s input limit, so the tools return file paths.
- SDXL (Stable Diffusion XL) training: rank 32, alpha 32, clip skip 2 for anime bases and 1 for photo-realistic ones, 4 epochs. Flux: rank 16, alpha 16, fp8 base, T5 attention mask, 8 epochs for face LoRAs.
- Captions: BLIP-2 (natural language) for Flux, WD14 (Danbooru tags) for SDXL and anime bases.
- Generation and training run through the GPU proxy: one workload at a time.
comfyui_generateortrain_startstops the LLM engine, and it restarts on the next chat request.
Topology
Section titled “Topology”The harness loads two MCP servers, comfyui and lora-train, as stdio Python processes that talk to the GPU proxy at localhost:11434. On a comfyui_generate or train_start call the proxy drains in-flight LLM requests, stops the LLM engine, starts the target service and forwards the call.
Generated PNGs land in a shared output directory. Trained .safetensors files land in a training output directory and are copied to ComfyUI’s LoRA directory by train_deploy. The trainer container mounts the dataset store read-only.
Which tool for what
Section titled “Which tool for what”Generation
Section titled “Generation”| Tool | What it does | When the agent calls it |
|---|---|---|
comfyui_generate | Submits a txt2img workflow and waits for the output PNG. The prompt, negative prompt, dimensions, steps, CFG, seed and checkpoint are all overridable; a full ComfyUI workflow JSON can be passed instead. | The user asks for an image, or a workflow step needs one. |
comfyui_status | Reports the GPU mode, the ComfyUI queue state, and whether a swap is in progress. | Before generation, to confirm the GPU is not locked by an unattended loop. |
comfyui_history | Returns output file paths and metadata for recent generations, or for one by its prompt id. | The user asks what was generated earlier in the session. |
The default workflow is a minimal txt2img graph: CheckpointLoaderSimple -> CLIPTextEncode (positive + negative) -> KSampler -> VAEDecode -> SaveImage. Every parameter has a built-in default, and a local config file (comfyui.local.env) can override them per machine.
| Default | Value | Note |
|---|---|---|
| Checkpoint | sd_xl_base_1.0.safetensors | Swapped per generation for Illustrious, Flux or custom checkpoints. |
| Dimensions | 832 x 1216 (portrait) | Other SDXL ratios in the tool description: 1024x1024, 1216x832, 768x1344. |
| Steps | 30 | Tool default. |
| Sampler | Euler | Tool default. |
| CFG | 5 | Tool default. |
| Positive prefix | masterpiece, best quality | The tool description tells the agent to prefix prompts with quality tags. |
Qwen-Image-2.1
Section titled “Qwen-Image-2.1”Qwen-Image-2.1 runs on this ComfyUI from the 2026-09-29 bump to v0.37.0 (v0.44.2 since 2026-11-07), with int8 weights in the ComfyUI models volume. It does not fit the default graph: it loads through UNETLoader and encodes through its own text-encoder node, so the agent passes a full workflow JSON (JavaScript Object Notation) to comfyui_generate instead of a checkpoint name. The working graph is the official image_qwen_image_2_1_t2i template from Comfy-Org’s workflow templates.
| Node or setting | Value |
|---|---|
| Model chain | UNETLoader -> QwenImage21Cache -> KSampler -> VAEDecode -> SaveImage |
| Text encoding | CLIPLoader (type qwen_image) -> TextEncodeQwenImage21 |
| Sampler | 25 steps, euler, simple scheduler, CFG 1 |
| Prompt | one flattened prose paragraph, not JSON |
| Time | about 40 s warm for a 1088x1920 vertical |
The container image needs the newer ComfyUI. Until 2026-10-08 the published image of this stack still carried ComfyUI 0.19.5, so a fresh pull produced a ComfyUI without TextEncodeQwenImage21 and the workflow failed on an unknown node; rebuilding the image locally fixed it, and the published image has been current since. Check the node list (/object_info) before blaming the workflow. The images moved from Docker Hub to ghcr.io on 2026-11-07; the Docker Hub tags are frozen.
FLUX 3 Image Klein and the concept runner
Section titled “FLUX 3 Image Klein and the concept runner”Since 2026-11-07 the same ComfyUI also runs FLUX 3 Image Klein (distilled: 16 steps, CFG (classifier-free guidance) 1; base: 50 steps, CFG 4), which needs ComfyUI 0.41 or later. Its licence allows commercial use under a revenue cap, unlike Qwen-Image-2.1’s research licence. For design concepts there is a batch runner, llmc concept run BRIEFS.toml --models qwen21,klein: it renders every brief, model and seed in one GPU session, runs tesseract on the CPU (central processing unit) against the strings each brief must contain, optionally swaps once to a vision model that transcribes the text of every image, and writes a labelled contact sheet.
The first run (40 images, hand-labelled by one reviewer) found that asking the vision model “is the text correct?” passed misspellings such as BOOOT0 and GRIDGLE. Having it transcribe the text and checking the spelling in code agreed with the labels on 36 of 40 images, with no correct image failed and four bad ones passed, so the result is a filter and a person still picks from the sheet. On those briefs, which had been written against Qwen, Qwen spelled the text correctly in 13 of 20 images and Klein in 8, and Klein was faster per image.
The agent never reads the output PNG. The MCP server returns local file paths and the user views the image in their own viewer. If the agent calls read on a generated PNG, the base64 inline exceeds the model’s input limit and the turn fails with “Input is too long”. The rule is in the comfyui_generate tool description, so every model sees it on every call.
Training
Section titled “Training”| Tool | What it does | When the agent calls it |
|---|---|---|
train_start | Starts a kohya sd-scripts training job with the given dataset config, base model, and hyperparameters. Returns the effective config and a warning that the LLM backend is stopped. | The user asks to train a LoRA on a prepared dataset. |
train_status | Reports state (training/completed/failed/idle), step count, loss, epoch, elapsed and ETA. | The agent polls progress, or the user asks how the run is going. |
train_logs | Returns the last N lines of training output. | The agent needs the raw loss curve or error text. |
train_cancel | Kills the current training job. | The user changes their mind, or the loss has diverged. |
train_list | Lists completed LoRA files with sizes. | Before deploying, or the user asks what has been trained. |
train_datasets | Lists available datasets under the trainer’s data root. | The user asks what can be trained on, or the agent is about to start a run. |
train_deploy | Copies a trained .safetensors LoRA from the output directory to ComfyUI’s models/loras/. | After training completes, so the LoRA is available in comfyui_generate workflows. |
Training takes 10-60+ minutes. train_start submits the job and returns immediately; train_status polls the training container’s HTTP (Hypertext Transfer Protocol) endpoint. The trainer container wraps kohya sd-scripts with a stdlib Python HTTP server.
SDXL vs Flux training defaults
Section titled “SDXL vs Flux training defaults”model_type is auto-detected from the base_model filename (flux* -> flux, otherwise sdxl), so the agent rarely sets it. Defaults for each type are applied server-side and an explicit parameter overrides them.
| Parameter | SDXL (Illustrious / NoobAI / Pony) | SDXL (JuggernautXL / photo-realistic) | Flux (flux1-dev) | Source of the choice |
|---|---|---|---|---|
LoRA rank (network_dim) | 32 | 32 | 16 | train/server.py docstring: for Flux, rank 32 raises the file from ~150 MB (rank 16) to ~600 MB with no meaningful identity gain on single-subject training. |
| Alpha | 32 (equal to rank, scale 1.0) | 32 | 16 | Alpha equals rank in both families. |
| Epochs | 4 | 4 | 8 (face), 4 (style) | Tool default is 4. The skill sets 8 for Flux. The 8-12 range for face LoRAs is in the train_start description; no style-LoRA measurement is recorded. |
| Clip skip | 2 | 1 | not passed | The anime bases in this stack were trained at clip skip 2 and JuggernautXL at 1 (_build_sdxl_command docstring). A wrong value trains fine and samples wrong (skill). |
| FP8 (8-bit floating point) base | n/a | n/a | true | train/server.py: required for Flux 12B on 32 GB VRAM. |
| T5 attention mask | n/a | n/a | true | kohya-recommended; keeps T5 padding tokens out of attention; no VRAM cost (train/server.py comment). |
| Optimizer | AdamW | AdamW | AdamW8bit | train/server.py: AdamW8bit is kohya’s recommendation for Flux. Cosine schedule and 100 warmup steps in both. |
| Learning rate | 1e-4 | 1e-4 | 1e-4 | Single learning_rate default; both builders pass --network_train_unet_only, so only the UNet is trained. |
| Gradient checkpointing | true | true | true | Default in both builders. |
| Batch size | 2 | 2 | 4 | Set in the dataset TOML, not by the trainer. The skill records SDXL runs at batch 2 and notes Flux at batch 4 takes several hours per run on the 5090. |
| V-parameterisation | false (true for NoobAI-v-pred) | false | n/a | v_parameterization=true adds --v_parameterization --zero_terminal_snr --scale_v_pred_loss_like_noise_pred. |
Both builders train the network only (--network_train_unet_only) and cache text-encoder outputs to disk. The train_start schema still advertises text_encoder_lr (default 5e-5), but train/server.py never reads it, so setting it has no effect (checked 2026-10-31). The earlier version of this page described SDXL as training the text encoder at 5e-5; that was wrong.
The train_start tool’s fp8_base defaults to true for Flux and is ignored for SDXL.
Captioning: matching the engine to the text encoder
Section titled “Captioning: matching the engine to the text encoder”Every image in the dataset needs a caption file beside it. Two engines serve two model families.
| Engine | Output | Model family | Stated reason |
|---|---|---|---|
| BLIP-2 | Natural-language sentences, roughly 1 image/s on 32 GB VRAM | Flux | Flux encodes prompts through T5-XXL, so natural-language captions align with it (skill, caption_start description). |
| WD14 | Danbooru tags, comma-separated (e.g. 1girl, solo, looking at viewer, smile) | SDXL / Illustrious | Danbooru tags are the recommended vocabulary for SDXL and anime bases (skill, caption_start description). |
No test compared a dataset captioned with the “wrong” engine against the right one. The pairing is the skill’s recommendation, not a measurement.
The trigger_word parameter prepends a token to every caption, which keeps the subject token consistent across images. The workflow is three calls: llmc dataset audit <name> checks existing captions (for an anime dataset, that expected WD14 tags are present), llmc dataset filter <src> <dst> copies only good images to a clean directory, and llmc dataset caption <name> runs the chosen engine over the clean set. Captioning is async: the call returns immediately and a status poll tracks progress.
A third engine, Florence-2, is still wired in the server (caption_florence.py), but the MCP tool description marks it broken on transformers >= 4.54. Only BLIP-2 and WD14 are listed.
Dataset prep: the audit-filter-caption pipeline
Section titled “Dataset prep: the audit-filter-caption pipeline”Training data lives as image/caption pairs in named directories under the training data root. Each dataset gets a TOML (Tom’s Obvious, Minimal Language) config with resolution, batch size, bucketing and repeat count:
[general]shuffle_caption = falsecaption_extension = ".txt"keep_tokens = 0
[[datasets]]resolution = 1024batch_size = 2enable_bucket = true
[[datasets.subsets]] image_dir = "/data/datasets/my-dataset" num_repeats = 1The agent runs three steps before train_start.
- Audit checks the raw image set and, with
--expected tags, missing WD14 tags for an anime dataset. It returns counts and a rejection list. - Filter copies images whose stems are not on the rejection list into a clean directory. The raw set is kept.
- Caption runs the chosen engine (BLIP-2 or WD14) over the clean directory, one
.txtfile per image. Existing captions are not overwritten unless asked.
keep_tokens pins the first N caption tokens during shuffle_caption. The skill’s rule is that a dataset with shuffle_caption = true needs keep_tokens = 1 in the train job so the trigger word stays first.
Deploying a trained LoRA
Section titled “Deploying a trained LoRA”After training completes, train_list shows the output files. train_deploy <name> copies the .safetensors file from the training output directory to ComfyUI’s models/loras/ directory. From then on, any comfyui_generate workflow can load it by adding a LoraLoader node that references the filename.
The trainer writes to its own volume and the generator reads from a different model tree, so deploy is an explicit step.
This workstation’s ComfyUI model tree was archived to a NAS (network-attached storage) share on 2026-09-26 and the local directory emptied. The generator fails on a missing checkpoint until the files it needs are restored. The LoRAs went with it (16 of the 45 archived files are under loras/), so a deployed LoRA has to be restored along with the base checkpoint it was trained on.
Coexisting with the LLM on one GPU
Section titled “Coexisting with the LLM on one GPU”The proxy described in Scheduling one GPU between LLM, image and training work owns container lifecycle: one of the LLM engine, ComfyUI or the trainer is active at a time.
Generation (20-60 s)
Section titled “Generation (20-60 s)”comfyui_generate drains in-flight LLM requests, stops the LLM engine, starts ComfyUI and forwards the workflow. Tool calls are synchronous, so the model waits for the result and the proxy restarts the LLM engine on the next chat request.
Training (10-60+ min)
Section titled “Training (10-60+ min)”train_start runs the same sequence, and the LLM backend stays down for the whole run. train_status polls reach the trainer container through the proxy and keep working. The agent cannot call the model until the next chat request restarts the engine.
Lock contention
Section titled “Lock contention”If an unattended loop has pinned the LLM preset with a lock, comfyui_generate and train_start return a 503 “model lock active”. A request for the mode that is already running is granted. Since 2026-10-27 a lock owner can switch modes by sending its owner name in an X-LLM-Lock-Owner header; the MCP servers do not send it, so through these tools a lock means 503. The agent does not unlock without asking: it waits, or asks whether the lock should be released.
Drain deadline
Section titled “Drain deadline”In-flight LLM requests finish before the engine is killed, up to a 60 s grace deadline, so a generation or training call does not interrupt a mid-response turn. Past the deadline the swap proceeds anyway.
A single image is fine inline. A training run is a background task: the agent calls train_start, reports the ETA (estimated time of arrival), and polls train_status on the user’s next prompt.
What carries over to another setup
Section titled “What carries over to another setup”The tool shapes and MCP wiring are specific to this harness and its proxy.
- Return file paths for generated images. One base64 PNG exceeds the input limit of the model used here.
- Training defaults follow the base model: rank, alpha, clip skip, fp8 and the T5 mask differ between SDXL and Flux in the kohya builders read for this page. Another trainer’s defaults need their own check.
- Pair the captioning engine with the text encoder: BLIP-2 for T5-XXL (Flux), WD14 for the SDXL family. This is the skill’s recommendation, untested here.
- Audit before caption and caption before train, so a bad image costs a filter step rather than a training run.
- Deploy is an explicit step when trainer output and generator input are separate trees.
- One GPU means one workload at a time. A 10-60 minute run blocks everything else on the card, so either accept the idle period or add a second GPU.
- Check the VRAM (video random-access memory) budget before the run. Flux needs fp8 base on 32 GB (
train/server.py).
Decision guide
Section titled “Decision guide”- For generation: call
comfyui_generatewith a prompt and an optional checkpoint. Accept the returned file path; never read the PNG back into context. If the GPU is locked by a loop, wait or ask the user. - For training: determine the base model family (Flux or SDXL). Flux: rank 16, alpha 16, fp8 base, 8 epochs, BLIP-2 captions. SDXL: rank 32, alpha 32, clip skip 2 for anime bases or 1 for photo-realistic, 4 epochs, WD14 tags.
- If the dataset has no captions, audit, filter and caption it first - BLIP-2 for Flux, WD14 for SDXL.
- After training, run
train_deployto copy the LoRA to ComfyUI’s model tree. Then it is available in generation workflows through aLoraLoadernode.
Evidence
Section titled “Evidence”| Claim | How it was checked | Status |
|---|---|---|
comfyui_generate tool shape: prompt, negative_prompt, dimensions, steps, cfg, seed, checkpoint, workflow overrides | comfyui-server.py tool description and tool_generate function, 2026-10-20 | read from source |
| Default workflow: CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage | comfyui-server.py DEFAULT_WORKFLOW dict, 2026-10-20 | read from source |
Default checkpoint sd_xl_base_1.0.safetensors, 832x1216, 30 steps, Euler, CFG 5 | comfyui-server.py DEFAULT_CHECKPOINT etc., 2026-10-20 | read from source |
| Agent must not read generated PNG - base64 exceeds input limit | tool description in comfyui-server.py, 2026-10-20 | read from source |
train_start tool and its seven-training-tool surface | train-server.py MCP schema and tool_* functions, 2026-10-20 | read from source |
| SDXL defaults: dim=32, alpha=32, clip_skip=2 or 1, epochs=4 | lora-train skill SKILL.md, 2026-10-20; train/server.py _common_config, 2026-10-31 | read from source |
Both builders pass --network_train_unet_only; text_encoder_lr is in the MCP schema but unused | train/server.py _build_sdxl_command, _build_flux_command; rg text_encoder_lr finds it only in mcp/train-server.py, 2026-10-31 | read from source |
| Flux optimizer AdamW8bit, SDXL AdamW, cosine schedule, 100 warmup steps | train/server.py _common_config and _build_flux_command, 2026-10-31 | read from source |
| Flux defaults: dim=16, alpha=16, fp8_base=true, apply_t5_attn_mask=true, epochs=8 | lora-train skill SKILL.md, 2026-10-20 | read from source |
model_type auto-detected from base_model filename (flux* -> flux, else sdxl) | train-server.py header comment and tool_start implementation, 2026-10-20 | read from source |
| BLIP-2 recommended for Flux (aligns with T5-XXL), WD14 for SDXL/anime | lora-train skill SKILL.md captioning section, 2026-10-20 | read from source |
| BLIP-2 at ~1 image/s on 32 GB VRAM | lora-train skill SKILL.md, 2026-10-20 | read from source |
| Florence-2 marked broken on transformers >= 4.54 | mcp/train-server.py caption_start tool description, 2026-10-20 | read from source |
Captioning workflow: audit, filter, caption (llmc dataset subcommands) | lora-train skill SKILL.md, 2026-10-20 | read from source |
train_deploy copies LoRA from training output to ComfyUI models/loras/ | train-server.py tool_deploy function, lora-train skill SKILL.md, 2026-10-20 | read from source |
| TOML dataset config shape: resolution, batch_size, enable_bucket, subsets | lora-train skill SKILL.md, 2026-10-20 | read from source |
| GPU proxy: one workload at a time, drain-before-swap, 60 s grace, lock TTL (time to live) | llmc-single-gpu-stack.mdx, proxy-go source referenced there, 2026-10-20 | design-read |
ComfyUI v0.44.2, FLUX 3 Image Klein weights, llmc concept runner, images on ghcr.io | llmc, 2026-11-07; concept/run.py; llmc docs/research/2026-11-07-concept-ab.md, 2026-11-07 | read from source; A/B measured, n=40, one labeller |
| ComfyUI model store archived to NAS on 2026-09-26 | comfyui skill SKILL.md, 2026-10-20 | read from source |
Flux fp8_base defaults to true because Flux 12B needs it on 32 GB | train/server.py _build_flux_command docstring and fp8_base = config.get("fp8_base", True), re-read 2026-10-31 | read from source; a full-precision run was not attempted |
| Swap latency: 20-60 s for generation (30-60 s cold), training 30-60 s cold start | llmc-single-gpu-stack.mdx swap section, 2026-10-20 | design-read |
Related docs
Section titled “Related docs”- Scheduling one GPU between LLM, image and training work - the proxy, presets, locks, swap mechanics and what an eviction costs
- Which model runs which agent work - how the harness decides which model serves each request, including vision routing
- The pi harness journey - the extension catalogue these MCP servers plug into
- Subagents, worktrees, and parallel agent work - the background task that wraps a training run
- Benchmarking local models for agent work - throughput numbers that justify the one-workload-at-a-time rule