消息线程

通过在每次请求中只发送新消息,让长时间运行的智能体更快获得首个 token,尤其是在长对话中。

通过在每次请求中只发送新消息,让长时间运行的智能体更快获得首个 token,尤其是在长对话中。

消息线程

Beta

所属功能 Messages API
模型 所有模型
云平台 Claude API
Claude Platform on AWS
Claude Models on Google Cloud(Anthropic 托管)
Microsoft Foundry
Beta 请求头 message-threads-2026-08-12
数据处理 不符合 ZDR 条件
不符合 HIPAA 条件

使用消息线程后,请求会更小,而且随着对话增长,首个 token 的延迟仍然较低、更加稳定。线程对于长时间的智能体循环最有帮助。不使用线程时,每一轮都会再次上传整个对话,API 也会再次验证并对所有内容进行分词。使用线程后,这些工作的大部分只需要针对新的一轮进行。

消息线程会将对话短暂保留在服务器上。你只需发送一次完整对话、系统提示词和工具。之后每一轮发送新消息和上一次响应的 id,而不是完整对话。API 在调用模型之前重建对话。你需要在 Messages API 请求中添加 thread 参数和一个 beta 请求头。响应仍然是通常的消息。

消息线程不同于 Claude Managed Agents 中的会话线程。

消息线程如何工作

  • 创建。 像现在一样发送第一个请求,包含完整对话、system 和 tools。在请求中添加 "thread": {"type": "create"}。API 会以响应 id 为索引存储对话,包括 Claude 的回复。
  • 继续。 只发送自上次响应之后新增的消息,并添加 "thread": {"type": "continue", "previous_message_id": "<previous id>"}。不要在请求中包含 system 和 tools。线程会保留创建请求中的值。使用每次新响应的 id 继续下一轮。
  • 重放。 线程按尽力而为的方式提供。它会在最后一次请求的 5 分钟后过期,API 会在最后一次使用后不超过 1 小时将其删除。API 每存储一次响应,都会重新开始计算这 5 分钟。如果 API 无法继续线程,继续请求会返回 404 错误。在新的创建请求中再次发送完整对话,然后从该响应的 id 继续。SDK 线程辅助工具会替你完成重放(见 SDK 辅助工具的行为)。收到备用模型的响应之后,请参阅在线程中使用回退。

应用始终是对话的权威记录。保留每条消息的副本,并从一开始就构建重放路径。无论创建请求还是继续请求,其响应都不会说明 API 是否存储了这一轮。你会在下一次继续请求时得知。SDK 线程辅助工具会在辅助对象存在期间,将这份副本保留在内存中,不会保存到其他地方。如果对话必须比进程存活得更久,就要自行保留副本。

使用 SDK 操作线程

SDK 提供了线程辅助工具,替你构建每次请求。使用与 Messages 请求相同的字段创建辅助工具,然后每次发送一轮。辅助工具将完整对话保留在内存中。

本示例有两轮。辅助工具在第一轮创建线程,在第二轮继续线程,并替你添加 beta 请求头。顶层 cache_control 是可选的,它请求在每一轮使用提示词缓存(见线程上的提示词缓存)。没有它时,后续每一轮仍然只发送新消息,但除非你自行添加缓存断点,否则不会缓存任何内容。

client = anthropic.Anthropic()

# Create the helper. This call sends no request.
thread = client.beta.messages.thread(
    model="claude-opus-5-5",
    max_tokens=1024,
    cache_control={"type": "ephemeral"},
    system="You are a support agent for Acme. Keep replies short.",
)

# Turn 1: the helper creates a thread and sends the full conversation
thread.send({"role": "user", "content": "Hi! I have a question about an order."})

# Turn 2: the helper continues the thread and sends only the new message
second = thread.send(
    {"role": "user", "content": "How long does standard shipping usually take?"}
)

for block in second.content:
    if block.type == "text":
        print(block.text)
const client = new Anthropic();

// Create the helper. This call sends no request.
const thread = client.beta.messages.thread({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  cache_control: { type: "ephemeral" },
  system: "You are a support agent for Acme. Keep replies short."
});

// Turn 1: the helper creates a thread and sends the full conversation
await thread.send({ role: "user", content: "Hi! I have a question about an order." });

// Turn 2: the helper continues the thread and sends only the new message
const second = await thread.send({
  role: "user",
  content: "How long does standard shipping usually take?"
});

for (const block of second.content) {
  if (block.type === "text") {
    console.log(block.text);
  }
}
using Anthropic.Helpers.Beta;

AnthropicClient client = new();

// Create the helper. This call sends no request.
var thread = client.Beta.Messages.Thread(
    new ThreadCreateParams
    {
        Model = Messages::Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Messages = [],
        CacheControl = new(),
        System = "You are a support agent for Acme. Keep replies short.",
    }
);

