Fine-Tuning a 7B Human-in-the-Loop Tool-Calling Model & Multi-LoRA Engine for Workloop
Training Qwen2.5-7B-Instruct with QLoRA on an NVIDIA L4, enforcing 6 HITL tools, debugging Unsloth's inference token-duplication bug, serving 3 adapters on one base model, and confronting the honest Held-Out (97.81%) vs OOD (89.47%) gap.
In Part 1, I covered how Workloop turns chaotic stakeholder meetings and coding-agent loops into a structured workspace backed by 66 endpoints, fail-closed portals, and an interactive Human-in-the-Loop (HITL) AI drawer.
Workloop already supports Bring Your Own Key (BYOK) providers out of the box. Still, just like when I built Kosera SPK AI Service, stopping at commercial API wrappers misses half the reason I build these projects: I wanted to understand model fine-tuning, tool-calling failure modes, and multi-adapter serving end to end, and craft a dedicated model tailored specifically for bilingual Indonesian/English Workloop briefs without owning local GPU hardware.
The guiding rule from day one remained strict: fine-tune for behavior, never for memorization. Task titles, live counts, and deadlines live in PostgreSQL; QLoRA teaches the model when to invoke tools, how to extract structured parameters in Asia/Jakarta (+07:00), when to reject ambiguity or out-of-scope requests honestly, and never to claim a database mutation happened before human confirmation.
1. The 6-Tool Human-in-the-Loop Safety Contract
Giving an autonomous 7B model direct INSERT or DELETE power over real project state is asking for silent data corruption—especially on messy client notes where "geser ke besok sore" might apply to one task or three.
In configs/tool_schemas.json, workloop-ai-service splits six Hermes-format functions into two strict safety tiers:
| Tool Name | Tier | Execution Behavior | Primary Purpose |
|---|---|---|---|
listTasks | Read | Executed immediately | Filter active tasks by project, status, priority, tags, due range, or keyword |
getTaskRevisionHistory | Read | Executed immediately | Fetch versioned revision rounds (v1, v2, ...) and checklists |
getWorkloadSummary | Read | Executed immediately | Aggregate overdue, due, review, revision-needed, and completed counts |
proposeTaskFromBrief | Write-Draft | Returns editable Confirmation Card | Turn raw meeting/chat notes into a structured task draft; never writes to DB |
proposeRevisionItems | Write-Draft | Returns editable Confirmation Card | Convert unstructured stakeholder feedback into atomic revision checklist items |
draftReviewMessage | Write-Draft | Returns editable Confirmation Card | Compose a WhatsApp or Email review message with deliverable version & link context |
Even when all arguments look clear, write tools always stop at a Draft Confirmation Card inside Workloop's SSE drawer so the human owner remains the final write gate.
2. Dataset Engineering & QLoRA Training on NVIDIA L4
Instead of training on loose single-turn QA pairs, datasets/sft_v1/ contains 750 validated, leakage-free multi-turn conversations split 630 train / 60 val / 60 test (fixed seed = 42, UTC+7 Asia/Jakarta) across 9 behavioral categories—including brief extraction, revision parsing, read lookups, empty-result honesty, ambiguous-reference clarification, and prompt-injection/out-of-scope refusals.
Training ran on a single NVIDIA L4 GPU in Colab using Qwen/Qwen2.5-7B-Instruct with 4-bit QLoRA (r = 16, lora_alpha = 32, lr = 1e-4, warmup_ratio = 0.05, MAX_SEQ_LENGTH = 4096, 2 epochs) via Unsloth + TRL SFTTrainer with train_on_responses_only masking user and tool-output turns out of the loss:
- Total training time:
58.53 minutes - Best validation checkpoint:
checkpoint-80 - Best eval loss:
0.1317(0.13167248666286469)

