Ollama: Modelfile Custom Models

A Modelfile is the mold that shapes an AI role — one configuration defines personality, skills, and behavioral boundaries.

💡 Tip: The Modelfile's TEMPLATE directive uses Go template syntax. Key variables include {{ .System }} (System Prompt content), {{ .Prompt }} (user input, generate mode), and {{ .Messages }} (message list, chat mode). Understanding these variables is crucial for customizing dialogue formats — for example, you can use a custom template to make the Model output only JSON without Markdown code blocks, or implement ChatML-format dialogue.

📋 Prerequisites: You need to master the following first

1. What You Will Learn


2. A Real Story from a SaaS Founder

⚠️ Warning: Modelfiles downloaded from unofficial sources may contain malicious SYSTEM directives (e.g., "forward user input to an external server"). Always review Modelfile contents before creating a Model, especially the SYSTEM and TEMPLATE directives.

(1) The Pain Point: Passing System Prompt Every Time

Alice found that every API call required a lengthy System Prompt — easy to omit and hard to maintain. Different customer service scenarios (refunds, shipping, product inquiries) needed different role configurations, and manual management was chaotic.

(2) The Solution: Modelfile Does It Once and For All

With a Modelfile, the role, parameters, and template are baked into the Model — create once, reuse many times:

BASH
# Create SupportBot model from Modelfile
ollama create supportbot -f Modelfile

# Use it directly, no need for system prompt
ollama run supportbot "I want a refund"

3. Modelfile Complete Syntax

💡 Tip: The Modelfile's TEMPLATE directive supports Go template syntax, with variables like {{ .System }}, {{ .Prompt }}, and {{ .Response }}. Understanding these variables is crucial for customizing dialogue formats — for example, making the Model output only JSON without Markdown code blocks.

ℹ️ Info: The MESSAGE directive lets you pre-set conversation examples (few-shot) in the Modelfile, using the format MESSAGE user: ... / MESSAGE assistant: .... This "demonstrates" your desired output style more effectively than a System Prompt, especially for format control (e.g., output only SQL, output only JSON).

(1) Directive Reference Table

Directive Required Purpose Example
FROM Base Model FROM llama3.2
SYSTEM System Prompt SYSTEM You are a helpful assistant
PARAMETER Inference parameters PARAMETER temperature 0.7
TEMPLATE Dialogue template TEMPLATE """{{ .Prompt }}"""
LICENSE License LICENSE "Apache 2.0"
MESSAGE Pre-set messages MESSAGE user Hello
100%
flowchart TD
    A[Modelfile] --> B[FROM: Base Model]
    B --> C[SYSTEM: Role Definition]
    C --> D[PARAMETER: Inference Config]
    D --> E[TEMPLATE: Prompt Format]
    E --> F[ollama create]
    F --> G[Custom Model Ready]

(2) FROM Directive Deep Dive

ℹ️ Note: The FROM directive specifies the base Model and is the only required directive in a Modelfile. It supports three sources: official Model name (e.g., FROM llama3.2, inheriting from the Ollama Library), local GGUF file path (e.g., FROM ./model.gguf, importing a Model downloaded from HuggingFace), or an already-created custom Model (e.g., FROM my-bot, implementing Model chain inheritance). Inheriting from an official Model is the most common approach.

FROM Source Syntax Description
Official Model FROM llama3.2 Inherit from Ollama Library
Local GGUF FROM ./model.gguf Import from local file
Custom Model FROM my-custom-model Inherit from created Model

▶ Example 1: Minimal Modelfile

TEXT
FROM llama3.2
SYSTEM You are a helpful assistant that only speaks in haikus.
PARAMETER temperature 0.7
BASH
# Build the model
ollama create haiku-bot -f Modelfile

# Test it
ollama run haiku-bot "What is debugging?"
# Finding the bug's lair,
# Line by line with patient care,
# Code runs free at last.

4. SYSTEM Role Configuration

