当从文本补全迁移到消息时,请考虑以下变化。

输入和输出

文本补全和消息之间最大的变化是您指定模型输入和从模型接收输出的方式。 使用文本补全时,输入是原始字符串:
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服务器发送事件中的任何一个。详见文本补全流式传输 消息可以包含不同类型的多个内容块,因此其流式格式稍微复杂一些。详见消息流式传输