为您的 AI 智能体提供记忆:6 个月的 WhatsApp 聊天记录和联系人
在通过 Coexistence 连接的号码上,如果在连接后 24 小时内将直接 Webhook 目的地保存下来,且企业在应用中同意,Meta 就可以将应用中的联系人以及最多 180 天的一对一聊天记录一次性发送到您的服务器。分块可能乱序到达,进度达到 100 即表示结束。请按 id 存储消息,以 BSUID 为键保存人员信息,并将最近的对话轮次提供给智能体。
easyCoexistence 通过 Meta 的 Coexistence 流程连接号码。
历史同步从入驻起回溯的时间范围;Meta 的功能表称之为最近 6 个月。
入驻后请求联系人和历史记录的时限;每次请求只能发起一次。
标志历史同步已完成的 metadata.progress 值;Meta 表示仅凭 phase 并不能判断。
当企业在 WhatsApp Business 应用中关闭历史记录共享时,历史 Webhook 中出现的错误代码。
第 0 阶段涵盖入驻前第 0 天至第 1 天,第 1 阶段为第 1 天至第 90 天,第 2 阶段为第 90 天至第 180 天。
Meta 发送的最大 Webhook 负载,决定了您的端点所需的请求体大小限制。
导入会带来什么,什么不会带来?
两类数据流,均来自手机上的 WhatsApp Business 应用。联系人以 smb_app_state_sync Webhook 形式到达,每个联系人一条记录,action 取值为 add 或 remove;同一字段也会报告企业之后在应用中新增、编辑或删除的联系人。聊天记录以历史 Webhook 形式到达:入驻前最多 180 天的一对一会话,双向,并附带投递状态。下文列出了不会随导入一并到达的内容,因此基于导入数据构建的记忆不应指望获得这些内容。
如何确保导入数据能到达您的服务器?
在号码连接之前先让端点上线,然后在连接后 24 小时内将其保存为号码的直接 Webhook 目的地:可在号码页面的“Route incoming messages to your own webhook”下设置,或通过您的 AI 调用 set_webhook_destination,或在 Partner API 连接会话中将其设为 webhook_url。保存目的地后,easyCoexistence 才会向 Meta 请求同步,先联系人后历史记录,每次入驻只请求一次;请求及 Meta 的请求 id 会出现在号码的事件日志中,记为 history_sync_requested。
企业在连接过程中,应用询问时必须同意共享历史记录。若号码的消息经由 easyCoexistence 传入(在卡片 Where incoming messages go 中选择 Through easyCoexistence),即便设置了 Forward URL,也不会获得导入,因为请求只针对直接目的地发起。如果之后需要使用自动化,请等导入结束后再切换。
历史记录分块如何到达?
乱序到达,按阶段从最新消息向前回溯:第 0 阶段涵盖入驻前的最后一天,第 1 阶段最多回溯到第 90 天,第 2 阶段最多回溯到第 180 天。若顺序重要,请按 metadata.chunk_order 排序;并将 metadata.progress = 100 视为结束,因为 Meta 指出仅凭 phase 无法判断某个阶段已完成。会话的 id 是客户的电话号码,无法共享时会被省略;其 context 包含 wa_id、user_id 和 username。企业发送的消息,其 from 设为企业号码,并带有 to 字段。
{
"messaging_product": "whatsapp",
"metadata": { "display_phone_number": "16315550142", "phone_number_id": "106540352242922" },
"history": [{
"metadata": { "phase": 1, "chunk_order": 2, "progress": 55 },
"threads": [{
"id": "5511987654321",
"context": { "wa_id": "5511987654321", "user_id": "BR.13491208655302741918" },
"messages": [
{
"from": "5511987654321",
"from_user_id": "BR.13491208655302741918",
"id": "wamid.HBgNNTUxMTk4NzY1NDMyMRUCABIYFDNBMDhFN0QxRjM2QTk4RTU2RTY0AA==",
"timestamp": "1789912800",
"type": "text",
"text": { "body": "Can I pick up the cake on Saturday?" },
"history_context": { "status": "read" }
},
{
"from": "16315550142",
"to": "5511987654321",
"id": "wamid.HBgNNTUxMTk4NzY1NDMyMRUCABEYEjQ2RDhGMkE3QjEwQzNFOTFBMgA=",
"timestamp": "1789913100",
"type": "text",
"text": { "body": "Yes, from 9 am. See you then!" },
"history_context": { "status": "read" }
}
]
}]
}]
}如何存储智能体的记忆?
两张表就够了。人员以 BSUID 为键,即 Meta 添加到联系人、会话和消息中的 user_id,同时保留手机号码,因为带有 username 的用户可能没有手机号码;Meta 自身的参考文档指出应使用 user_id 来识别联系人。消息以其 wamid 为键,因此导入数据、实时 Webhook 以及同一消息的重试投递会合并为一行,并通过 from_business 标记记录发言方。按人员和时间建立索引,因为智能体需要查询某个人最近的几轮对话。
-- One row per person. Key on the BSUID (user_id); keep the phone number beside it.
create table wa_contacts (
user_key text primary key, -- user_id (BSUID) when present, else the phone number
wa_id text, -- phone number in digits, when Meta shares it
username text,
name text, -- full_name from the app's address book
removed boolean not null default false,
updated_at timestamptz not null default now()
);
-- One row per message. The wamid makes history, live events and retries collapse.
create table wa_messages (
id text primary key, -- messages[].id
user_key text not null,
from_business boolean not null,
type text not null, -- text, image, media_placeholder...
body text not null, -- the text, a caption, or a [type] placeholder
sent_at timestamptz not null,
source text not null -- history | live | echo
);
create index wa_messages_by_user on wa_messages (user_key, sent_at desc);如何将分块和联系人加载到记忆中?
使用幂等插入,这样顺序和重复投递都不再影响结果。ingestHistory 读取一条历史变更:记录 2593109 拒绝并继续处理;以 context.user_id 或其 id 为键保存会话;当 from 等于 metadata.display_phone_number 时,将消息标记为企业发出;若无文本,则存储一个 [type] 占位符。ingestContacts 以 user_id 或手机号码为键执行更新或插入(upsert),对已删除的联系人做标记,而不删除其消息。在直接目的地上调用时传入 change.value;当转发的事件为 history 或 smb_app_state_sync 时,则传入请求体中的 value。
// memory.mjs: npm i pg. Feed it the value of a "history" or "smb_app_state_sync"
// change: change.value on a direct destination, delivery.value on a forward.
import pg from "pg";
const db = new pg.Pool(); // reads the PG* environment variables
export async function ingestHistory(value) {
const business = value.metadata?.display_phone_number; // digits, like messages[].from
for (const chunk of value.history ?? []) {
if (chunk.errors?.some((e) => e.code === 2593109)) {
console.log("The business turned off history sharing in the app"); // contacts still come
continue;
}
for (const thread of chunk.threads ?? []) {
const userKey = thread.context?.user_id ?? thread.id; // thread.id is the phone, when shared
for (const m of thread.messages ?? []) {
await db.query(
`insert into wa_messages (id, user_key, from_business, type, body, sent_at, source)
values ($1, $2, $3, $4, $5, to_timestamp($6), 'history')
on conflict (id) do nothing`,
[m.id, userKey, m.from === business, m.type,
m.text?.body ?? m[m.type]?.caption ?? `[${m.type}]`, Number(m.timestamp)]
);
}
}
const { phase, chunk_order, progress } = chunk.metadata ?? {};
console.log(`history: phase ${phase}, chunk ${chunk_order}, ${progress}%`);
if (Number(progress) === 100) console.log("Import complete; late chunks still insert safely");
}
}
export async function ingestContacts(value) {
for (const s of value.state_sync ?? []) {
const c = s.type === "contact" ? s.contact ?? {} : null;
const userKey = c && (c.user_id ?? c.phone_number);
if (!userKey) continue;
await db.query(
`insert into wa_contacts (user_key, wa_id, username, name, removed)
values ($1, $2, $3, $4, $5)
on conflict (user_key) do update set
wa_id = coalesce(excluded.wa_id, wa_contacts.wa_id),
username = coalesce(excluded.username, wa_contacts.username),
name = coalesce(excluded.name, wa_contacts.name),
removed = excluded.removed, updated_at = now()`,
[userKey, c.phone_number ?? null, c.username ?? null, c.full_name ?? c.first_name ?? null,
s.action === "remove"]
);
}
}
// A bounded memory for one person: who they are and their last turns, oldest first.
export async function memoryFor(userKey, turns = 20) {
const [{ rows: [contact] }, { rows }] = await Promise.all([
db.query("select name from wa_contacts where user_key = $1 and not removed", [userKey]),
db.query(
`select from_business, body from wa_messages
where user_key = $1 order by sent_at desc limit $2`, [userKey, turns]),
]);
const history = rows.reverse().map((r) => ({ role: r.from_business ? "assistant" : "user", content: r.body }));
while (history[0]?.role === "assistant") history.shift(); // open on the customer's turn
const who = contact?.name ? `The customer is ${contact.name}.` : "The customer is not in the address book.";
return { system: `${process.env.AI_INSTRUCTIONS ?? ""}\n${who}`.trim(), history };
}如何把记忆提供给智能体?
有限量提供,而不是一次全部提供。memoryFor 返回该人员在通讯录中的姓名,以及最近 20 轮对话,按从旧到新排序,并以客户的一轮开头,符合大多数聊天 API 的预期;如果智能体需要更多内容,可以加入较早对话的已存摘要。把 6 个月的聊天记录放进每个提示中,每次回复都会消耗令牌,还会淹没正在提出的问题。
作为对比,内置的“Reply with AI”步骤最多读取此前 20 条消息(默认 10 条),而“Call my webhook”步骤发送最近 10 条。两者都依赖按所有者所选保留期保存的文本,可选 30、90 或 365 天(默认 90 天),即自动化开启之时起算,因此这六个月的已导入聊天记录必须保存在您自己的数据库中。
导入之后,记忆如何保持最新?
同一目的地会持续接收实时流量:客户发来的消息、在应用中输入的回复所对应的 smb_message_echoes,以及企业编辑联系人时的 smb_app_state_sync。请通过同样的表插入这些数据,并将来源标记为 live 或 echo。当客户更换手机号码时,Meta 会发送类型为 user_changed_number 或 user_changed_user_id 的系统消息,其中带有 previous_user_id,提示您将其记录迁移到新的 BSUID。
之后开启自动化会移除直接目的地。请将同一 URL 添加为 Forward URL,并从每个已签名的 POST 请求中读取 event 和 value。请等到 progress 达到 100 再切换,否则剩余分块只能通过该转发到达。
设置方法
- Put the endpoint onlineIt must return hub.challenge as plain text on Meta's GET handshake when hub.verify_token matches, accept POST bodies of a few megabytes and answer 200 fast.
- Connect the numberRun the connection from the dashboard, and accept sharing chat history when the WhatsApp Business app asks.
- Save the destination within 24 hoursOn the number's page, under Route incoming messages to your own webhook, fill Webhook URL (with a long random path) and Verify token, then Save; or ask your AI to call set_webhook_destination.
- Store chunks until progress 100Insert contacts and messages as they come; the event log shows history_sync_requested once the request went to Meta.
- Switch modes only afterwardsIf you want automations, choose Through easyCoexistence in the card Where incoming messages go and add the same URL as the Forward URL.
常见错误
- 在第二天才保存目的地。同步只会在连接后 24 小时内请求,因此之后才保存的端点只会收到实时消息。
- 在进度达到 100 之前开启自动化。直接目的地会立即被移除,只有事先设置了 Forward URL,后续分块才能到达您这里。
- 把第 2 阶段当作导入结束。只有 metadata.progress = 100 才表示同步完成,而且分块并不按顺序投递。
- 仅以手机号码作为记忆的键。当带有 username 的用户无法共享手机号码时,会话 id 和联系人不再包含手机号码,但 user_id 仍然存在。
如果您在 24 小时内将端点保存为直接 Webhook 目的地,它便会向 Meta 请求一次联系人以及最多 180 天的聊天记录,这些数据会直接发送到您的服务器。该请求会记录在号码的事件日志中,之后号码将全天候 24/7 受到监控。每个已连接号码每月 US$ 9 起,号码越多越便宜,最低降至 US$ 0.75,并提供 3 天免费试用。
常见问题
导入可以再运行一次吗?
只能通过新的入驻流程进行。Meta 每次入驻只允许请求一次,因此必须断开号码后重新连接,聊天记录随之会再次到达。按消息 id 插入可以防止第二次导入时重复添加任何内容。
easyCoexistence 会保存导入聊天记录的副本吗?
不会。历史记录和联系人直接从 Meta 发送到您的端点,默认不予存储。对于开启了自动化的号码,easyCoexistence 会按您选择的期限保存消息文本,可选 30、90 或 365 天(默认 90 天),并在“对话”界面中显示;转发的投递最多保存 7 天,运行日志保存 30 天。
负载可以有多大?
单个 Meta Webhook 最多可以包含 3 MB,而繁忙的号码会发送许多历史分块。请提高框架的请求体限制(Express 默认为 100 kb),并先确认接收,再写入数据库。
智能体一定需要导入才能运行吗?
不需要。没有导入时,记忆从连接后的第一条消息开始,并随实时流量增长。当过往对话需要从第一天起就影响回答时,导入才有意义,例如返回客户的上一笔订单。
继续阅读
准备开始了吗?
几分钟即可设置 WhatsApp Coexistence,而不是几个月。应用会继续在手机上运行。
开始免费试用验证时间