Skip to content

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_generate or train_start stops the LLM engine, and it restarts on the next chat request.

agent harness (pi)GPU proxy :11434GPU services (one active)storageMCP clientcomfyui_generatecomfyui_statuscomfyui_historytrain_start / train_status train_logs / train_canceltrain_list / train_datasetstrain_deployschedulerone workload at a timeMCP stdio -> /comfyui/*MCP stdio -> /train/*ComfyUI :8188generationmode comfyuilora-train :8787kohya sd-scriptsmode trainLLM engine :8080(not covered here)mode llm(default)output storeimages + LoRAswrites imagesdataset storeimage/caption pairsreadswrites LoRAs

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.


ToolWhat it doesWhen the agent calls it
comfyui_generateSubmits 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_statusReports 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_historyReturns 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.

DefaultValueNote
Checkpointsd_xl_base_1.0.safetensorsSwapped per generation for Illustrious, Flux or custom checkpoints.
Dimensions832 x 1216 (portrait)Other SDXL ratios in the tool description: 1024x1024, 1216x832, 768x1344.
Steps30Tool default.
SamplerEulerTool default.
CFG5Tool default.
Positive prefixmasterpiece, best qualityThe tool description tells the agent to prefix prompts with quality tags.

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 settingValue
Model chainUNETLoader -> QwenImage21Cache -> KSampler -> VAEDecode -> SaveImage
Text encodingCLIPLoader (type qwen_image) -> TextEncodeQwenImage21
Sampler25 steps, euler, simple scheduler, CFG 1
Promptone flattened prose paragraph, not JSON
Timeabout 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.

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.

ToolWhat it doesWhen the agent calls it
train_startStarts 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_statusReports 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_logsReturns the last N lines of training output.The agent needs the raw loss curve or error text.
train_cancelKills the current training job.The user changes their mind, or the loss has diverged.
train_listLists completed LoRA files with sizes.Before deploying, or the user asks what has been trained.
train_datasetsLists 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_deployCopies 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.


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.

ParameterSDXL (Illustrious / NoobAI / Pony)SDXL (JuggernautXL / photo-realistic)Flux (flux1-dev)Source of the choice
LoRA rank (network_dim)323216train/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.
Alpha32 (equal to rank, scale 1.0)3216Alpha equals rank in both families.
Epochs448 (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 skip21not passedThe 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) basen/an/atruetrain/server.py: required for Flux 12B on 32 GB VRAM.
T5 attention maskn/an/atruekohya-recommended; keeps T5 padding tokens out of attention; no VRAM cost (train/server.py comment).
OptimizerAdamWAdamWAdamW8bittrain/server.py: AdamW8bit is kohya’s recommendation for Flux. Cosine schedule and 100 warmup steps in both.
Learning rate1e-41e-41e-4Single learning_rate default; both builders pass --network_train_unet_only, so only the UNet is trained.
Gradient checkpointingtruetruetrueDefault in both builders.
Batch size224Set 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-parameterisationfalse (true for NoobAI-v-pred)falsen/av_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.

EngineOutputModel familyStated reason
BLIP-2Natural-language sentences, roughly 1 image/s on 32 GB VRAMFluxFlux encodes prompts through T5-XXL, so natural-language captions align with it (skill, caption_start description).
WD14Danbooru tags, comma-separated (e.g. 1girl, solo, looking at viewer, smile)SDXL / IllustriousDanbooru 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 = false
caption_extension = ".txt"
keep_tokens = 0
[[datasets]]
resolution = 1024
batch_size = 2
enable_bucket = true
[[datasets.subsets]]
image_dir = "/data/datasets/my-dataset"
num_repeats = 1

The agent runs three steps before train_start.

  1. Audit checks the raw image set and, with --expected tags, missing WD14 tags for an anime dataset. It returns counts and a rejection list.
  2. Filter copies images whose stems are not on the rejection list into a clean directory. The raw set is kept.
  3. Caption runs the chosen engine (BLIP-2 or WD14) over the clean directory, one .txt file 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.


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.


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.

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.

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.

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.

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.


The tool shapes and MCP wiring are specific to this harness and its proxy.

  1. Return file paths for generated images. One base64 PNG exceeds the input limit of the model used here.
  2. 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.
  3. 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.
  4. Audit before caption and caption before train, so a bad image costs a filter step rather than a training run.
  5. Deploy is an explicit step when trainer output and generator input are separate trees.
  6. 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.
  7. Check the VRAM (video random-access memory) budget before the run. Flux needs fp8 base on 32 GB (train/server.py).

Agent needs toproduce an imageor train a LoRATraining orgeneration?GPU locked byan unattendedloop?generationDataset alreadycaptioned?trainingFlux or SDXLbase model?Flux: dim=16, alpha=16,fp8_base=true, epochs=8,caption with BLIP-2FluxSDXL: dim=32, alpha=32,clip_skip=2 (anime) or 1 (photo),epochs=4, caption with WD14SDXLcomfyui_generatewith prompt + checkpoint.Never read the output PNG.noWait, or ask userif the lock shouldbe releasedyesyesAudit, filter,caption first.BLIP-2 for Flux,WD14 for SDXL.notrain_deploy toComfyUI models/loras/, thengenerate with a LoraLoader nodeafter trainingafter training
  1. For generation: call comfyui_generate with 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.
  2. 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.
  3. If the dataset has no captions, audit, filter and caption it first - BLIP-2 for Flux, WD14 for SDXL.
  4. After training, run train_deploy to copy the LoRA to ComfyUI’s model tree. Then it is available in generation workflows through a LoraLoader node.

ClaimHow it was checkedStatus
comfyui_generate tool shape: prompt, negative_prompt, dimensions, steps, cfg, seed, checkpoint, workflow overridescomfyui-server.py tool description and tool_generate function, 2026-10-20read from source
Default workflow: CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImagecomfyui-server.py DEFAULT_WORKFLOW dict, 2026-10-20read from source
Default checkpoint sd_xl_base_1.0.safetensors, 832x1216, 30 steps, Euler, CFG 5comfyui-server.py DEFAULT_CHECKPOINT etc., 2026-10-20read from source
Agent must not read generated PNG - base64 exceeds input limittool description in comfyui-server.py, 2026-10-20read from source
train_start tool and its seven-training-tool surfacetrain-server.py MCP schema and tool_* functions, 2026-10-20read from source
SDXL defaults: dim=32, alpha=32, clip_skip=2 or 1, epochs=4lora-train skill SKILL.md, 2026-10-20; train/server.py _common_config, 2026-10-31read from source
Both builders pass --network_train_unet_only; text_encoder_lr is in the MCP schema but unusedtrain/server.py _build_sdxl_command, _build_flux_command; rg text_encoder_lr finds it only in mcp/train-server.py, 2026-10-31read from source
Flux optimizer AdamW8bit, SDXL AdamW, cosine schedule, 100 warmup stepstrain/server.py _common_config and _build_flux_command, 2026-10-31read from source
Flux defaults: dim=16, alpha=16, fp8_base=true, apply_t5_attn_mask=true, epochs=8lora-train skill SKILL.md, 2026-10-20read 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-20read from source
BLIP-2 recommended for Flux (aligns with T5-XXL), WD14 for SDXL/animelora-train skill SKILL.md captioning section, 2026-10-20read from source
BLIP-2 at ~1 image/s on 32 GB VRAMlora-train skill SKILL.md, 2026-10-20read from source
Florence-2 marked broken on transformers >= 4.54mcp/train-server.py caption_start tool description, 2026-10-20read from source
Captioning workflow: audit, filter, caption (llmc dataset subcommands)lora-train skill SKILL.md, 2026-10-20read 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-20read from source
TOML dataset config shape: resolution, batch_size, enable_bucket, subsetslora-train skill SKILL.md, 2026-10-20read 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-20design-read
ComfyUI v0.44.2, FLUX 3 Image Klein weights, llmc concept runner, images on ghcr.iollmc, 2026-11-07; concept/run.py; llmc docs/research/2026-11-07-concept-ab.md, 2026-11-07read from source; A/B measured, n=40, one labeller
ComfyUI model store archived to NAS on 2026-09-26comfyui skill SKILL.md, 2026-10-20read from source
Flux fp8_base defaults to true because Flux 12B needs it on 32 GBtrain/server.py _build_flux_command docstring and fp8_base = config.get("fp8_base", True), re-read 2026-10-31read 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 startllmc-single-gpu-stack.mdx swap section, 2026-10-20design-read