Ollama 使用 Go 模板语言来定义对话模板。本章介绍模板的高级用法。
使用 {{ }} 输出变量:
{{ .Prompt }}
{{ .System }}
使用 {{/* */}} 添加注释:
{{/* 这是一个注释 */}}
| 变量 | 类型 | 说明 |
|---|---|---|
| .System | string | 系统提示词 |
| .Prompt | string | 用户输入 |
| .First | bool | 是否第一条消息 |
| 变量 | 类型 | 说明 |
|---|---|---|
| .Messages | array | 消息历史数组 |
| .Message.Role | string | 消息角色 |
| .Message.Content | string | 消息内容 |
{{ if .First }}
这是第一条消息。
{{ end }}
{{ 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 .Messages }}
角色: {{ .Role }}
内容: {{ .Content }}
{{ end }}
{{ range $index, $msg := .Messages }}
消息 {{ $index }}: {{ $msg.Content }}
{{ end }}
TEMPLATE """{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}<|im_start|>user
{{ .Prompt }}<|im_end|>
<|im_start|>assistant
"""
TEMPLATE """{{ if .System }}{{ .System }}
{{ end }}### Instruction:
{{ .Prompt }}
### Response:
"""
TEMPLATE """{{ if .System }}{{ .System }}
{{ end }}USER: {{ .Prompt }}
ASSISTANT:
"""
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|>
"""
TEMPLATE """{{ if .System }}[INST] {{ .System }}
{{ end }}{{ .Prompt }} [/INST]"""
使用 - 去除多余空白:
{{- .Prompt -}}
{{- 去除左边空白-}} 去除右边空白{{ .Prompt | upper }}
{{ .System | lower }}
{{ $role := "assistant" }}
角色是: {{ $role }}
{{ 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 }}