// Turn 1: the helper creates a thread and sends the full conversation
await thread.Send(
    new BetaUserMessageParam { Content = "Hi! I have a question about an order." }
);

// Turn 2: the helper continues the thread and sends only the new message
var second = await thread.Send(
    new BetaUserMessageParam { Content = "How long does standard shipping usually take?" }
);

foreach (var block in second.Content)
{
    if (block.TryPickText(out var textBlock))
    {
        Console.WriteLine(textBlock.Text);
    }
}
client := anthropic.NewClient()
ctx := context.Background()

// Create the helper. This call sends no request.
thread := client.Beta.Messages.NewThread(anthropic.BetaMessageThreadCreateParams{
	Model:        anthropic.ModelClaudeOpus5_5,
	MaxTokens:    1024,
	CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),
	System: []anthropic.BetaTextBlockParam{
		{Text: "You are a support agent for Acme. Keep replies short."},
	},
})

// Turn 1: the helper creates a thread and sends the full conversation
_, err := thread.Send(ctx, anthropic.BetaMessageThreadSendParams{
	Messages: []anthropic.BetaMessageParam{
		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hi! I have a question about an order.")),
	},
})
if err != nil {
	panic(err)
}

// Turn 2: the helper continues the thread and sends only the new message
second, err := thread.Send(ctx, anthropic.BetaMessageThreadSendParams{
	Messages: []anthropic.BetaMessageParam{
		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("How long does standard shipping usually take?")),
	},
})
if err != nil {
	panic(err)
}

for _, block := range second.Content {
	if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
		fmt.Println(textBlock.Text)
	}
}
var client = AnthropicOkHttpClient.fromEnv();

// Create the helper. This call sends no request.
var thread = client.beta().messages().thread(
    ThreadCreateParams.builder()
        .model(Model.CLAUDE_OPUS_5_5)
        .maxTokens(1024)
        .cacheControl(BetaCacheControlEphemeral.builder().build())
        .system("You are a support agent for Acme. Keep replies short.")
        .build()
);

// Turn 1: the helper creates a thread and sends the full conversation
thread.send("Hi! I have a question about an order.");

// Turn 2: the helper continues the thread and sends only the new message
var second = thread.send("How long does standard shipping usually take?");

second.content().stream()
    .flatMap(block -> block.text().stream())
    .forEach(textBlock -> IO.println(textBlock.text()));
$client = new Client();

// Create the helper. This call sends no request.
$thread = $client->beta->messages->thread(
    maxTokens: 1024,
    model: Model::CLAUDE_OPUS_5_5,
    cacheControl: new BetaCacheControlEphemeral(),
    system: 'You are a support agent for Acme. Keep replies short.',
);

// Turn 1: the helper creates a thread and sends the full conversation
$thread->send(['role' => 'user', 'content' => 'Hi! I have a question about an order.']);

// Turn 2: the helper continues the thread and sends only the new message
$second = $thread->send(['role' => 'user', 'content' => 'How long does standard shipping usually take?']);

foreach ($second->content as $block) {
    if ($block instanceof \Anthropic\Beta\Messages\BetaTextBlock) {
        echo $block->text, PHP_EOL;
    }
}
client = Anthropic::Client.new

# Create the helper. This call sends no request.
thread = client.beta.messages.thread(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  cache_control: {type: "ephemeral"},
  system_: "You are a support agent for Acme. Keep replies short."
)

# Turn 1: the helper creates a thread and sends the full conversation
thread.send_message({role: "user", content: "Hi! I have a question about an order."})

# Turn 2: the helper continues the thread and sends only the new message
second = thread.send_message({role: "user", content: "How long does standard shipping usually take?"})

second.content.each do |block|
  puts block.text if block.type == :text
end

自行发送 thread 字段

自行在每次请求中添加 thread 字段。可以使用 cURL、CLI 或普通的 SDK 请求来完成。

在线程的每次请求中发送 message-threads-2026-08-12 beta 请求头。

本示例在第一轮创建线程,在第二轮继续线程。顶层 cache_control 请求在每一轮使用提示词缓存。在完整对话连同 system 和 tools 达到可缓存的最小长度之前,不会缓存任何内容。

# Turn 1: send the full conversation and create a thread
curl -sS --fail-with-body https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "anthropic-beta: message-threads-2026-08-12" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "cache_control": {"type": "ephemeral"},
    "system": "You are a support agent for Acme. Keep replies short.",
    "messages": [{"role": "user", "content": "Hi! I have a question about an order."}],
    "thread": {"type": "create"}
  }'

# Turn 2: send only the new message. Set message_id to the id of the turn 1 response.
# Leave out system and tools: the thread keeps them.
curl -sS --fail-with-body https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "anthropic-beta: message-threads-2026-08-12" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "cache_control": {"type": "ephemeral"},
    "messages": [{"role": "user", "content": "How long does standard shipping usually take?"}],
    "thread": {"type": "continue", "previous_message_id": "'"$message_id"'"}
  }'
