Sub topic 13
Writing a Modelfile
A Modelfile is a plain text recipe that tells Ollama how to build a model. It does not contain weights. It points at weights (an existing model or a GGUF file) and layers settings on top: sampling parameters, a system prompt, a prompt template, and more. This chapter covers the file format and each instruction. The next chapter builds and shares a customized model.
This chapter assumes you can run ollama pull, ollama run, and ollama list. It also assumes you know what a context window and sampling temperature are from the earlier chapters.
What a Modelfile is for
A pulled model ships with defaults chosen by its publisher. A Modelfile lets you change those defaults without editing weights. Common reasons:
- Give a model a fixed persona or output format with a system prompt.
- Lower temperature for more repeatable answers.
- Raise or lower the context window to fit your memory.
- Pre-load a conversation history as examples.
- Wrap imported GGUF weights so they run like any library model.
The syntax resembles a Dockerfile. Each line starts with an instruction in upper or lower case (the convention is upper case), followed by arguments. Lines starting with # are comments.
A minimal Modelfile
This is the example from the topic plan:
FROM llama3.2
PARAMETER temperature 0.3
PARAMETER num_ctx 4096
SYSTEM You are a concise assistant that answers in at most three sentences.Reading it line by line:
FROM llama3.2names the starting point. This is the only required instruction.PARAMETER temperature 0.3sets a default sampling temperature. Lower values make output less random.PARAMETER num_ctx 4096sets the context window to 4096 tokens.SYSTEM ...sets the system message used at the start of every conversation.
The instructions
| Instruction | Purpose | Notes |
|---|---|---|
| `FROM` | Base model or weights | Required. A model name, a path to a GGUF file, or a path to a Safetensors directory. |
| `PARAMETER` | Default generation or runtime setting | One setting per line. Can appear many times. |
| `SYSTEM` | System message | Applied to every new conversation. |
| `TEMPLATE` | Prompt template | Controls how system, user, and assistant text are laid out. |
| `MESSAGE` | Seed conversation history | Role is `system`, `user`, or `assistant`. |
| `ADAPTER` | LoRA adapter | Must match the base model the adapter was trained on. |
| `LICENSE` | License text | Stored with the model and shown by `ollama show`. |
FROM: choosing the base
FROM accepts three kinds of values.
# An existing model, with a tag
FROM llama3.2:3b
# A local GGUF file (covered in a later chapter)
FROM ./my-model.Q4_K_M.ggufWhen you name a library model, Ollama needs it on disk. If you have not pulled it, ollama create will fetch it. Be explicit with tags. FROM llama3.2 resolves to the latest tag, which can change when the publisher updates it. Your custom model is built from whatever latest points to at creation time, so rebuilding later may give a different base.
The new model inherits the base model's weights, template, and parameters. Anything you set in the Modelfile overrides the inherited value. Anything you leave out keeps the base value.
PARAMETER: defaults for generation
Each PARAMETER line sets one value. The ones you will use most:
| Parameter | Meaning | Typical use |
|---|---|---|
| `temperature` | Randomness of sampling | 0.0 to 0.3 for extraction and code. 0.7 to 1.0 for creative text. |
| `num_ctx` | Context window in tokens | Raise for long documents. Costs more memory. |
| `top_p` | Nucleus sampling cutoff | Usually 0.9. Tune this or `temperature`, not both at once. |
| `top_k` | Sample only from the k most likely tokens | Lower values give safer output. |
| `num_predict` | Maximum tokens to generate | Prevents runaway output. |
| `repeat_penalty` | Discourages repeated tokens | Raise slightly if the model loops. |
| `seed` | Random seed | Set with a low temperature for reproducible runs. |
| `stop` | Text that ends generation | Can be repeated for several stop strings. |
The stop parameter is the only one you normally repeat:
FROM llama3.2
PARAMETER stop "Observation:"
PARAMETER stop "###"Parameters in a Modelfile are defaults. A client can override them per request through the options field in the REST API, and inside ollama run you can change them for the session with /set parameter temperature 0.8.
SYSTEM: a standing instruction
The system message sets role and style. It works with the model's template, which inserts it in the format the model was trained on.
FROM llama3.2
SYSTEM """
You are a code reviewer.
Reply with a bulleted list of at most five issues.
If the code has no issues, reply with the single word: clean.
"""Triple quotes allow multi-line text. For a single line, no quotes are needed. A system message in a request through the API replaces the one baked into the model for that request, so the Modelfile value is a default, not a lock.
TEMPLATE: when you need it
Most of the time you do not write a TEMPLATE. Library models already include a correct one, and FROM inherits it. You need one mainly when importing raw weights, because a GGUF file does not always carry the chat format Ollama expects.
A template uses Go template syntax with variables such as .System, .Prompt, and .Response. Here is a ChatML-style example:
FROM ./my-model.Q4_K_M.gguf
TEMPLATE """{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}<|im_start|>user
{{ .Prompt }}<|im_end|>
<|im_start|>assistant
"""
PARAMETER stop "<|im_end|>"A wrong template is a common cause of strange output: the model ignores the system prompt, repeats itself, or never stops. Pair a custom template with the matching stop parameters.
To see the template and parameters of a model you already have, print them:
ollama show llama3.2 --modelfileThis outputs a Modelfile you can copy and edit. It is the safest way to learn what a given model expects.
MESSAGE: seeding a conversation
MESSAGE adds turns to the starting history. This is few-shot prompting baked into the model.
FROM llama3.2
SYSTEM Classify the sentiment of the user's text as positive, negative, or neutral. Reply with one word.
PARAMETER temperature 0
MESSAGE user The battery lasts all day and the screen is gorgeous.
MESSAGE assistant positive
MESSAGE user It arrived late and the box was crushed.
MESSAGE assistant negativeEach example uses context tokens on every request, so keep seeded history short.
Common errors
- Missing
FROM.ollama createfails because there is no base. PutFROMfirst. - Quotes in the wrong place.
PARAMETERvalues are bare, exceptstop, which takes quoted strings.SYSTEMneeds triple quotes only for multiple lines. - Unknown parameter names. A typo such as
num_contextis not a valid setting. Check the spelling against the Ollama Modelfile reference. - Template mismatch. Output full of stray special tokens means the template or stop strings do not match what the model was trained on.
- Adapter mismatch. An
ADAPTERtrained on a different base model produces garbage or an error. - Expecting a rebuild. Editing the Modelfile does nothing to an existing model. You must run
ollama createagain with the same name to replace it.
Verifying the result
After building (the next chapter covers the command), inspect the model rather than trusting the file:
ollama show concise-assistant
ollama show concise-assistant --modelfileThe first prints the architecture, parameter count, quantization, context length, and your overrides. The second prints the effective Modelfile, including inherited values.
Exercise
You write a Modelfile with FROM llama3.2, PARAMETER temperature 0.2, and a SYSTEM line. A teammate calls the API with "options": {"temperature": 0.9} and its own system message in the request. Which temperature and which system message does the model use, and why?
Show answer
It uses temperature 0.9 and the system message from the request. Modelfile values are only defaults. Per-request options and a per-request system message override what is baked into the model.
Exercise
You import a GGUF file with a Modelfile that has only FROM ./model.gguf. The model answers but never stops and prints special tokens. Which instructions should you check or add first?
Show answer
Add or fix TEMPLATE so it matches the model's chat format, and add the matching PARAMETER stop lines for its end-of-turn tokens. A missing or wrong template and missing stop strings are the usual cause.