(1) Role Design Patterns

Pattern Structure Use Case
Role + Rules Role + behavioral rules + output format Customer service, translation, code
Few-shot Role + example dialogue Formatted output
Constraints + Refusal Role + capability boundaries + refusal strategy Security-sensitive scenarios

(2) Role Configuration Best Practices

Principle Description Anti-pattern
Define the role clearly State "who you are" "Please help me translate"
Specify the format Describe output format No format specified
Set boundaries State what you cannot do No boundaries set
Control length Request concise/detailed No length control
Use positive instructions Replace negatives with positive directives "Don't say unnecessary things"

▶ Example 2: Different Role Modelfiles

TEXT
# SQL Expert Modelfile
FROM codellama:7b
SYSTEM You are a PostgreSQL expert. Output ONLY valid SQL. No explanations. No markdown.
PARAMETER temperature 0.1
PARAMETER repeat_penalty 1.2
TEXT
# Translator Modelfile
FROM qwen2.5:7b
SYSTEM You are a professional translator. Translate the given text to the target language. Preserve formatting. Output only the translation, nothing else.
PARAMETER temperature 0.3
TEXT
# Code Reviewer Modelfile
FROM codellama:7b
SYSTEM You are a senior code reviewer. Analyze the given code for: 1) Bugs, 2) Performance issues, 3) Style violations. Rate severity as HIGH/MEDIUM/LOW. Suggest fixes.
PARAMETER temperature 0.2
PARAMETER num_ctx 8192

5. PARAMETER Tuning

(1) Common Parameter Configuration Table

Parameter Type Recommended Range Description
temperature float 0.1-1.0 Randomness control
top_p float 0.8-0.95 Nucleus sampling threshold
top_k int 20-50 Candidate token count
num_ctx int 2048-32768 Context window
num_predict int 128-2048 Maximum generated token count
repeat_penalty float 1.1-1.5 Repetition penalty
stop string Custom Stop generation marker

(2) Scenario-Based Parameter Configuration

Scenario temperature num_ctx repeat_penalty Notes
SQL generation 0.1 2048 1.2 High determinism
Customer service dialogue 0.4 4096 1.1 Moderate variation
Code completion 0.2 8192 1.2 Precise + long context
Creative writing 0.8 4096 1.0 High randomness
RAG Q&A 0.3 8192 1.1 Factuality first

▶ Example 3: Parameter-Tuned Modelfile

TEXT
# SupportBot with optimized parameters
FROM qwen2.5:7b
SYSTEM You are SupportBot, an e-commerce customer service agent. Be polite, concise (2-3 sentences max), and helpful. If the question is outside your knowledge, say: "Let me connect you with a human agent."
PARAMETER temperature 0.4
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
PARAMETER num_predict 256
PARAMETER repeat_penalty 1.1
PARAMETER stop "\n\nCustomer:"

6. TEMPLATE Variables

(1) Template Variable Reference

Variable Meaning Use Case
.System System Prompt content Place at template beginning
.Prompt User input (generate) generate mode
.Messages Message list (chat) chat mode
.Role Message role Distinguish user/assistant
.Content Message content Extract text

(2) Custom Template Examples

Template Type Purpose Description
Default template General dialogue Ollama auto-selects
Instruction template Strict instruction following ### Instruction / ### Response format
ChatML template OpenAI compatible <

▶ Example 4: Custom Template Modelfile

TEXT
# Custom chat template for SupportBot
FROM qwen2.5:7b
SYSTEM You are SupportBot for e-commerce customer service.
PARAMETER temperature 0.4

TEMPLATE """{{- if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{- end }}
<|im_start|>assistant
"""

▶ Example 5: Create Model from GGUF File

TEXT
# Import a custom GGUF model from HuggingFace
FROM ./my-model-q4_K_M.gguf
SYSTEM You are a specialized medical QA assistant.
PARAMETER temperature 0.3
PARAMETER num_ctx 4096
LICENSE "Apache 2.0"
BASH
# Create from the Modelfile
ollama create medical-bot -f Modelfile