# Turn 1: send the full conversation and create a thread
ant beta:messages create --beta message-threads-2026-08-12 <<'YAML'
model: claude-opus-5-5
max_tokens: 1024
cache_control:
  type: ephemeral
system: "You are a support agent for Acme. Keep replies short."
messages:
  - role: user
    content: "Hi! I have a question about an order."
thread:
  type: create
YAML

# Turn 2: send only the new message. Set message_id to the id of the turn 1 response.
# Leave out system and tools: the thread keeps them.
ant beta:messages create --beta message-threads-2026-08-12 <<YAML
model: claude-opus-5-5
max_tokens: 1024
cache_control:
  type: ephemeral
messages:
  - role: user
    content: "How long does standard shipping usually take?"
thread:
  type: continue
  previous_message_id: $message_id
YAML
client = anthropic.Anthropic()

# Turn 1: send the full conversation and create a thread
first = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    cache_control={"type": "ephemeral"},
    system="You are a support agent for Acme. Keep replies short.",
    messages=[{"role": "user", "content": "Hi! I have a question about an order."}],
    thread={"type": "create"},
    betas=["message-threads-2026-08-12"],
)

# Turn 2: send only the new message and the id of the turn 1 response.
# Leave out system and tools: the thread keeps them.
second = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    cache_control={"type": "ephemeral"},
    messages=[
        {"role": "user", "content": "How long does standard shipping usually take?"}
    ],
    thread={"type": "continue", "previous_message_id": first.id},
    betas=["message-threads-2026-08-12"],
)

for block in second.content:
    if block.type == "text":
        print(block.text)
const client = new Anthropic();

// Turn 1: send the full conversation and create a thread
const first = await client.beta.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  cache_control: { type: "ephemeral" },
  system: "You are a support agent for Acme. Keep replies short.",
  messages: [{ role: "user", content: "Hi! I have a question about an order." }],
  thread: { type: "create" },
  betas: ["message-threads-2026-08-12"]
});

// Turn 2: send only the new message and the id of the turn 1 response.
// Leave out system and tools: the thread keeps them.
const second = await client.beta.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  cache_control: { type: "ephemeral" },
  messages: [{ role: "user", content: "How long does standard shipping usually take?" }],
  thread: { type: "continue", previous_message_id: first.id },
  betas: ["message-threads-2026-08-12"]
});

for (const block of second.content) {
  if (block.type === "text") {
    console.log(block.text);
  }
}
AnthropicClient client = new();

// Turn 1: send the full conversation and create a thread
var first = await client.Beta.Messages.Create(
    new()
    {
        Model = Messages::Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        CacheControl = new(),
        System = "You are a support agent for Acme. Keep replies short.",
        Messages =
        [
            new BetaUserMessageParam { Content = "Hi! I have a question about an order." },
        ],
        Thread = new BetaThreadCreateParams(),
        Betas = [AnthropicBeta.MessageThreads2026_08_12],
    }
);

// Turn 2: send only the new message and the id of the turn 1 response.
// Leave out System and Tools: the thread keeps them.
var second = await client.Beta.Messages.Create(
    new()
    {
        Model = Messages::Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        CacheControl = new(),
        Messages =
        [
            new BetaUserMessageParam { Content = "How long does standard shipping usually take?" },
        ],
        Thread = new BetaThreadContinueParams(first.ID),
        Betas = [AnthropicBeta.MessageThreads2026_08_12],
    }
);

foreach (var block in second.Content)
{
    if (block.TryPickText(out var textBlock))
    {
        Console.WriteLine(textBlock.Text);
    }
}
client := anthropic.NewClient()
ctx := context.Background()

// Turn 1: send the full conversation and create a thread
threadCreate := anthropic.NewBetaThreadCreateParams()
first, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{
	Model:        anthropic.ModelClaudeOpus5_5,
	MaxTokens:    1024,
	CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),
	System: []anthropic.BetaTextBlockParam{
		{Text: "You are a support agent for Acme. Keep replies short."},
	},
	Messages: []anthropic.BetaMessageParam{
		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hi! I have a question about an order.")),
	},
	Thread: anthropic.BetaMessageThreadParamUnion{OfCreate: &threadCreate},
	Betas:  []anthropic.AnthropicBeta{anthropic.AnthropicBetaMessageThreads2026_08_12},
})
if err != nil {
	panic(err)
}

