做梦

让 Claude 反思过去的会话,以策展智能体的记忆并发现新的洞察。


Tip

做梦是研究预览功能。请求访问以试用。

智能体在工作时会写入它们的记忆存储,但这些写入是本地和增量的:经过多次会话后,记忆存储会积累重复、矛盾和过时的条目。

做梦让 Claude 可以清理这些内容。做梦会读取现有的记忆存储以及过去的会话记录,然后生成一个新的、重新组织的记忆存储:重复项被合并,过时或矛盾的条目被最新值替换,并发现新的洞察。

输入存储永远不会被修改,因此您可以查看输出,如果不喜欢结果可以丢弃它。

Note

所有托管智能体 API 请求都需要 managed-agents-2026-04-01 beta 头。做梦还需要 dreaming-2026-04-21 beta 头。SDK 会自动设置这些。

工作原理

做梦是一个异步作业,接收:

  • 一个预先存在的记忆存储:Claude 验证、去重和重新组织的存储,以及
  • 1 到 100 个会话:Claude 挖掘模式和洞察以融入输出的过去记录。

做梦生成另一个输出记忆存储,与输入分开。输出存储 ID 在做梦开始 running 后出现在做梦的 outputs[] 中。

创建做梦

dream=$(curl -s https://api.anthropic.com/v1/dreams \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21" \
  -H "content-type: application/json" \
  --data @- <<EOF
{
  "inputs": [
    { "type": "memory_store", "memory_store_id": "$store_id" },
    { "type": "sessions", "session_ids": ["$session_a", "$session_b"] }
  ],
  "model": "claude-opus-4-7",
  "instructions": "Focus on coding-style preferences; ignore one-off debugging notes."
}
EOF
)
dream_id=$(jq -r '.id' <<< "$dream")
echo "$dream_id"  # drm_01...
dream_id=$(ant beta:dreams create --transform id --raw-output <<YAML
inputs:
  - type: memory_store
    memory_store_id: $store_id
  - type: sessions
    session_ids: [$session_a, $session_b]
model: claude-opus-4-7
instructions: Focus on coding-style preferences; ignore one-off debugging notes.
YAML
)
dream = client.beta.dreams.create(
    inputs=[
        {"type": "memory_store", "memory_store_id": store_id},
        {"type": "sessions", "session_ids": [session_a, session_b]},
    ],
    model="claude-opus-4-7",
    instructions="Focus on coding-style preferences; ignore one-off debugging notes.",
)
print(dream.id)  # drm_01...
let dream = await client.beta.dreams.create({
  inputs: [
    { type: "memory_store", memory_store_id: storeId },
    { type: "sessions", session_ids: [sessionA, sessionB] },
  ],
  model: "claude-opus-4-7",
  instructions: "Focus on coding-style preferences; ignore one-off debugging notes.",
});
console.log(dream.id); // drm_01...
var dream = await client.Beta.Dreams.Create(new()
{
    Inputs =
    [
        new BetaDreamMemoryStoreInput
        {
            Type = BetaDreamMemoryStoreInputType.MemoryStore,
            MemoryStoreID = storeID,
        },
        new BetaDreamSessionsInput
        {
            Type = BetaDreamSessionsInputType.Sessions,
            SessionIds = [sessionA, sessionB],
        },
    ],
    Model = "claude-opus-4-7",
    Instructions = "Focus on coding-style preferences; ignore one-off debugging notes.",
});
Console.WriteLine(dream.ID);  // drm_01...
dream, err := client.Beta.Dreams.New(ctx, anthropic.BetaDreamNewParams{
	Inputs: []anthropic.BetaDreamInputUnionParam{
		anthropic.BetaDreamInputParamOfMemoryStore(storeID),
		anthropic.BetaDreamInputParamOfSessions([]string{sessionA, sessionB}),
	},
	Model: anthropic.BetaDreamModelParamsUnion{
		OfString: anthropic.String("claude-opus-4-7"),
	},
	Instructions: anthropic.String("Focus on coding-style preferences; ignore one-off debugging notes."),
})
if err != nil {
	panic(err)
}
fmt.Println(dream.ID) // drm_01...
var dream = client.beta().dreams().create(
    DreamCreateParams.builder()
        .addMemoryStoreInput(storeId)
        .addSessionsInput(List.of(sessionA, sessionB))
        .model("claude-opus-4-7")
        .instructions("Focus on coding-style preferences; ignore one-off debugging notes.")
        .build()
);
IO.println(dream.id());  // drm_01...
$dream = $client->beta->dreams->create(
    inputs: [
        ['type' => 'memory_store', 'memory_store_id' => $storeId],
        ['type' => 'sessions', 'session_ids' => [$sessionA, $sessionB]],
    ],
    model: 'claude-opus-4-7',
    instructions: 'Focus on coding-style preferences; ignore one-off debugging notes.',
);
echo "{$dream->id}\n"; // drm_01...
dream = client.beta.dreams.create(
  inputs: [
    {type: "memory_store", memory_store_id: store_id},
    {type: "sessions", session_ids: [session_a, session_b]}
  ],
  model: "claude-opus-4-7",
  instructions: "Focus on coding-style preferences; ignore one-off debugging notes."
)
puts dream.id # drm_01...