The Qwen2.5 tool_calls.arguments Template Gotcha
One subtle bug caught early in dataset validation and serving inside server/protocol.py (normalize_messages_for_qwen): Qwen2.5's Jinja chat template applies the | tojson filter directly to tool_calls[].function.arguments.
If conversation history passes arguments as an already-serialized JSON string (as returned verbatim by many OpenAI SDK wrappers), the template double-escapes the JSON string ("{\"query\": ...}"), silently corrupting multi-turn tool context between training and inference. Normalizing stringified arguments back into Python dict objects before calling apply_chat_template kept training and serving token streams identical.
3. Catching the Unsloth Inference Token-Duplication Bug
Unsloth delivered major VRAM and speed wins during Phase 4 training, making 58.5-minute runs practical on an L4. However, running Phase 5 evaluation directly through Unsloth's fast inference path uncovered token-duplication glitches during structured generation.
Had those numbers gone unchecked, benchmark scores would have confounded true model mistakes with runtime artifacts—and streamed <tool_call> blocks in production could stutter mid-JSON.
The fix was separating training kernels from serving engines:
- Training: Keep Unsloth + TRL for fast 4-bit QLoRA convergence.
- Evaluation & Serving: Load the canonical
Qwen/Qwen2.5-7B-Instructbase model with standard Hugging Facetransformers+peftfor reproducible Phase 5 evaluation, and persistent vLLM (--tool-call-parser hermes) in GPU serving. Result:duplication_glitch_ratedropped cleanly to0.0%across every held-out and OOD probe.
4. Multi-LoRA Serving (3 Adapters / 1 Base Model) & SSE Prefix Filtering
Because keeping adapters unmerged (no merge_and_unload()) preserves lightweight ~16-rank deltas on disk, a single Qwen2.5-7B-Instruct weight matrix in GPU VRAM can serve multiple unrelated products concurrently by routing per-request model names:
Incoming OpenAI-Compatible Chat Request (model = "workloop" | "kosera" | "portfolio")
|
v
Shared Base Model in GPU VRAM (Qwen/Qwen2.5-7B-Instruct, dtype=bfloat16)
|-- model="workloop" -> adapters/workloop (6 HITL project & revision tools)
|-- model="kosera" -> adapters/kosera (Semantic + Profile Matching SPK tools)
|-- model="portfolio" -> adapters/portfolio (Portfolio assistant adapter slot)
|
+---> FastAPI + SSE (ToolCallPrefixFilter) OR persistent vLLM (--enable-lora --tool-call-parser hermes)
In persistent GPU deployments, deploy/vllm_multilora_launch.sh boots one vLLM process capable of hot-swapping up to four LoRA adapters without duplicating 7B base weights across separate containers:
exec python3 -m vllm.entrypoints.openai.api_server \
--model "${BASE_MODEL_ID}" \
--host "${HOST}" \
--port "${PORT}" \
--dtype "${DTYPE}" \
--max-model-len "${MAX_MODEL_LEN}" \
--gpu-memory-utilization "${GPU_MEMORY_UTILIZATION}" \
--enable-lora \
--max-loras "${MAX_LORAS}" \
--max-lora-rank "${MAX_LORA_RANK}" \
--lora-modules "${LORA_MODULES[@]}" \
--enable-auto-tool-choice \
--tool-call-parser hermes \
"${EXTRA_ARGS[@]}"
For lightweight single-instance Colab or FastAPI hosting (server/chat_app.py), streaming prose token-by-token introduces another UX hazard: if the model emits <tool_call>{...}</tool_call>, flushing initial tokens straight to the UI flickers raw XML tags in front of the user. ToolCallPrefixFilter in server/protocol.py solves this as a deterministic three-state prefix machine (detecting -> text or tool_call):
class ToolCallPrefixFilter:
"""Stream-prefix state machine that suppresses `<tool_call>` XML during SSE streaming."""
def __init__(self) -> None:
self.mode: Literal["detecting", "text", "tool_call"] = "detecting"
self._pending_buffer = ""
def push(self, chunk: str) -> list[str]:
if not chunk:
return []
if self.mode == "text":
return [chunk]
if self.mode == "tool_call":
return []
self._pending_buffer += chunk
stripped = self._pending_buffer.lstrip()
if not stripped:
return []
if stripped.startswith(TOOL_PREFIX_TRIGGER):
self.mode = "tool_call"
self._pending_buffer = ""
return []
if TOOL_PREFIX_TRIGGER.startswith(stripped):
return []
self.mode = "text"
flushed = self._pending_buffer
self._pending_buffer = ""
return [flushed]
If prose starts naturally, detecting locks into text on the first non-matching character and streams immediately with zero extra latency. If <tool_call> begins arriving, it suppresses XML emission, parses completed JSON blocks cleanly at EOF into structured tool events, and falls back safely if an output contains malformed XML.
5. Held-Out Benchmark vs Honest OOD Reality Check
Phase 5 evaluated the base Qwen2.5-7B-Instruct model against the workloop QLoRA adapter on 137 held-out test probes (outputs-phase-5-hf/phase5_comparison_report.json) across all KPI gates:

