← Code Recipes
Hosting, Gateways & Local

llama.cpp Free code examples in C#, Python and JavaScript

The inference engine underneath most local tooling. Runs on almost anything.

C# Python Java JavaScript

WHAT THIS PAGE COVERS

Quantisation levels, and what each one actually costs you in quality.

Model Q4_K_M
Package llama-cpp-python
Checked

Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.

Install

LLamaSharp needs a backend package as well as the binding — the managed package alone compiles and then fails at load. Pick the backend that matches the hardware.

dotnet add package LLamaSharp
dotnet add package LLamaSharp.Backend.Cpu
# or LLamaSharp.Backend.Cuda12 / .Metal for GPU

# Grab a Q4_K_M GGUF:
curl -L -o Qwen3.5-0.8B-Q4_K_M.gguf \
  https://huggingface.co/ggml-org/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf
Choosing a quantisation

Q4_K_M is the default recommendation and the one to start from. The file name carries the precision, so it is visible at a glance in a deployment — which matters when a slow machine turns out to be running Q8_0 by accident.

# For an 8B model:
#   Q8_0     ~8.5GB   near-lossless, twice the memory of Q4
#   Q5_K_M   ~5.7GB   marginal gain over Q4_K_M
#   Q4_K_M   ~4.9GB   THE DEFAULT
#   Q3_K_M   ~4.0GB   quality loss you will notice
#
# The weights are not the whole cost: context is allocated on top,
# and a 32k window can be what exhausts the machine rather than
# the model itself.
Running it in-process

LLamaWeights and LLamaContext are both IDisposable and both hold native memory. Weights are loaded once per process; a context is per conversation.

using LLama;
using LLama.Common;

var parameters = new ModelParams("Qwen3.5-0.8B-Q4_K_M.gguf")
{
    ContextSize = 4096,      // costs memory on top of the weights
    GpuLayerCount = 32,      // 0 for CPU only
};

// Expensive, native memory. One per process.
using var weights = LLamaWeights.LoadFromFile(parameters);
using var context = weights.CreateContext(parameters);

var executor = new InteractiveExecutor(context);
var session = new ChatSession(executor);

await foreach (var token in session.ChatAsync(
    new ChatHistory.Message(AuthorRole.User, "Explain a database index."),
    new InferenceParams { MaxTokens = 256 }))
{
    Console.Write(token);
}
Serving it instead, which is usually right

In-process ties gigabytes of weights to your application's lifetime, so a rolling deploy reloads them. `llama serve` keeps the model warm and reduces your dependency to an HTTP call.

// Terminal: llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF:Q4_K_M
using System.ClientModel;
using OpenAI;
using OpenAI.Chat;

// Required by the client, ignored by the server.
var placeholder = new ApiKeyCredential("llama");

ChatClient chat = new(
    model: "local",          // llama serve ignores this
    credential: placeholder,
    options: new OpenAIClientOptions
    {
        Endpoint = new Uri("http://127.0.0.1:8080/v1"),
        NetworkTimeout = TimeSpan.FromMinutes(5),
    });

var completion = await chat.CompleteChatAsync("Explain a database index.");
Console.WriteLine(completion.Value.Content[0].Text);
Install

llama-cpp-python builds the engine from source on install, so a C compiler is required. The -hf flag on the CLI downloads GGUF files from Hugging Face and caches them.

# The engine itself, for the server and the CLI:
git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp && cmake -B build && cmake --build build -j --config Release

# Try a model without downloading anything by hand:
llama cli -hf ggml-org/Qwen3.5-0.8B-GGUF

# The Python binding builds llama.cpp as part of the install.
pip install llama-cpp-python
Choosing a quantisation

THIS IS THE DECISION. The suffix on the GGUF file is the precision, and it is the only knob that changes both memory and quality at once. Q4_K_M is the default for a reason; below Q4 the failures start looking like stupidity rather than compression.

# Same model, four precisions. Sizes are for an 8B model.
#
#   Q8_0     ~8.5GB   near-lossless; use when RAM is not the constraint
#   Q6_K     ~6.6GB   very close to Q8, meaningfully smaller
#   Q5_K_M   ~5.7GB   a small, usually unnoticeable step down
#   Q4_K_M   ~4.9GB   THE DEFAULT. Best quality per gigabyte.
#   Q3_K_M   ~4.0GB   noticeable: more repetition, worse arithmetic
#   Q2_K     ~3.2GB   a demo, not a deployment
#
# Pull a specific one with a tag:
llama serve -hf ggml-org/gemma-4-e4b-it-GGUF:Q4_K_M