做梦输入包括预先存在的记忆存储和会话数组。所选模型将运行做梦管道;在研究预览期间支持 claude-opus-4-7claude-sonnet-4-6。您还可以在 instructions 中提供关于做梦运行执行的额外指导。

响应是完整的 dream 资源,status: "pending"

{
  "type": "dream",
  "id": "drm_01AbCDefGhIjKlMnOpQrStUv",
  "status": "pending",
  "inputs": [
    { "type": "memory_store", "memory_store_id": "memstore_01Hx..." },
    { "type": "sessions", "session_ids": ["sesn_01...", "sesn_02..."] }
  ],
  "outputs": [],
  "model": { "id": "claude-opus-4-7" },
  "instructions": "Focus on coding-style preferences; ignore one-off debugging notes.",
  "session_id": null,
  "created_at": "2026-04-29T17:04:10Z",
  "ended_at": null,
  "archived_at": null,
  "usage": {
    "input_tokens": 0,
    "output_tokens": 0,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  },
  "error": null
}
Tip

如果您只有会话记录而没有现有存储,请先创建空记忆存储并将其作为 memory_store 输入传递。

跟踪进度

做梦异步运行,通常需要几分钟到几十分钟,具体取决于输入大小。按 ID 轮询做梦以检查状态:

while true; do
  dream=$(curl -s "https://api.anthropic.com/v1/dreams/$dream_id" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21")
  status=$(jq -r '.status' <<< "$dream")
  echo "status=$status input_tokens=$(jq -r '.usage.input_tokens' <<< "$dream")"
  [[ "$status" == "pending" || "$status" == "running" ]] || break
  sleep 10
done
ant beta:dreams retrieve --dream-id "$dream_id"
while dream.status in ("pending", "running"):
    time.sleep(10)
    dream = client.beta.dreams.retrieve(dream.id)
    print(f"status={dream.status} input_tokens={dream.usage.input_tokens}")
while (dream.status === "pending" || dream.status === "running") {
  await sleep(10_000);
  dream = await client.beta.dreams.retrieve(dream.id);
  console.log(`status=${dream.status} input_tokens=${dream.usage.input_tokens}`);
}
while (dream.Status.Value() is BetaDreamStatus.Pending or BetaDreamStatus.Running)
{
    await Task.Delay(TimeSpan.FromSeconds(10));
    dream = await client.Beta.Dreams.Retrieve(dream.ID);
    Console.WriteLine({{CONTENT}}quot;status={dream.Status.Raw()} input_tokens={dream.Usage.InputTokens}");
}
for dream.Status == anthropic.BetaDreamStatusPending || dream.Status == anthropic.BetaDreamStatusRunning {
	time.Sleep(10 * time.Second)
	dream, err = client.Beta.Dreams.Get(ctx, dream.ID, anthropic.BetaDreamGetParams{})
	if err != nil {
		panic(err)
	}
	fmt.Printf("status=%s input_tokens=%d\n", dream.Status, dream.Usage.InputTokens)
}
while (dream.status().equals(BetaDreamStatus.PENDING)
        || dream.status().equals(BetaDreamStatus.RUNNING)) {
    Thread.sleep(10_000);
    dream = client.beta().dreams().retrieve(dream.id());
    IO.println("status=" + dream.status() + " input_tokens=" + dream.usage().inputTokens());
}
while (in_array($dream->status, [BetaDreamStatus::PENDING->value, BetaDreamStatus::RUNNING->value], true)) {
    sleep(10);
    $dream = $client->beta->dreams->retrieve($dream->id);
    echo "status={$dream->status} input_tokens={$dream->usage->inputTokens}\n";
}
while %i[pending running].include?(dream.status)
  sleep 10
  dream = client.beta.dreams.retrieve(dream.id)
  puts "status=#{dream.status} input_tokens=#{dream.usage.input_tokens}"
end

生命周期

status含义
pending做梦成功创建并排队。
running管道正在处理。usage 随工作进展而更新。
completed成功完成。outputs[] 值是新的记忆存储。
failed做梦运行因错误终止。输出记忆存储保留失败前写入的内容。
canceled做梦运行已取消。输出记忆存储保留现有内容。

观看管道运行

做梦进入 running 状态后,其 session_id 字段指向执行管道的底层会话。您可以流式传输该会话的事件以实时观察做梦正在读取和写入的内容。当做梦达到终止状态时,会话会被归档(不是删除),因此记录之后仍然可用。

使用输出

status 达到 completed 时,outputs[] 中的 memory_store 条目引用一个完全填充的存储。它是您工作区中的普通记忆存储。使用记忆存储 API 或在控制台中查看它,然后:

  • 利用它: 将其作为 memory_store 资源附加到未来的会话,替代(或 alongside)输入记忆存储,或
  • 丢弃它: 删除归档它。
# 做梦结束后,memory_store 输出保存重建的存储
output_store_id=$(jq -r 'first(.outputs[] | select(.type == "memory_store")).memory_store_id' <<< "$dream")

curl -s https://api.anthropic.com/v1/sessions \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "content-type: application/json" \
  --data @- <<EOF
{
  "agent": "$agent_id",
  "environment_id": "$environment_id",
  "resources": [
    { "type": "memory_store", "memory_store_id": "$output_store_id" }
  ]
}
EOF
output_store_id=$(ant beta:dreams retrieve --dream-id "$dream_id" --format json |
  jq -r 'first(.outputs[] | select(.type == "memory_store")).memory_store_id')

ant beta:sessions create <<YAML
agent: $agent_id
environment_id: $environment_id
resources:
  - type: memory_store
    memory_store_id: $output_store_id
YAML
# 做梦结束后,输出保存重建的记忆存储
output_store_id = next(
    output.memory_store_id for output in dream.outputs if output.type == "memory_store"
)

session = client.beta.sessions.create(
    agent=agent_id,
    environment_id=environment_id,
    resources=[
        {"type": "memory_store", "memory_store_id": output_store_id},
    ],
)
// 做梦结束后,输出保存重建的记忆存储
const output = dream.outputs.find((entry) => entry.type === "memory_store");
const outputStoreId = output!.memory_store_id;

await client.beta.sessions.create({
  agent: agentId,
  environment_id: environmentId,
  resources: [
    { type: "memory_store", memory_store_id: outputStoreId },
  ],
});
var output = dream.Outputs.FirstOrDefault(entry => entry.Type == "memory_store");
if (output is { MemoryStoreID: var outputStoreID })
{
    await client.Beta.Sessions.Create(new()
    {
        Agent = agentID,
        EnvironmentID = environmentID,
        Resources =
        [
            new BetaManagedAgentsMemoryStoreResourceParam
            {
                Type = BetaManagedAgentsMemoryStoreResourceParamType.MemoryStore,
                MemoryStoreID = outputStoreID,
            },
        ],
    });
}
for _, output := range dream.Outputs {
	if output.Type != "memory_store" {
		continue
	}
	outputStoreID := output.MemoryStoreID

	session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
		Agent: anthropic.BetaSessionNewParamsAgentUnion{
			OfString: anthropic.String(agentID),
		},
		EnvironmentID: environmentID,
		Resources: []anthropic.BetaSessionNewParamsResourceUnion{{
			OfMemoryStore: &anthropic.BetaManagedAgentsMemoryStoreResourceParam{
				MemoryStoreID: outputStoreID,
			},
		}},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(session.ID)
	break
}
var output = dream.outputs().stream()
    .filter(entry -> entry.type().equals(BetaDreamOutput.Type.MEMORY_STORE))
    .findFirst();
if (output.isPresent()) {
    var outputStoreId = output.get().memoryStoreId();

    var session = client.beta().sessions().create(
        SessionCreateParams.builder()
            .agent(agentId)
            .environmentId(environmentId)
            .addMemoryStoreResource(outputStoreId)
            .build()
    );
}
$matches = array_filter($dream->outputs, fn($output) => $output->type === 'memory_store');
$output = $matches ? reset($matches) : null;
if ($output !== null) {
    $session = $client->beta->sessions->create(
        agent: $agentId,
        environmentID: $environmentId,
        resources: [
            ['type' => 'memory_store', 'memory_store_id' => $output->memoryStoreID],
        ],
    );
}
output = dream.outputs.find { it.type == :memory_store }
if output
  client.beta.sessions.create(
    agent: agent_id,
    environment_id: environment_id,
    resources: [
      {type: "memory_store", memory_store_id: output.memory_store_id}
    ]
  )
end

做梦本身永远不会删除或修改其输入。在 failedcanceled 时,输出存储会保留部分内容,以便您可以在停止前检查生成了什么;如果不需要,请通过记忆存储 API 清理它。

Warning

当做梦处于 pendingrunning 状态时,归档或删除其输出存储会被 400 拒绝。在运行期间归档或删除输入存储或会话将导致做梦以 input_memory_store_unavailableinput_session_unavailable 失败。

取消做梦

取消会立即将 pendingrunning 的做梦移动到 canceled。取消已经 canceled 的做梦是幂等的无操作;取消 completedfailed 的做梦返回 400。

curl -s -X POST "https://api.anthropic.com/v1/dreams/$dream_id/cancel" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21"
ant beta:dreams cancel --dream-id "$dream_id"
client.beta.dreams.cancel(dream.id)
await client.beta.dreams.cancel(dream.id);
await client.Beta.Dreams.Cancel(dream.ID);
dream, err = client.Beta.Dreams.Cancel(ctx, dream.ID, anthropic.BetaDreamCancelParams{})
if err != nil {
	panic(err)
}
client.beta().dreams().cancel(dream.id());
$client->beta->dreams->cancel($dream->id);
client.beta.dreams.cancel(dream.id)

归档做梦

归档会对已达到终止状态(completedfailedcanceled)的做梦设置 archived_atstatus 保持不变。已归档的做梦默认从列表响应中排除,但仍可通过 ID 读取。归档已经归档的做梦是幂等的无操作。归档 pendingrunning 的做梦返回 400;请先取消它。没有取消归档。

curl -s -X POST "https://api.anthropic.com/v1/dreams/$dream_id/archive" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21"
ant beta:dreams archive --dream-id "$dream_id"
client.beta.dreams.archive(dream.id)
await client.beta.dreams.archive(dream.id);
await client.Beta.Dreams.Archive(dream.ID);
dream, err = client.Beta.Dreams.Archive(ctx, dream.ID, anthropic.BetaDreamArchiveParams{})
if err != nil {
	panic(err)
}
client.beta().dreams().archive(dream.id());
$client->beta->dreams->archive($dream->id);
client.beta.dreams.archive(dream.id)

归档做梦不会触动其输出记忆存储;通过记忆存储 API单独管理它。

列出做梦

返回工作区中所有未归档的做梦,最新的在前。使用 limit(默认 20,最大 100)和 page 游标进行分页。传递 include_archived=true 以包含已归档的做梦。

curl -s "https://api.anthropic.com/v1/dreams?limit=20" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21"
ant beta:dreams list --limit 20
for listed_dream in client.beta.dreams.list(limit=20):
    print(listed_dream.id, listed_dream.status)
for await (const listedDream of client.beta.dreams.list({ limit: 20 })) {
  console.log(listedDream.id, listedDream.status);
}
var page = await client.Beta.Dreams.List(new() { Limit = 20 });
await foreach (var listed in page.Paginate())
{
    Console.WriteLine({{CONTENT}}quot;{listed.ID} {listed.Status.Raw()}");
}
dreams := client.Beta.Dreams.ListAutoPaging(ctx, anthropic.BetaDreamListParams{
	Limit: anthropic.Int(20),
})
for dreams.Next() {
	listed := dreams.Current()
	fmt.Println(listed.ID, listed.Status)
}
if err := dreams.Err(); err != nil {
	panic(err)
}
for (var listedDream : client.beta().dreams().list(
    DreamListParams.builder().limit(20).build()
).autoPager()) {
    IO.println(listedDream.id() + " " + listedDream.status());
}
foreach ($client->beta->dreams->list(limit: 20)->pagingEachItem() as $dream) {
    echo "{$dream->id} {$dream->status}\n";
}
client.beta.dreams.list(limit: 20).auto_paging_each do
  puts "#{it.id} #{it.status}"
end

错误

以下是可能的做梦错误的非详尽列表。

error.type何时
timeout管道超出其运行时预算。
internal_error未分类的管道故障。
memory_store_org_limit_exceeded您的组织在管道配置工作存储时达到其记忆存储上限。
input_memory_store_too_large输入记忆存储超出管道的大小限制。
input_memory_store_unavailable输入记忆存储在做梦创建后被归档或删除。
input_session_unavailable输入会话在做梦创建后被归档或删除。

计费

做梦按您选择的模型的标准 API token 费率计费;资源上的 usage 报告确切的总数。成本大致随输入会话的数量和长度线性扩展。从一小批会话开始,一旦您对策展质量满意就扩大规模。

限制

限制
每个做梦的会话数100
instructions 长度4,096 个字符
支持的模型claude-opus-4-7claude-sonnet-4-6

当此功能处于 beta 阶段时,默认速率限制适用于做梦创建。如果您需要更高的限制,请联系支持