| Held-Out Metric (137 Probes) | Base Qwen2.5-7B | Workloop QLoRA | Delta |
|---|---|---|---|
| Overall Pass Rate | 60.58% | 97.81% | +37.23% |
Tool-Call Validity (>= 98% gate) | 77.92% | 100.00% | +22.08% |
Parameter Extraction Accuracy (>= 93% gate) | 83.39% | 98.89% | +15.50% |
Groundedness Rate (100% gate) | 91.97% | 100.00% | +8.03% |
Ambiguity & Empty Honesty (100% gate) | 80.00% | 100.00% | +20.00% |
Prompt Injection / Refusal Rate (100% gate) | 66.67% | 100.00% | +33.33% |
Duplication Glitch Rate (0% gate) | 0.00% | 0.00% | 0.00% |
Passing 100% of held-out KPI gates looks impressive on paper—which is precisely why testing out-of-distribution (OOD) inputs matters. I ran a second evaluation (outputs-phase-5-hf/phase5_ood_comparison_report.json) on 26 completely unseen, messy WhatsApp-style Indonesian/English prompts filled with informal shortcuts, relative dates, and implicit requester references:
| Unseen OOD Metric (26 Prompts) | Base Qwen2.5-7B (OOD) | Workloop QLoRA (OOD) | Delta |
|---|---|---|---|
| Tool-Call Validity (19 tool prompts) | 78.95% | 89.47% | +10.52% |
| Parameter Extraction Accuracy | 68.52% | 70.37% | +1.85% |
| Groundedness Rate | 92.31% | 96.15% | +3.84% |
| Empty Honesty Rate | 50.00% | 100.00% | +50.00% |
| Refusal Rate | 50.00% | 100.00% | +50.00% |
| Duplication Glitch Rate | 0.00% | 0.00% | 0.00% |
| Avg Latency per Prompt | 9.38s | 8.51s | -0.87s |
The honest contrast between 98.89% held-out parameter extraction and 70.37% OOD parameter extraction tells the real engineering story: SFT v1 mastered Workloop's behavioral guardrails (100% OOD empty honesty and refusals, +10.52% tool validity, 0% glitches), yet messy real-world date idioms and implicit stakeholder hints outside the synthetic training distribution still slip arguments roughly three out of ten times.
Had I relied solely on synthetic test splits, that generalization blind spot would have gone unnoticed until users complained.
6. Closing the Loop: The ai_feedback -> sft_v2 Flywheel
Notice how cleanly Part 1's UX safeguards connect to Part 2's OOD bottleneck: Draft Confirmation Cards generate labeled preference data automatically during normal work.
Every time Workloop renders a proposeTaskFromBrief, proposeRevisionItems, or draftReviewMessage card and the user corrects a due date, project assignment, or requester name before hitting confirm, POST /api/v1/ai/feedback persists the raw turn alongside the human-corrected arguments in PostgreSQL.
scripts/export_feedback_to_sft.py then completes the flywheel:
- Pulls verified
ai_feedbackrows directly from PostgreSQL (or offline JSONL snapshots). - Scrubs sensitive PII/credentials (
wl_live_*keys, Bearer/JWT secrets, emails, share tokens/p/*&/r/*, Indonesian phone numbers) while preserving non-PII enums, ISO+07:00timestamps, and IDs. - Reconstructs clean multi-turn Qwen2.5 records with
dict-typedtool_calls[].function.argumentsvalidated againstconfigs/tool_schemas.jsonfordatasets/sft_v2/.
Instead of endlessly guessing new synthetic templates, future LoRA iterations train directly on real colloquial edge cases corrected in production.
Explore the Code & Live Workspace
- Live Web App (Zero-Config Preview Mode): workloop.my.id
- Workloop AI Service (Datasets, QLoRA, Evals, Multi-LoRA Server): github.com/rizalkr/workloop-ai-service
- Workloop Full-Stack App (Next.js 15, Drizzle, R2, HITL UI): github.com/rizalkr/workloop
- Previous Chapter: Part 1: Why I Built Workloop