當從文本補全遷移到訊息時,請考慮以下變更。

輸入和輸出

文本補全和訊息之間最大的變更是您指定模型輸入和從模型接收輸出的方式。

使用文本補全時,輸入是原始字串:

Python
prompt = "\n\nHuman: Hello there\n\nAssistant: Hi, I'm Claude. How can I help?\n\nHuman: Can you explain Glycolysis to me?\n\nAssistant:"

使用訊息時,您指定輸入訊息列表而不是原始提示:

messages = [
  {"role": "user", "content": "Hello there."},
  {"role": "assistant", "content": "Hi, I'm Claude. How can I help?"},
  {"role": "user", "content": "Can you explain Glycolysis to me?"},
]

每個輸入訊息都有一個rolecontent

角色名稱

文本補全 API 期望交替的\n\nHuman:\n\nAssistant:輪次,但訊息 API 期望userassistant角色。您可能會看到文件中提到「human」或「user」輪次。這些指的是同一個角色,往後將使用「user」。

使用文本補全時,模型生成的文本在回應的completion值中返回:

Python
>>> response = anthropic.completions.create(...)
>>> response.completion
" Hi, I'm Claude"

使用訊息時,回應是content值,這是一個內容區塊列表:

Python
>>> response = anthropic.messages.create(...)
>>> response.content
[{"type": "text", "text": "Hi, I'm Claude"}]

為 Claude 預填回應

使用文本補全時,您可以預填 Claude 回應的一部分:

Python
prompt = "\n\nHuman: Hello\n\nAssistant: Hello, my name is"

使用訊息時,您可以通過讓最後一個輸入訊息具有assistant角色來達到相同的結果:

Python
messages = [
  {"role": "human", "content": "Hello"},
  {"role": "assistant", "content": "Hello, my name is"},
]

這樣做時,回應content將從最後一個輸入訊息content繼續:

JSON
{
  "role": "assistant",
  "content": [{"type": "text", "text": " Claude. How can I assist you today?" }],
  ...
}

系統提示

使用文本補全時,系統提示是通過在第一個\n\nHuman:輪次之前添加文本來指定的:

Python
prompt = "Today is January 1, 2024.\n\nHuman: Hello, Claude\n\nAssistant:"

使用訊息時,您使用system參數指定系統提示:

Python
anthropic.Anthropic().messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system="Today is January 1, 2024.", # <-- system prompt
    messages=[
        {"role": "user", "content": "Hello, Claude"}
    ]
)

模型名稱

訊息 API 要求您指定完整的模型版本(例如claude-sonnet-4-20250514)。

我們之前支援僅指定主要版本號(例如claude-2),這會導致自動升級到次要版本。但是,我們不再推薦這種整合模式,訊息也不支援它。

停止原因

文本補全總是有以下其中一種stop_reason

  • "stop_sequence":模型要麼自然結束其輪次,要麼生成了您的自定義停止序列之一。
  • "max_tokens":要麼模型生成了您指定的max_tokens內容,要麼達到了其絕對最大值

訊息有以下值之一的stop_reason

  • "end_turn":對話輪次自然結束。
  • "stop_sequence":生成了您指定的自定義停止序列之一。
  • "max_tokens":(不變)

指定最大令牌數

  • 文本補全:max_tokens_to_sample參數。沒有驗證,但每個模型都有上限值。
  • 訊息:max_tokens參數。如果傳遞的值高於模型支援的值,則返回驗證錯誤。

串流格式

在文本補全中使用"stream": true時,回應包括completionpingerror伺服器發送事件中的任何一個。詳情請參閱文本補全串流

訊息可以包含多個不同類型的內容區塊,因此其串流格式稍微複雜一些。詳情請參閱訊息串流