模板语法

Ollama 使用 Go 模板语言来定义对话模板。本章介绍模板的高级用法。

基础语法

变量输出

使用 {{ }} 输出变量:

{{ .Prompt }}
{{ .System }}

注释

使用 {{/* */}} 添加注释:

{{/* 这是一个注释 */}}

可用变量

基本变量

变量类型说明
.Systemstring系统提示词
.Promptstring用户输入
.Firstbool是否第一条消息

消息历史

变量类型说明
.Messagesarray消息历史数组
.Message.Rolestring消息角色
.Message.Contentstring消息内容

条件判断

if 语句

{{ if .First }}
这是第一条消息。
{{ end }}

if-else 语句

{{ if .System }}
系统提示:{{ .System }}
{{ else }}
没有系统提示。
{{ end }}

判断角色

{{ range .Messages }}
{{ if eq .Role "user" }}
用户: {{ .Content }}
{{ else if eq .Role "assistant" }}
助手: {{ .Content }}
{{ end }}
{{ end }}

比较运算符

运算符说明
eq等于
ne不等于
lt小于
le小于等于
gt大于
ge大于等于

循环

range 遍历

{{ range .Messages }}
角色: {{ .Role }}
内容: {{ .Content }}
{{ end }}

带索引遍历

{{ range $index, $msg := .Messages }}
消息 {{ $index }}: {{ $msg.Content }}
{{ end }}

常用模板模式

ChatML 格式

TEMPLATE """{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}<|im_start|>user
{{ .Prompt }}<|im_end|>
<|im_start|>assistant
"""

Alpaca 格式

TEMPLATE """{{ if .System }}{{ .System }}

{{ end }}### Instruction:
{{ .Prompt }}

### Response:
"""

Vicuna 格式

TEMPLATE """{{ if .System }}{{ .System }}

{{ end }}USER: {{ .Prompt }}
ASSISTANT:
"""

Llama 3 格式

TEMPLATE """<|begin_of_text|>{{ if .System }}<|start_header_id|>system<|end_header_id|>

{{ .System }}<|eot_id|>{{ end }}<|start_header_id|>user<|end_header_id|>

{{ .Prompt }}<|eot_id|><|start_header_id|>assistant<|end_header_id|>

"""

Mistral 格式

TEMPLATE """{{ if .System }}[INST] {{ .System }}

{{ end }}{{ .Prompt }} [/INST]"""

高级技巧

空白控制

使用 - 去除多余空白:

{{- .Prompt -}}
  • {{- 去除左边空白
  • -}} 去除右边空白

管道操作

{{ .Prompt | upper }}
{{ .System | lower }}

自定义变量

{{ $role := "assistant" }}
角色是: {{ $role }}

and/or 逻辑

{{ if and .System .First }}
有系统提示且是第一条消息。
{{ end }}

{{ if or .System .Prompt }}
有系统提示或用户输入。
{{ end }}

完整示例

多轮对话模板

TEMPLATE """{{ if .System }}System: {{ .System }}

{{ end }}{{ range .Messages }}{{ if eq .Role "user" }}User: {{ .Content }}

{{ else if eq .Role "assistant" }}Assistant: {{ .Content }}

{{ end }}{{ end }}Assistant: """

带历史的聊天模板

TEMPLATE """{{- if .System }}
<|system|>
{{ .System }}</s>
{{- end }}
{{- range .Messages }}
{{- if eq .Role "user" }}
<|user|>
{{ .Content }}</s>
{{- else if eq .Role "assistant" }}
<|assistant|)
{{ .Content }}</s>
{{- end }}
{{- end }}
<|assistant|)
"""

代码助手模板

TEMPLATE """{{ if .System }}# System
{{ .System }}

{{ end }}# Task
{{ .Prompt }}

# Solution
```"""

调试模板

查看模型的模板

ollama show llama3.2 --modelfile

测试模板

创建测试模型验证模板效果:

ollama create test-template -f Modelfile
ollama run test-template "测试输入"

常见问题

模板不生效

检查语法是否正确,特别是 {{}} 的配对。

输出格式不对

可能是空白字符问题,尝试使用 {{--}}

变量为空

使用条件判断处理空值:

{{ if .System }}{{ .System }}{{ end }}