// Turn 2: send only the new message and the id of the turn 1 response.
// Leave out System and Tools: the thread keeps them.
second, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{
	Model:        anthropic.ModelClaudeOpus5_5,
	MaxTokens:    1024,
	CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),
	Messages: []anthropic.BetaMessageParam{
		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("How long does standard shipping usually take?")),
	},
	Thread: anthropic.BetaMessageThreadParamOfContinue(first.ID),
	Betas:  []anthropic.AnthropicBeta{anthropic.AnthropicBetaMessageThreads2026_08_12},
})
if err != nil {
	panic(err)
}

for _, block := range second.Content {
	if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
		fmt.Println(textBlock.Text)
	}
}
var client = AnthropicOkHttpClient.fromEnv();

// Turn 1: send the full conversation and create a thread
var first = client.beta().messages().create(
    MessageCreateParams.builder()
        .model(Model.CLAUDE_OPUS_5_5)
        .maxTokens(1024)
        .cacheControl(BetaCacheControlEphemeral.builder().build())
        .system("You are a support agent for Acme. Keep replies short.")
        .addUserMessage("Hi! I have a question about an order.")
        .thread(BetaThreadCreateParams.builder().build())
        .addBeta(AnthropicBeta.MESSAGE_THREADS_2026_08_12)
        .build()
);

// Turn 2: send only the new message and the id of the turn 1 response.
// Leave out system and tools: the thread keeps them.
var second = client.beta().messages().create(
    MessageCreateParams.builder()
        .model(Model.CLAUDE_OPUS_5_5)
        .maxTokens(1024)
        .cacheControl(BetaCacheControlEphemeral.builder().build())
        .addUserMessage("How long does standard shipping usually take?")
        .continueThread(first.id())
        .addBeta(AnthropicBeta.MESSAGE_THREADS_2026_08_12)
        .build()
);

second.content().stream()
    .flatMap(block -> block.text().stream())
    .forEach(textBlock -> IO.println(textBlock.text()));
$client = new Client();

// Turn 1: send the full conversation and create a thread
$first = $client->beta->messages->create(
    model: Model::CLAUDE_OPUS_5_5,
    maxTokens: 1024,
    cacheControl: new BetaCacheControlEphemeral(),
    system: 'You are a support agent for Acme. Keep replies short.',
    messages: [
        ['role' => 'user', 'content' => 'Hi! I have a question about an order.'],
    ],
    thread: BetaThreadCreateParams::with(),
    betas: ['message-threads-2026-08-12'],
);

// Turn 2: send only the new message and the id of the turn 1 response.
// Leave out system and tools: the thread keeps them.
$second = $client->beta->messages->create(
    model: Model::CLAUDE_OPUS_5_5,
    maxTokens: 1024,
    cacheControl: new BetaCacheControlEphemeral(),
    messages: [
        ['role' => 'user', 'content' => 'How long does standard shipping usually take?'],
    ],
    thread: BetaThreadContinueParams::with(previousMessageID: $first->id),
    betas: ['message-threads-2026-08-12'],
);

foreach ($second->content as $block) {
    if ($block instanceof \Anthropic\Beta\Messages\BetaTextBlock) {
        echo $block->text, PHP_EOL;
    }
}
client = Anthropic::Client.new

# Turn 1: send the full conversation and create a thread
first = client.beta.messages.create(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  cache_control: {type: "ephemeral"},
  system_: "You are a support agent for Acme. Keep replies short.",
  messages: [{role: "user", content: "Hi! I have a question about an order."}],
  thread: {type: "create"},
  betas: ["message-threads-2026-08-12"]
)

# Turn 2: send only the new message and the id of the turn 1 response.
# Leave out system_ and tools: the thread keeps them.
second = client.beta.messages.create(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  cache_control: {type: "ephemeral"},
  messages: [{role: "user", content: "How long does standard shipping usually take?"}],
  thread: {type: "continue", previous_message_id: first.id},
  betas: ["message-threads-2026-08-12"]
)

second.content.each do |block|
  puts block.text if block.type == :text
end

每次请求应该发送什么

分组 字段 规则
仅创建时发送 system、tools 只在创建请求中发送它们,包括其上的任何 cache_control 断点。在继续请求中发送任一字段,即使值为 null,也会返回 400 错误。
固定 model、tool_choice、thinking、mcp_servers(各服务器的授权令牌除外)、context_management、output_config、container 中的 skills、顶层 cache_control,以及 anthropic-beta 值的集合 在线程的每次请求中发送它们,值必须与创建请求相同。值不同时会返回 400 错误,错误码为 thread_fingerprint_mismatch,错误消息会指出不同的字段。
自由 max_tokens、stop_sequences、stream、metadata、service_tier,以及本页未提及的其他字段 这些字段可以在不同轮次之间改变。

API 不存储 MCP 服务器 URL、MCP 授权令牌或容器 id。每次请求使用 mcp_servers 和 container 时,都要发送它们。MCP 授权令牌可以在请求之间改变。