# Or quantise a model you already have:
./build/bin/llama-quantize model-f16.gguf model-Q4_K_M.gguf Q4_K_M
Running it in-process

n_gpu_layers is the other big lever: -1 offloads everything it can. n_ctx costs memory proportional to its size, so a 32k context on a laptop can be what pushes the model out of RAM rather than the weights.

from llama_cpp import Llama

llm = Llama.from_pretrained(
    repo_id="ggml-org/Qwen3.5-0.8B-GGUF",
    filename="*Q4_K_M.gguf",       # the quantisation, by pattern
    n_ctx=4096,                    # context costs memory too
    n_gpu_layers=-1,               # -1 = offload everything possible
    verbose=False,
)

response = llm.create_chat_completion(
    messages=[{"role": "user", "content": "Explain a database index."}],
)

print(response["choices"][0]["message"]["content"])
Serving it instead, which is usually right

In-process means one model per process and no sharing. `llama serve` gives you an OpenAI-compatible endpoint, so the application stops depending on the engine entirely — and that is the shape FreeYantra uses for its own tools.

# Defaults to http://127.0.0.1:8080
llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF:Q4_K_M

# Started with no model, `llama serve` becomes a router: it loads and
# unloads models on demand and forwards each request to the right one.
llama serve

# Then any OpenAI client works against it:
#   OpenAI(base_url="http://127.0.0.1:8080/v1", api_key=PLACEHOLDER)
Install

node-llama-cpp ships prebuilt binaries for the common platforms, so there is usually no compiler step. It is the only first-party-ish Node path to the engine.

npm install node-llama-cpp

# Or skip the binding entirely and run the server:
llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF:Q4_K_M
Choosing a quantisation

The suffix is the precision. Q4_K_M is the default recommendation; the steps above it buy little and the steps below it cost real quality.

# For an 8B model:
#   Q8_0     ~8.5GB   near-lossless
#   Q5_K_M   ~5.7GB   a small step down, rarely noticed
#   Q4_K_M   ~4.9GB   THE DEFAULT
#   Q3_K_M   ~4.0GB   repetition and arithmetic start to suffer
#
npx node-llama-cpp pull \
  --dir ./models \
  "https://huggingface.co/ggml-org/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf"
Running it in-process

A model is loaded once and a context is created per conversation. Creating a context per request is the common mistake — the load is the expensive part and it is being repeated.

import { getLlama, LlamaChatSession } from "node-llama-cpp";
import path from "node:path";

const llama = await getLlama();

// Expensive. Once per process.
const model = await llama.loadModel({
  modelPath: path.join("./models", "Qwen3.5-0.8B-Q4_K_M.gguf"),
});

// Cheap-ish. Once per conversation, not once per request.
const context = await model.createContext({ contextSize: 4096 });
const session = new LlamaChatSession({
  contextSequence: context.getSequence(),
});

console.log(await session.prompt("Explain a database index."));
Serving it instead, which is usually right

A binding ties the model's lifetime to your process — a deploy unloads gigabytes and reloads them. A server keeps the model warm and turns the engine into an HTTP dependency any client can speak to.

// Terminal: llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF:Q4_K_M
import OpenAI from "openai";

// Required by the client, ignored by the server.
const placeholderKey = "llama";

const client = new OpenAI({
  baseURL: "http://127.0.0.1:8080/v1",
  apiKey: placeholderKey,
});

const response = await client.chat.completions.create({
  model: "local",          // llama serve ignores this
  messages: [{ role: "user", content: "Explain a database index." }],
});

console.log(response.choices[0].message.content);

QUESTIONS

Which languages are the llama.cpp examples in?

C#, Python and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.

Which package do I install for llama.cpp?

The samples use llama-cpp-python. The install step on each language tab gives the exact command.

Which llama.cpp model do these examples use?

Q4_K_M, checked against the official documentation on 26 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.

Where is the official llama.cpp documentation?

https://github.com/ggml-org/llama.cpp — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.

ALSO IN HOSTING, GATEWAYS & LOCAL

The authority

Official llama.cpp documentation

Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.

Read the docs ↗

https://github.com/ggml-org/llama.cpp

New drops, every week

Free tools & Claude templates, landing regularly.

We keep shipping new free tools, code recipes and Claude Code templates. Follow @freeyantra on Instagram or join the newsletter so you never miss one.

Follow @freeyantra

or get them by email

Double opt-in. Unsubscribe any time. Privacy