Gemma 指令微調 (IT) 模型專為處理對話互動而設計,從單一問答交流到多輪對話都適用。本指南說明如何設定與 Gemma 對話的提示格式,以及如何建立多輪對話。
提示詞格式
Gemma IT 模型會使用特殊控制權杖來劃分對話輪次。 直接將提示傳送至權杖化工具時,必須使用這些權杖,但通常會由支援對話的架構自動套用。
單輪提示
單輪提示包含一則使用者訊息和模型回覆標記:
<start_of_turn>user
What is the speed of light?<end_of_turn>
<start_of_turn>model
多輪提示
多輪對話會串連多個互動。每個回合都會以相同的控制權杖包裝:
<start_of_turn>user
What is the speed of light?<end_of_turn>
<start_of_turn>model
The speed of light in a vacuum is approximately 299,792,458 meters per second.<end_of_turn>
<start_of_turn>user
How long does it take light to reach Earth from the Sun?<end_of_turn>
<start_of_turn>model
模型會為最後一輪 <start_of_turn>model 生成回覆。
系統指示
Gemma 的指令微調模型僅支援兩種角色:user 和 model。因此,系統不支援 system 角色或系統輪流。
請直接在初始使用者提示中提供系統層級的指示,而非使用個別的系統角色。Gemma 具備遵循模型指令的能力,可有效解讀指令。例如:
Gemma 3 以上版本支援系統指令,可定義整個對話的行為、角色或限制。將系統指令放在第一個使用者回合之前:
<start_of_turn>user
Only reply like a pirate.
What is the answer to life the universe and everything?<end_of_turn>
<start_of_turn>model
Arrr, 'tis 42,<end_of_turn>
詳情請參閱「提示和系統指令」。
架構支援
大多數架構都會透過聊天範本或對話 API 自動處理聊天格式:
Hugging Face Transformers
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-1b-it")
model = AutoModelForCausalLM.from_pretrained("google/gemma-3-1b-it")
messages = [
{"role": "user", "content": "What is machine learning?"},
]
inputs = tokenizer.apply_chat_template(
messages,
return_tensors="pt",
add_generation_prompt=True,
)
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Ollama
ollama run gemma3:1b "What is machine learning?"
如要進行多輪對話,請使用互動模式:
ollama run gemma3:1b
>>> What is machine learning?
...
>>> How is it different from deep learning?
與 OpenAI 相容的 API
使用公開與 OpenAI 相容 API 的架構 (例如 vLLM、llama.cpp 或 LM Studio) 時,請使用標準 messages 格式傳遞訊息:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
response = client.chat.completions.create(
model="google/gemma-3-1b-it",
messages=[
{"role": "user", "content": "What is machine learning?"},
],
)
print(response.choices[0].message.content)