** Ollama Modelfile 示例**,并配套详细讲解。内容覆盖:
- 基本结构
- 模板
- system prompt
- 参数
- 工具声明(可选)
示例以 Qwen2/Qwen3 类型模型为例,但结构对所有模型通用。
一、完整可运行的 Modelfile 示例
# 使用基础模型
FROM qwen2.5:7b-instruct
# 系统提示,会成为 .System 字段
SYSTEM """
You are a helpful assistant that answers concisely.
"""
# 模型配置
PARAMETER temperature 0.2
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
# 函数工具定义(可选)
TOOLS """
[
{
"name": "get_weather",
"description": "Get weather information of a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
]
"""
# 模板:负责把 Ollama 的内部结构转换成 Qwen 能理解的 prompt
TEMPLATE """
{{- if .System }}
<|im_start|>system
{{ .System }}
<|im_end|>
{{- end }}
{{- if .Tools }}
<|im_start|>system
You may call one or more functions.
<tools>
{{ .Tools }}
</tools>
<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}
<|im_end|>
{{- end }}
<|im_start|>assistant
"""
此 Modelfile 可直接保存为 Modelfile,然后:
ollama create mymodel -f Modelfile
ollama run mymodel
二、逐段讲解
下面详细说明每个字段的意义。
1. FROM(必需)
FROM qwen2.5:7b-instruct
指定底层模型。 Ollama 会基于该模型构建新模型。
可以换成:
llama3.1:8b-instructqwen3:0.6bmistral:7b-instruct
2. SYSTEM(可选)
SYSTEM """
You are a helpful assistant that answers concisely.
"""
写入到 .System 字段。
模板可以决定是否注入到最终 prompt。
3. PARAMETER(可选)
PARAMETER temperature 0.2
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
覆盖模型运行时的默认参数。 不写则使用系统默认值。
常见:
temperaturetop_pnum_ctxpresence_penalty、frequency_penalty
4. TOOLS(可选)
TOOLS """
[
{
"name": "get_weather",
"description": "...",
"parameters": { ... }
}
]
"""
这是 Ollama 对 function calling 的声明格式。
写入 .Tools,供模板读取。
如果模板不处理工具,工具将不会被模型实际使用。
5. TEMPLATE(核心部分)
模板负责将:
.Messages
.System
.Tools
转换为模型需要的格式。
例如,对于 Qwen 系列模型,常见格式是:
<|im_start|>role
content
<|im_end|>
模板中的内容是 Go template 语法,.Messages、.System、.Tools 的变量由 Ollama 注入。
模板解释示例
{{- if .System }}
<|im_start|>system
{{ .System }}
<|im_end|>
{{- end }}
- 如果有系统 prompt,则输出一个 system 段。
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}
<|im_end|>
{{- end }}
遍历整个对话历史,按格式输出用户和助手所有消息。
最终:
<|im_start|>assistant
告诉模型:现在轮到 assistant 回答。
三、运行示例
ollama create mymodel -f Modelfile
ollama run mymodel
输入:
What's the weather in Beijing today?
模型可能会输出工具调用:
<tool_call>
{"name": "get_weather", "arguments":{"city":"Beijing"}}
</tool_call>
Ollama 会解析,并自动调用名为 get_weather 的函数(如果你在 API server 注册了这个函数)。
四、可选增强功能
可以在 TEMPLATE 里加入:
- 思考模式(Qwen3 的
/think) - 特殊 token
<think>...</think> - 工具调用特殊包装
- 自定义输出限制
例如加入 Qwen 的思考控制:
{{ if .IsThinkSet }}{{ if .Think }} /think {{ else }} /no_think {{ end }}{{ end }}
五、最小可运行版本(无工具)
如果你只想写一个最小 Modelfile,可以用这个版本:
FROM qwen2.5:7b-instruct
SYSTEM "A concise and helpful assistant."
TEMPLATE """
{{- if .System }}
<|im_start|>system
{{ .System }}
<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}
<|im_end|>
{{- end }}
<|im_start|>assistant
"""