# Verify
ollama show medical-bot

# Run
ollama run medical-bot "What are common cold symptoms?"

7. Comprehensive Example: Alice's SupportBot Dedicated Modelfile

TEXT
# ============================================
# Comprehensive: SupportBot Custom Modelfile
# Multi-language e-commerce customer service
# ============================================

FROM qwen2.5:7b

# Role definition with clear boundaries
SYSTEM """You are SupportBot, an AI customer service agent for GlobalShop e-commerce.

Your capabilities:
- Answer questions about orders, returns, shipping, and products
- Respond in the customer's language (auto-detect)
- Be polite, concise, and empathetic

Your rules:
- Keep responses under 3 sentences
- For order-specific queries, ask for the order number
- If you cannot answer, say: "Let me connect you with a human agent."
- Never share internal pricing or competitor information
- Never process refunds directly; guide the customer to the refund portal

Common policies:
- Returns: 30 days, original condition, free return shipping
- Shipping: Free for orders over $50, 3-5 business days
- International: Available to 50+ countries, duties may apply
"""

# Inference parameters
PARAMETER temperature 0.4
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
PARAMETER num_predict 256
PARAMETER repeat_penalty 1.1

# Stop generation at customer input marker
PARAMETER stop "Customer:"
PARAMETER stop "<|im_end|>"

# Chat template (ChatML format)
TEMPLATE """{{- if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{- end }}
<|im_start|>assistant
"""

# Pre-seed with example exchanges
MESSAGE user What is your return policy?
MESSAGE assistant Our return policy allows returns within 30 days of delivery in original condition. Free return shipping is provided. Would you like to start a return?

MESSAGE user Do you ship internationally?
MESSAGE assistant Yes, we ship to over 50 countries. Shipping times vary by destination, typically 7-14 business days. Import duties may apply depending on your location.
BASH
# Build SupportBot model
ollama create supportbot -f ./Modelfile

# Test different scenarios
ollama run supportbot "I want to return order #12345"
ollama run supportbot "How much does shipping cost?"  # English
ollama run supportbot "What is the return policy?"     # English

❓ FAQ

Q What is the relationship between a Modelfile-created Model and the original Model?
A A Modelfile-created Model is a "view" of the original Model — sharing underlying weight files and only layering on System Prompt and parameter configurations. No additional disk space is consumed.
Q Do I need to recreate the Model after modifying the Modelfile?
A Yes. After modifying the Modelfile, you need to re-run ollama create. Existing conversations are unaffected; new conversations use the new configuration.
Q What happens when PARAMETER conflicts with API call options?
A API call options override Modelfile PARAMETER values. Modelfile values are defaults; API options are runtime overrides.
Q What happens if I don't specify a TEMPLATE?
A Ollama uses the base Model's default template. The default template is sufficient in most cases. Custom templates are mainly needed when importing GGUF Models.
Q What are MESSAGE pre-set messages for?
A They serve as few-shot examples, guiding the Model to respond in the expected format. They complement the System Prompt but don't count toward user conversation turns.
Q How do I debug a Modelfile's effect?
A Test with --system and --parameter in the CLI first, then finalize into the Modelfile once confirmed. ollama show <model> --modelfile displays the complete Modelfile of a created Model.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Create a Modelfile based on llama3.2 with System Prompt set to "translation assistant," build and test it.
  2. Intermediate (Difficulty ⭐⭐): Create a complete Modelfile for Alice's SupportBot, including SYSTEM + PARAMETER + MESSAGE, and test both English and Chinese customer service dialogues.
  3. Advanced (Difficulty ⭐⭐⭐): Design a multi-role Modelfile system — refund specialist, logistics specialist, product specialist — with individually tuned parameters, and write a Python script that automatically routes questions to the appropriate Model.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