← All guides AI Release
RU Subscribe to @ai_releaseorg

Step-by-step guide: how to assign GGUF models to roles in llama-runner (Qwen4 for code, GigaChat4 for text)

Updated: 06.12.2026 · AI Release · @ai_releaseorg
Step-by-step guide: how to assign GGUF models to roles in llama-runner (Qwen4 for code, GigaChat4 for text)

🤖 AI summary

Which topics does it cover?
llama-runner несколько моделей, Qwen4 для кода, GigaChat4 локально, распределение GGUF моделей по ролям →

TL;DR

What you will get

Quick start

mkdir -p /opt/llm/models /opt/llm/logs
nohup llama-server -m /opt/llm/models/Qwen4-Code.gguf --alias qwen4-code --host 127.0.0.1 --port 8080 -c 8192 -ngl 99 > /opt/llm/logs/code.log 2>&1 &
nohup llama-server -m /opt/llm/models/GigaChat4-Text.gguf --alias gigachat4-text --host 127.0.0.1 --port 8081 -c 8192 -ngl 99 > /opt/llm/logs/text.log 2>&1 &
pip install flask pyyaml requests && python3 /opt/llm/router.py &

Details and checks are in the steps below. The two file names are placeholders: replace them with the exact GGUF file names published in the Qwen4 and GigaChat4 model cards (see Step 1).

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup

Step 1. Lay out directories and prove each GGUF loads

What to do: create /opt/llm/models and /opt/llm/logs, copy both GGUF files in, then load each file once with llama-cli before you touch any server config.

Why: a truncated download or an unsupported quant fails at load time, and it is far easier to read that failure in a foreground CLI run than in a background server log.

How to check:

ls -lh /opt/llm/models
llama-cli -m /opt/llm/models/Qwen4-Code.gguf -p "def add(a, b):" -n 16 -ngl 99

Example: the second command prints a short completion after def add(a, b): and then a timing summary. Any generated text means the file loads and the chat template is readable. Run the same command with GigaChat4-Text.gguf. If the card publishes several quants, note the exact file name — you need it verbatim in Step 2.

Step 2. Start both servers with role aliases and wire the router

What to do: launch one llama-server per role, each with a distinct port and a distinct --alias, then start the router that maps a role name to a backend URL.

Why: llama-server loads exactly one model per process, so roles become separate processes. --alias sets the model value returned in API responses; that string is how you later prove which backend answered. -c is the context window in tokens, -ngl is how many layers go to the GPU (use -ngl 0 on a CPU-only box — throughput will differ, check the model card for expectations).

# code role -> Qwen4
llama-server -m /opt/llm/models/Qwen4-Code.gguf --alias qwen4-code \
  --host 127.0.0.1 --port 8080 -c 8192 -ngl 99

# text role -> GigaChat4 (second terminal)
llama-server -m /opt/llm/models/GigaChat4-Text.gguf --alias gigachat4-text \
  --host 127.0.0.1 --port 8081 -c 8192 -ngl 99

The flag set depends on your llama.cpp build; run llama-server --help and drop anything your build does not list.

Example: /opt/llm/roles.yaml:

roles:
  code:
    url: http://127.0.0.1:8080
    model: qwen4-code
    timeout: 300
  text:
    url: http://127.0.0.1:8081
    model: gigachat4-text
    timeout: 120

/opt/llm/router.py:

import yaml, requests
from flask import Flask, request, jsonify, Response

app = Flask(__name__)
ROLES = yaml.safe_load(open("/opt/llm/roles.yaml"))["roles"]

@app.post("/<role>/v1/chat/completions")
def route(role):
    if role not in ROLES:
        return jsonify(error=f"unknown role '{role}'"), 404
    up = ROLES[role]
    payload = request.get_json(force=True)
    payload["model"] = up["model"]          # force the alias of that role
    r = requests.post(f"{up['url']}/v1/chat/completions",
                      json=payload, timeout=up.get("timeout", 300))
    return Response(r.content, status=r.status_code, mimetype="application/json")

@app.get("/health")
def health():
    out = {}
    for role, up in ROLES.items():
        try:
            out[role] = requests.get(f"{up['url']}/health", timeout=2).status_code
        except Exception as exc:
            out[role] = str(exc)
    return jsonify(out)

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8082)

How to check:

curl -s http://127.0.0.1:8080/health   # {"status":"ok"}
curl -s http://127.0.0.1:8081/health   # {"status":"ok"}
curl -s http://127.0.0.1:8082/health   # {"code":200,"text":200}

If a /health call on 8080 or 8081 hangs, the process is still loading weights — check tail -f /opt/llm/logs/code.log. The router only forwards, so a healthy router with a dead upstream still returns an error for that role; both numbers must be 200.

Step 3. Verify each role answers from the right backend

Illustration: Step 3. Verify each role answers from the right backend
Illustration: Step 3. Verify each role answers from the right backend

What to do: send one code request and one text request through the router and inspect the model field of each answer.

Why: a router bug that sends everything to one backend looks identical to success if you only read the text of the reply. The model field is the proof of routing.

# code role
curl -s http://127.0.0.1:8082/code/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"Write a Python function that returns the nth Fibonacci number."}],"max_tokens":128}' \
  | jq -r '.model, .choices[0].message.content'

