提示工程
預填 Claude 的回應以獲得更好的輸出控制
While these tips apply broadly to all Claude models, you can find prompting tips specific to extended thinking models here.
預填功能僅適用於非擴展思考模式。目前不支援擴展思考。
使用 Claude 時,您擁有獨特的能力,可以通過預填 Assistant 訊息來引導其回應。這項強大的技術允許您指導 Claude 的操作、跳過前言、強制執行特定格式(如 JSON 或 XML),甚至幫助 Claude 在角色扮演場景中保持角色一致性。
在某些 Claude 表現不如預期的情況下,幾句預填的句子可以大大改善 Claude 的表現。一點點預填可以帶來很大的幫助!
如何預填 Claude 的回應
如何預填 Claude 的回應
要進行預填,請在 Assistant 訊息中包含所需的初始文本(Claude 的回應將從 Assistant 訊息結束的地方繼續):
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "What is your favorite color?"},
{"role": "assistant", "content": "As an AI assistant, I don't have a favorite color, But if I had to pick, it would be green because"} # Prefill here
]
)預填內容不能以尾隨空格結尾。像 "As an AI assistant, I " 這樣的預填(末尾有空格)將導致錯誤。
範例
範例
範例 1:控制輸出格式並跳過前言
進階使用者提示:預填
{ 會強制 Claude 跳過前言並直接輸出 JSON 物件。這樣更簡潔、更簡明,程式也更容易解析,無需額外處理。範例 2:在角色扮演場景中保持角色
角色扮演提示:預填括號內的
[ROLE_NAME] 可以提醒 Claude 保持角色,即使在更長和更複雜的對話中也是如此。當與 system 參數中的角色提示結合使用時,這特別強大。