SDK 线程辅助工具会替你在继续请求中省略 system 和 tools,并在每一轮重新发送固定字段。

如果使用服务器端回退,要么在线程的每次请求中发送 fallbacks 字段,要么每次都不发送。请参阅在线程中使用回退。

要更改仅创建时发送的字段或固定字段,请开始一个新线程:在创建请求中发送完整对话,并使用新的值。

如果更改 system 或 tools: 对于以下模型,请从新的创建请求所发送的对话中移除每个 thinking 和 redacted_thinking 块:Claude Fable 5.2、Claude Mythos 5.2、Claude Fable 5.1、Claude Mythos 5.1、Claude Opus 5.5、Claude Sonnet 5.5 和 Claude Haiku 5.5。这样,模型回答时就不包含此前的推理。

继续请求中只发送新消息。API 不会将它们与已经持有的消息进行比较。重新发送某条消息,可能使它在对话中出现两次,也可能导致请求返回错误。例如,以之前的响应开头的继续请求会返回错误。

新消息通常以一条 user 消息开头:可以是下一轮用户消息,也可以是回答上次响应中 tool_use 的 tool_result 块。如果响应以 stop_reason: "pause_turn" 停止,请通过继续请求恢复,使用该响应的 id 和空的 messages 列表("messages": [])。如果该请求返回 404 错误,请在新的创建请求中重放完整对话,包括已暂停的响应。轮次暂停期间,不要发送新的 user 消息:API 会拒绝它。使用 SDK 线程辅助工具时,不带消息调用 send():辅助工具会发送该请求,并在收到 404 错误时重放。

线程只能追加,每个响应 id 只能被继续一次。始终从线程最新的响应 id 继续。要编辑较早的消息或从那里分支,请通过创建请求开始新线程。要用摘要替换较早的轮次,请参阅压缩对话。

线程上的提示词缓存

线程不会替你缓存提示词。提示词缓存的工作方式与不使用线程时相同:由你选择缓存断点的位置。

要缓存每一轮,在线程的每次请求中发送顶层 cache_control,如前面的示例所示。API 会将它应用于每次请求 messages 中最后一个可缓存的块。这样,每一轮都会从缓存读取较早的对话,并将新的一轮写入缓存。顶层 cache_control 是固定字段:每次请求都发送相同的值。

你也可以自行将 cache_control 断点放在块上:

  • 如果创建请求中的断点位于 tools、system 或最后一块之前的某个消息块上,它们会在后续每一轮继续生效。请求 messages 最后一块上的断点会在该请求中写入缓存。要缓存每个新轮次,每次请求都要发送一个断点。没有断点的请求仍有可能从缓存读取部分对话。
  • 发送断点之后,无法移动或删除它,因为继续请求不能重新发送较早的消息。
  • 带有 thread 的请求最多可携带 4 个 cache_control 断点。顶层 cache_control 算一个。创建请求中 system 和 tools 上的断点,在每个继续请求中仍然计数。较早存储的消息上的断点不计数。多一个断点也会返回 400 错误,错误码为 thread_unsupported_request。
  • 如果自行在消息块上放置断点,在新的创建请求中重放对话时,要移除较早消息上的断点,并在最后一块上保留一个。这样,请求就不会超过 4 个的限制。

流式传输

线程支持流式传输。响应 id 会在 message_start 事件中到达,但只有收到 message_stop 事件后才能从它继续。更早发送的继续请求可能返回 404 错误。

如果继续请求的流在 message_stop 之前中断,请再次发送相同的继续请求。如果该请求返回 thread_already_continued 或 thread_continue_in_flight 错误,请在新的创建请求中重放完整对话。

连接可能在服务器仍在生成响应时中断,也可能在服务器保存响应之后中断。因此,API 可能拒绝重试。重放你保存的精确副本是安全的。

SDK 线程辅助工具不会在流中断后重试继续请求。请参阅 SDK 辅助工具的行为。

在线程无法继续时恢复

API 无法继续线程时,继续请求会返回 404 错误,且 error.details.error_code 为 thread_not_found。响应不会说明原因。可能的原因包括:

  • 线程已过期。
  • API 处理了上一轮,却没有存储。例如,API 不会存储以被 max_tokens 截断的工具调用结束的响应。
  • 上一次响应由备用模型生成。请参阅在线程中使用回退。
  • 上一次响应仍在生成。
  • 请求来自不同的组织或工作区。
  • 请求来自与创建线程者不同的用户或服务账户。使用工作区密钥(旧版)创建的线程始终绑定该密钥,因此整个线程都要使用同一个密钥。
  • 新消息添加了已存储对话无法接受的内容。例如,在原本没有图像的对话中添加第一张图像,可能返回此错误。

