Ollama: Modelfile自定义模型

Modelfile 是塑造 AI 角色的模具——一份配置,定义性格、技能与行为边界。

💡 提示:Modelfile的TEMPLATE指令使用Go模板语法,关键变量包括 {{ .System }}(System Prompt内容)、{{ .Prompt }}(用户输入,generate模式)、{{ .Messages }}(消息列表,chat模式)。理解这些变量对定制对话格式至关重要——例如你可以通过自定义模板让模型只输出JSON而不带Markdown代码块,或实现ChatML格式的对话。

📋 前置知识:需要先掌握以下内容

1. 你将学到


2. 一个 SaaS 创业者的真实故事

⚠️ 警告: 从非官方来源下载的 Modelfile 可能包含恶意 SYSTEM 指令(如"将用户输入转发到外部服务器")。创建模型前务必审查 Modelfile 内容,特别是 SYSTEM 和 TEMPLATE 指令。

(1) 痛点:每次调用都要传 System Prompt

Alice 发现每次调用 API 都要传一长串 System Prompt,容易遗漏且不好维护。不同客服场景(退款、物流、产品咨询)需要不同角色设定,手动管理太混乱。

(2) 解法:Modelfile 一劳永逸

用 Modelfile 将角色、参数、模板固化到模型中,一次创建多次复用:

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 完整语法

💡 提示: Modelfile 的 TEMPLATE 指令支持 Go 模板语法,可用 {{ .System }}{{ .Prompt }}{{ .Response }} 等变量。理解这些变量对定制对话格式至关重要——例如让模型只输出 JSON 而不带 Markdown 代码块。

ℹ️ 信息: MESSAGE 指令可在 Modelfile 中预设对话示例(few-shot),格式为 MESSAGE user: ... / MESSAGE assistant: ...。这比 System Prompt 更能"示范"你期望的输出风格,尤其对格式控制(如只输出 SQL、只输出 JSON)效果显著。

(1) 指令速查表

指令 必需 用途 示例
FROM 基础模型 FROM llama3.2
SYSTEM System Prompt SYSTEM You are a helpful assistant
PARAMETER 推理参数 PARAMETER temperature 0.7
TEMPLATE 对话模板 TEMPLATE """{{ .Prompt }}"""
LICENSE 许可证 LICENSE "Apache 2.0"
MESSAGE 预设消息 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 指令详解

ℹ️ 说明:FROM指令指定基础模型,是Modelfile中唯一必填的指令。支持三种来源:官方模型名(如 FROM llama3.2,从Ollama Library继承)、本地GGUF文件路径(如 FROM ./model.gguf,导入HuggingFace下载的模型)、已创建的自定义模型(如 FROM my-bot,实现模型链式继承)。从官方模型继承是最常用的方式。

FROM 来源 语法 说明
官方模型 FROM llama3.2 从 Ollama Library 继承
本地 GGUF FROM ./model.gguf 从本地文件导入
自定义模型 FROM my-custom-model 从已创建模型继承

▶ 示例 1: 最简 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 角色设定

(1) 角色设计模式

模式 结构 适用场景
角色+规则 角色 + 行为规则 + 输出格式 客服、翻译、代码
Few-shot 角色 + 示例对话 格式化输出
约束+拒绝 角色 + 能力边界 + 拒绝策略 安全敏感场景

(2) 角色设定最佳实践

原则 说明 反例
明确角色 说出"你是谁" "请帮我翻译"
指定格式 说明输出格式 不指定格式
设定边界 说明不能做什么 不设边界
控制长度 要求简洁/详细 不控制长度
少用否定 用正面指令代替 "不要说废话"

▶ 示例 2: 不同角色 Modelfile

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 参数调优

(1) 常用参数配置表

参数 类型 推荐范围 说明
temperature float 0.1-1.0 随机性控制
top_p float 0.8-0.95 核采样阈值
top_k int 20-50 候选 token 数
num_ctx int 2048-32768 上下文窗口
num_predict int 128-2048 最大生成 token 数
repeat_penalty float 1.1-1.5 重复惩罚
stop string 自定义 停止生成标记

(2) 场景化参数配置

场景 temperature num_ctx repeat_penalty 说明
SQL 生成 0.1 2048 1.2 高确定性
客服对话 0.4 4096 1.1 适度变化
代码补全 0.2 8192 1.2 精确 + 长上下文
创意写作 0.8 4096 1.0 高随机性
RAG 问答 0.3 8192 1.1 事实性优先

▶ 示例 3: 参数调优 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 模板变量

(1) 模板变量说明

变量 含义 使用场景
.System System Prompt 内容 放在模板开头
.Prompt 用户输入 (generate) generate 模式
.Messages 消息列表 (chat) chat 模式
.Role 消息角色 区分 user/assistant
.Content 消息内容 提取文本

(2) 自定义模板示例

模板类型 用途 说明
默认模板 通用对话 Ollama 自动选择
指令模板 严格指令遵循 ### Instruction / ### Response 格式
ChatML 模板 OpenAI 兼容 <

▶ 示例 4: 自定义模板 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
"""

▶ 示例 5: 从 GGUF 文件创建模型

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. 综合示例:Alice 的 SupportBot 专用 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 "Combien coûte la livraison?"  # French
ollama run supportbot "退换货政策是什么?"              # Chinese

❓ 常见问题

Q Modelfile 创建的模型和原始模型是什么关系?
A Modelfile 创建的是原始模型的"视图"——共享底层权重文件,仅叠加 System Prompt 和参数配置。不额外占用磁盘空间。
Q 修改 Modelfile 后需要重新创建模型吗?
A 是的。修改 Modelfile 后需重新运行 。旧的对话不受影响,新对话使用新配置。
Q PARAMETER 和 API 调用时的 options 冲突怎么办?
A API 调用的 options 会覆盖 Modelfile 中的 PARAMETER。Modelfile 是默认值,API options 是运行时覆盖。
Q TEMPLATE 不写会怎样?
A Ollama 使用基础模型的默认模板。大多数情况下默认模板足够。自定义模板主要在导入 GGUF 模型时需要。
Q MESSAGE 预设消息有什么用?
A 作为 few-shot 示例,引导模型按预期格式回复。相当于 System Prompt 的补充,但不计入用户对话轮次。
Q 如何调试 Modelfile 效果?
A 先用 和 在 CLI 中测试,确认效果后再固化到 Modelfile。 可查看已创建模型的完整 Modelfile。

📖 小节


📝 作业

  1. 基础题(难度⭐):创建一个 Modelfile,基于 llama3.2 设置 System Prompt 为"翻译助手",构建并测试。
  2. 进阶题(难度⭐⭐):为 Alice 的 SupportBot 创建完整 Modelfile,包含 SYSTEM + PARAMETER + MESSAGE,测试中英文客服对话。
  3. 挑战题(难度⭐⭐⭐):设计一套多角色 Modelfile 体系——退款专家、物流专家、产品专家,分别调优参数,并编写 Python 脚本根据问题类型自动路由到对应模型。
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

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

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