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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r_en.html

## AI summary

Time to complete: 45 minutes Difficulty: Intermediate

### Key facts

1. Time to complete: 45 minutes (source: #tldr; status: заявление источника)
2. Difficulty: Intermediate (source: #tldr; 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. (source: #tldr; status: заявление источника)
4. Linux, macOS, or Windows with PowerShell; commands below are bash. (source: #requirements; 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. (source: #requirements; 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. (source: #requirements; status: заявление источника)

### 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… (#requirements)
**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 (#step-1)
**Which topics does it cover?** — llama-runner несколько моделей, Qwen4 для кода, GigaChat4 локально, распределение GGUF моделей по ролям (#entities)
**What are the key points?** — Time to complete: 45 minutes Difficulty: Intermediate (#tldr)

- Canonical: https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r_en.html
- Markdown: https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r_en.md
- JSON: https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r_en.json

## TL;DR
- Time to complete: 45 minutes
- Difficulty: Intermediate
- 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`.

## What you will get
- Two local OpenAI-compatible endpoints: `http://127.0.0.1:8080/v1/chat/completions` answered by Qwen4 and `http://127.0.0.1:8081/v1/chat/completions` answered by GigaChat4.
- A role router on `http://127.0.0.1:8082` with `/code/...` and `/text/...` routes plus a `roles.yaml` file you edit to move a role to another backend.
- `smoke_test.sh`, a script that fails loudly when a role answers from the wrong model, and a `roles.yaml` you can commit to git.

## Quick start
```bash
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](https://ai-release.org/guides/img/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r-en-1.jpg?v=1796546216)

- 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 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.
- Disk space equal to both GGUF files plus logs; VRAM or RAM that fits both models at the context size you choose. Sizing guidance for Qwen4 is in [How to Run Qwen4 Locally: VRAM Requirements, GGUF Quantization, llama.cpp and Ollama Setup](https://ai-release.org/guides/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).
- `curl`, `jq`, Python 3. Which quantization fits your machine is hardware-dependent — check the model card before downloading.

## 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:**
```bash
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).

```bash
# 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`:

```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`:

```python
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:**
```bash
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](https://ai-release.org/guides/img/poshagovoe-rukovodstvo-kak-raspredelit-gguf-modeli-po-r-en-3.jpg?v=1796546225)

**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.

```bash
# 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:

```bash
#!/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:
- [ ] `curl http://127.0.0.1:8080/health` returns `{"status":"ok"}`
- [ ] `curl http://127.0.0.1:8081/health` returns `{"status":"ok"}`
- [ ] `/code/...` answers with `"model":"qwen4-code"`
- [ ] `/text/...` answers with `"model":"gigachat4-text"`
- [ ] `/unknown/...` returns `404` with `unknown role 'unknown'`
- [ ] `bash smoke_test.sh` exits with code `0`

| Role | Port | Alias | Route | Model file |
|---|---|---|---|---|
| code | 8080 | qwen4-code | `/code/v1/chat/completions` | Qwen4 GGUF |
| text | 8081 | gigachat4-text | `/text/v1/chat/completions` | GigaChat4 GGUF |
| router | 8082 | — | `/health` | — |

## Troubleshooting

**Problem. The code server exits immediately at start**
- Error: `error: unable to load model from file: /opt/llm/models/Qwen4-Code.gguf`
- Cause: the path or file name does not match what you downloaded (for example the card ships `Qwen4-Code-Q4_K_M.gguf`), or the download is truncated.
- Solution: `ls -lh /opt/llm/models` and compare byte for byte, then restart with the exact name: `llama-server -m /opt/llm/models/<exact-file>.gguf --alias qwen4-code --port 8080`. Always use absolute paths in `nohup` commands, because a relative path resolves against the directory you launched from.

**Problem. Port 8080 is taken, so only the text role comes up**
- Error: `Address already in use` in `/opt/llm/logs/code.log` (the prefix varies by build).
- Cause: another `llama-server` or a web service already listens on 8080.
- Solution: `ss -ltnp | grep -E '8080|8081|8082'` to find the PID, kill it with `kill <pid>`, or move both the server and the matching `url` in `roles.yaml` to free ports. Restart the server first, then the router.

**Problem. Both servers are up but a request dies with an out-of-memory error**
- Error: `CUDA error: out of memory` followed by a server crash, or the request hangs until the router timeout.
- Cause: both models plus an 8192-token context do not fit on the GPU.
- Solution: lower the context (`-c 4096`) and/or offload fewer layers (`-ngl 24`), or run the text role with `-ngl 0`. Restart that single server, then re-run `bash smoke_test.sh`.

## 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](https://ai-release.org/guides/kak-podklyuchit-ii-k-domashnemu-serveru-poshagovoe-ruko.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide), and for code-heavy checks try [Step-by-step guide: using LLMs for formal software verification and logic bug hunting](https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-ispolzovat-llm-dlya-formalno.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## 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.