要恢复,请使用自己保留的副本,在新的创建请求中发送完整对话,以及 system 和 tools。SDK 线程辅助工具会自行发送一次这个创建请求,并在发送时省略较早轮次的 cache_control 断点。如果副本中的较早消息带有 cache_control 断点,请先移除它们(见线程上的提示词缓存)。然后从新响应的 id 继续。如果上一次响应由备用模型生成,请参阅在线程中使用回退。要排除所有权方面的原因,线程的每次请求都使用相同的 API 密钥和工作区。在 Claude Platform on AWS 上,使用创建线程的 IAM 角色或 IAM 用户的凭据为线程的每次请求签名。

请求不存在的模型也会返回 404 错误,所以重放之前要检查 error.details.error_code。

如果重放后立即发出的继续请求仍然返回 404 错误,API 可能无法存储该对话,例如对话非常大时。此时发送请求时不要包含 thread。如果创建 SDK 线程辅助工具时,将 unsupported_request_behavior 设置为 continue_unthreaded,辅助工具就会这样处理。否则,它会在每一轮重放。

拒绝之后

响应带有 stop_reason: "refusal" 时,不要继续线程。API 可能已经持有被拒绝的轮次,而继续请求无法将其移除。使用创建请求开始新线程,并省略或改写导致拒绝的轮次。请参阅拒绝与回退。SDK 线程辅助工具会替你处理:它不会保留被拒绝的轮次,下一轮会开始新线程。

在线程中使用回退

Claude API 上的线程支持服务器端回退。创建线程时就要决定:要么在线程的每次请求中发送 fallbacks,要么每次都不发送。fallbacks 的值可以在请求之间变化。如果继续请求新增或移除 fallbacks,就会返回 400 错误,错误码为 thread_fingerprint_mismatch。

线程保留一个模型,因此 API 不会存储备用模型生成的轮次。你仍会照常获得响应,但无法从它的 id 继续。每次响应之后,按照以下步骤处理:

  1. 如果 stop_reason 为 "refusal",按照拒绝之后处理。
  2. 否则,在 usage.iterations 中查找 fallback_message 条目。对于流式响应,从最后的 message_delta 事件中读取。如果没有该条目,照常继续线程。
  3. 如果存在该条目,说明响应由备用模型生成。在新的创建请求中发送完整对话,包括该响应和你的下一条消息。保留 server-side-fallback-2026-07-01 beta 请求头。从以下两种请求中选择一种:
    • 再次发送同样的请求。 保持 model、fallbacks 和其他参数不变。如果你请求的模型回答,API 就会存储新线程。如果备用模型回答,响应会再次带有 fallback_message 条目,API 不会存储它,因此下一轮需要重复这一步。粘性路由可能直接将这些请求发送给备用模型,因此每一轮都可能需要发送完整对话。SDK 线程辅助工具采用这种方式。
    • 在备用模型上开始新线程。 将 model 设置为该 fallback_message 条目中的 model,省略 fallbacks,并使用该模型接受的参数。API 会立即存储这个线程,并一直使用该备用模型。回退尝试可能使用了与你发送值不同的设置,因此 API 可能拒绝从最初请求复制过来的值。
  4. 针对该请求的响应,回到第 1 步。如果其中没有 fallback_message 条目,从它的 id 继续新线程。

粘性路由会在请求发生回退后启动(创建请求或不带 thread 的请求)。在大约一小时内,对于相同对话、包含 fallbacks 的后续创建请求,它可能不尝试你请求的模型,而直接发送给备用模型。API 不会存储这些轮次,而且每次成功回答都会重新开始计算这一小时。继续请求既不会启动这种路由,也不会使用它。如果组织或工作区使用零数据保留或客户管理的加密密钥,粘性路由不适用。

压缩对话

线程只能追加,因此无法用摘要替换较早的轮次。要压缩对话,请从摘要开始新线程。在代码中编写摘要,然后将其作为普通消息放入新的创建请求,并包含 system 和 tools。线程不支持按需压缩(见线程不支持的功能)。

SDK 辅助工具的行为

辅助工具替你做的事情:

  • 为每次使用线程的请求添加 message-threads-2026-08-12 beta 请求头。
  • 在第一轮创建线程,之后继续线程,只发送新消息,省略 system 和 tools。
  • 继续请求返回 thread_not_found、thread_already_continued 或 thread_continue_in_flight 时,在新的创建请求中重放一次完整对话。
  • 不带消息调用 send() 时,恢复 pause_turn 响应。
  • 拒绝之后开始新线程。你仍会照常收到 stop_reason: "refusal" 响应,但辅助工具不会保留该轮次:它会收回你传给该次调用的消息。通过 thread.append(...) 添加的消息,或创建辅助工具时提供的消息,仍然保留为待发送状态。下一轮会将这些消息与被拒绝轮次之前的对话一起,通过新的创建请求发送。请发送改写后的消息;如果导致拒绝的是待发送的消息,则从参数中移除它,再开始新线程。
  • 收到备用模型的响应后,发送新的创建请求。响应的 usage.iterations 中带有 fallback_message 条目时,辅助工具会保留响应,并在下一轮通过新的创建请求发送完整对话。它不会等待 404 错误。该请求会保留你设置的 model 和 fallbacks。
  • 每次重新发送较早的轮次时,都省略这些轮次的 cache_control 断点,例如重放或分叉后的第一轮。最新消息、system、tools 和顶层 cache_control 按你提供的内容发送。