# text role
curl -s http://127.0.0.1:8082/text/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"Summarise this changelog in three bullets: fixed login timeout, added CSV export, removed legacy API."}],"max_tokens":128}' \
  | jq -r '.model, .choices[0].message.content'

Example: the first command prints qwen4-code on the first line and a function body below it; the second prints gigachat4-text and three bullets. smoke_test.sh automates the same assertion:

#!/usr/bin/env bash
set -euo pipefail
expect() {  # expect <role> <model-alias> <prompt>
  got=$(curl -s "http://127.0.0.1:8082/$1/v1/chat/completions" \
    -H 'Content-Type: application/json' \
    -d "{\"messages\":[{\"role\":\"user\",\"content\":\"$3\"}],\"max_tokens\":16}" | jq -r '.model')
  [ "$got" = "$2" ] && echo "OK   $1 -> $got" || { echo "FAIL $1 expected $2 got $got"; exit 1; }
}
expect code qwen4-code "print hello in python"
expect text gigachat4-text "say hello"

Acceptance checklist:

RolePortAliasRouteModel file
code8080qwen4-code/code/v1/chat/completionsQwen4 GGUF
text8081gigachat4-text/text/v1/chat/completionsGigaChat4 GGUF
router8082—/health—

Troubleshooting

Problem. The code server exits immediately at start

Problem. Port 8080 is taken, so only the text role comes up

Problem. Both servers are up but a request dies with an out-of-memory error

Summary and next steps

You now have two role-pinned local endpoints behind a router, with roles.yaml as the single place to move a role or change timeouts. Next, commit /opt/llm/roles.yaml and smoke_test.sh to git and add a systemd unit per server so the roles survive a reboot — if you also want to expose this on a home server, see How to add AI to your home server: self-hosted services guide, and for code-heavy checks try Step-by-step guide: using LLMs for formal software verification and logic bug hunting.

FAQ

Can one llama-server process serve both models?

No. Each process loads one GGUF, which is why this guide runs two processes with two aliases and a router in front.

Do I need two GPUs?

Not necessarily. Layering is controlled by -ngl per process, so you can offload one role fully and run the other on CPU. Required VRAM per model depends on the quant and context — check the model card.

Which quantization should I use for the code role?

Use whatever the model card lists for Qwen4 GGUF; Q4_K_M is a common trade-off between file size and quality. The card is the authority on available quants and their sizes.

How do I move the text role to a different machine?

Edit url under text: in /opt/llm/roles.yaml, then restart the router (python3 /opt/llm/router.py). The role name and alias stay the same, so callers do not change.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 45 minutes Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
Linux, macOS, or Windows with PowerShell; commands below are bash.; llama.cpp compiled with the server target: cmake -B build && cmake --build build --config Release. Confirm the binary path, usually build/bin/llama-server.; GGUF files for both models. GGUF is a single-file format that packs quantized weights, the… → details (AR-GUIDE-POSHAGOVOE-003)
How to do it?
Step 1. Lay out directories and prove each GGUF loads → Step 2. Start both servers with role aliases and wire the router → Step 3. Verify each role answers from the right backend → details (AR-GUIDE-POSHAGOVOE-004)
Which topics does it cover?
llama-runner несколько моделей, Qwen4 для кода, GigaChat4 локально, распределение GGUF моделей по ролям → details (AR-GUIDE-POSHAGOVOE-002)
What are the key points?
Time to complete: 45 minutes Difficulty: Intermediate → details (AR-GUIDE-POSHAGOVOE-007)

3. Key facts

  1. Time to complete: 45 minutes — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You will need: Linux or macOS (the same flags work in PowerShell on Windows), a compiled llama-server from llama.cpp, GGUF builds of Qwen4 (code role) and GigaChat4 (text role), Python 3 with flask, pyyaml and requests, plus curl and jq. — evidence; status: заявление источника.
  4. Linux, macOS, or Windows with PowerShell; commands below are bash. — evidence; status: заявление источника.
  5. llama.cpp compiled with the server target: cmake -B build && cmake --build build --config Release. Confirm the binary path, usually build/bin/llama-server. — evidence; status: заявление источника.
  6. GGUF files for both models. GGUF is a single-file format that packs quantized weights, the tokenizer and the chat template together, so one file per model is all you copy around. Quantization (for example Q4_K_M) is a smaller, lower-precision version of the weights — pick a quant listed in the model card. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
llama-runner несколько моделейтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Qwen4 для кодапродукт/модельупоминается в заголовке, TL;DR или разделах гайда
GigaChat4 локальнопродукт/модельупоминается в заголовке, TL;DR или разделах гайда
распределение GGUF моделей по ролямтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Linuxплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Pythonплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Gitплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
OpenAIкомпанияупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → Step-by-step guide: how to assign GGUF models to roles in llama-runner (Qwen4 for code, GigaChat4 for text) (AR-GUIDE-POSHAGOVOE-001).
  • Guide — includes step → Step 1. Lay out directories and prove each GGUF loads (AR-GUIDE-POSHAGOVOE-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
No external links——

Cite as: AI Release. Пошаговое руководство: как распределить GGUF-модели по ролям в llama-runner (Qwen4 для кода, GigaChat4 для текста). ai-release.org.