需要自行处理的事情:

  • 回退。 只要 API 持续使用备用模型回答,辅助工具就会在每一轮通过新的创建请求发送完整对话,因为 API 不会存储这些轮次。收到所请求模型的响应之后,它才会恢复继续请求。如果想将对话转移到备用模型,请根据在线程中使用回退所述,从参数开始新线程,将 model 设为该模型,并省略 fallbacks。
  • 流中断。 如果流在响应中途结束,辅助工具会保留已完成的块和已经到达的文字,下一轮通过新的创建请求发送完整对话。辅助工具不会自行重试:如果想重新发送被中断的轮次,请不带消息调用 send()。如果保留的部分以工具调用结束,在下一条消息中回答这些调用。如果你在流显示 stop_reason: "refusal" 之后停止读取,辅助工具会将该轮次视为拒绝。
  • 其他错误。 thread_fingerprint_mismatch 和 thread_unsupported_request 错误会传到你的代码。要在 thread_unsupported_request 错误之后不使用 thread 继续,请在创建辅助工具时,将 unsupported_request_behavior 设置为 continue_unthreaded。使用该设置时,如果重放后的第一次继续请求再次返回 thread_not_found,辅助工具也会停止使用 thread。API 可能无法存储该对话。不使用该设置时,辅助工具会在每一轮重放。自行创建线程的工具运行器默认使用该设置。

SDK 的 beta 工具运行器默认也使用线程。你可以在创建运行器时关闭这一默认行为。

其他辅助方法

要做什么 使用
流式传输一轮 thread.stream(...)
流式轮次的完整响应 stream.get_final_message()
完整对话 thread.messages
下一轮将从其继续的响应 id thread.previous_message_id
添加消息而不发送 thread.append(...)
更改后续轮次的字段 thread.update(...)
复制线程 thread.fork()
用于开始新线程的字段和对话 thread.params
此线程上的工具运行器 thread.tool_runner()
不使用线程的工具运行器 tool_runner(..., thread=False)

流式传输。 辅助工具在流到达 message_stop 时记录响应,因此要将流读到结束。如果提前停止读取,请结束流,让线程可以用于下一轮:

  • Python:退出 with 块。
  • TypeScript:退出循环,或调用 abort()。
  • Go:调用 Close。
  • Java 和 Ruby:调用 close()。
  • C#:释放枚举器。退出 await foreach 就会这样做。
  • PHP:调用 close()。

在 C# 中,请求会在开始读取流时发出。

在 C#、Go、Java 和 PHP 中,拒绝之后 thread.LastMessage 仍然返回上一轮响应;如果是第一轮,则不返回任何内容。请从流事件中读取拒绝。

更改字段。 更新不会发送任何内容,并且适用于之后的每一轮。线程获得响应之后,辅助工具会拒绝更改 system 或 tools 的轮次,API 也会拒绝对其他固定字段的更改(见每次请求应该发送什么)。要更改其中一个字段,请从参数开始新线程,或分叉线程,并在分叉的第一轮之前更新它。

分叉。 分叉会复制对话、字段和请求选项,并且不发送任何内容。其第一轮通过新的创建请求发送完整对话,之后两个线程相互独立。分叉始终从整个对话开始,而不是从较早的响应开始。

参数。 参数包含辅助工具的字段和完整对话。将其传给创建辅助工具的方法,即可开始新线程。例如,使用不同的 system(见每次请求应该发送什么),或截短 messages 以丢弃后面的轮次。从参数开始的线程会按原样发送每条消息,包括 cache_control 断点,因此要保持在 4 个以内(见线程上的提示词缓存)。除 Ruby 外,参数不包含请求选项,所以需要再次传入它们。

结构化输出。 创建辅助工具时提供输出格式。后续轮次无法更改它。如何获取解析结果,取决于 SDK:

  • Python 和 TypeScript:调用 thread.parse(...)。
  • C#:使用 client.Beta.Messages.Thread<T>(...) 创建辅助工具。
  • Go:Send 会反序列化到 Params.OutputConfig.Format.Schema 指向的结构体中。
  • Java:使用 thread(...) 和 outputConfig(MyClass.class) 创建辅助工具。
  • PHP:当 outputConfig 指定一个模型类时,send() 会在文本块上设置 parsed。
  • Ruby:向 thread(...) 传入 output_config: {format: MyModel},然后读取 reply.parsed_output。

错误

API 在模型运行之前返回下表中的错误。请求不使用 token,线程及其过期时间也不会改变。对于 400 错误,error.type 为 invalid_request_error;对于 404 错误,则为 not_found_error。

状态码 error_code 含义 应对方法
404 thread_not_found API 无法继续线程。 在新的创建请求中发送完整对话。
400 thread_fingerprint_mismatch 某个固定字段不同于线程中存储的值。错误消息会指出这些字段。 保持固定字段不变,或开始新线程以更改它。
400 thread_already_continued 每个响应 id 只能继续一次。 从线程最新的响应 id 继续。如果客户端从未收到该响应,则重放。
400 thread_continue_in_flight 来自该响应 id 的另一个继续请求仍在运行,通常是你自己较早的尝试。 等它完成并从其响应 id 继续,或重放。
400 thread_unsupported_request 请求使用了线程不支持的功能或组织设置。存在 error.details.unsupported 时,它会指出具体项目。 从请求中移除该功能,或发送完整对话而不使用 thread。

某些带有 thread 的请求会返回不带 error_code 的 400 错误。例如,继续请求缺少 previous_message_id,或包含 system 或 tools 时,就会返回此错误。

下面的示例展示一个错误响应体:

{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "thread: a maximum of 4 blocks with cache_control may be provided when `thread` is set. Found 5.",
    "details": {
      "error_code": "thread_unsupported_request",
      "unsupported": ["cache_control"]
    }
  },
  "request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"
}

线程不支持的功能

线程不支持以下功能:

  • Message Batches。包含 thread 的请求项会在批处理结果中以 invalid_request_error 结束。
  • Token 计数。包含 thread 的 token 计数请求返回 400 错误。应对完整对话进行计数,并包含 system 和 tools。
  • 压缩。线程不支持按需压缩。带有 thread 的请求如果设置了 compaction 参数,或在携带 compact-2026-09-04 beta 请求头时发送 compaction 块,就会返回 400 错误。请参阅压缩对话。
  • 上下文编辑,但 keep: "all" 的 clear_thinking_20251015 除外。
  • 启用了 HIPAA 就绪的组织。
  • 开启了 Inference hooks 的组织。

API 会以 400 错误和 thread_unsupported_request 错误码拒绝大多数线程不支持的请求。存在 error.details.unsupported 时,它包含以下值之一:

值 含义
context_management 请求使用了线程不支持的上下文管理或压缩。
cache_control 请求包含超过 4 个 cache_control 断点。请参阅线程上的提示词缓存。
fallbacks 请求设置了 fallbacks,但组织无法在线程中使用 fallbacks。
hipaa 组织启用了 HIPAA 就绪。
inference_hooks 组织开启了 Inference hooks。

API 可能会向此列表添加新值。如果遇到不认识的值,请发送完整对话而不使用 thread。请求同时符合多个条件时,错误只会指出其中一个。

限制

定价与速率限制

线程不会改变定价或速率限制。

数据保留

消息线程不符合 ZDR 条件。使用此功能不会影响你使用其他符合 ZDR 条件的功能。API 将线程保留在内存中,使用服务器管理的密钥加密,从不写入持久存储,并在最后一次使用后不超过 1 小时将其删除。

线程保留 API 发送给模型的对话、创建请求中的 system 和 tools,以及固定字段的指纹,供检查后续请求使用。它通过引用保留文件,因此使用线程期间,要确保对话所用的每个文件始终可用。

关于所有功能的 ZDR 资格,请参阅 API 与数据保留。

另请参阅

可用性

消息线程

Claude API

状态 Beta
API Messages API
Beta 请求头 需要
message-threads-2026-08-12
模型 所有模型

Claude Platform on AWS

状态 Beta
API Messages API
Beta 请求头 需要
message-threads-2026-08-12
模型 所有模型

Claude Models on Google Cloud(Anthropic 托管)

状态 Beta
API Messages API
Beta 请求头 需要
message-threads-2026-08-12
模型 所有模型

Microsoft Foundry

状态 Beta
API Messages API
Beta 请求头 需要
message-threads-2026-08-12
模型 所有模型

数据处理

数据处理概览

适用端点

  • 带有 thread 的 /v1/messages

零数据保留

不符合条件

线程的内容(对话、系统提示词和工具)保留在内存中,使用服务器管理的密钥加密,从不写入持久存储,并在最后一次使用后不超过 1 小时将其删除。使用此功能不会影响你使用其他符合 ZDR 条件的功能。了解更多

HIPAA

不符合条件

找你所需

输入关键词,寻找文章、视频、工具、AI技巧或术语。

Esc 关闭搜索