為你的 AI 代理加入記憶:匯入 6 個月的 WhatsApp 對話與聯絡人
在透過 Coexistence 連接的號碼上,若在連接後 24 小時內儲存了直接 webhook 目的地,且企業在 WhatsApp Business 應用程式中同意,Meta 便會一次性將聯絡人,以及最多 180 天的一對一對話送至你的伺服器。分段可能亂序抵達,進度達 100 即代表結束。請以訊息 id 儲存訊息,以 BSUID 記錄人物,並將最近的對話輪次提供給代理。
easyCoexistence 透過 Meta 的 Coexistence 流程連接號碼;當你把端點儲存為直接 webhook 目的地(連接後 24 小時內),便會向 Meta 請求一次聯絡人及最多 180 天的對話,並直接送至你的伺服器。
歷史同步從入職起回溯的範圍;Meta 的功能表稱為最近 6 個月。
入職後請求聯絡人與歷史的時限;每項請求只能提出一次。
標示歷史同步已完成的 metadata.progress 值;Meta 表示階段本身並不足以判斷。
企業在 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 目的地:在號碼頁面的「將收到的訊息路由至你自己的 webhook」下設定,或透過 AI 使用 set_webhook_destination,或在 Partner API 連接工作階段中以 webhook_url 設定。儲存之後,easyCoexistence 便會向 Meta 請求同步,先聯絡人,後歷史,每次入職一次;請求及 Meta 的請求 id 會在號碼的事件記錄中以 history_sync_requested 顯示。
企業在連接過程中,應用程式請求時必須同意分享歷史。若號碼的訊息經由 easyCoexistence 傳送(即「收到的訊息送往何處」卡片中的「經由 easyCoexistence」),即使設有 Forward URL,也不會有匯入,因為請求只會為直接目的地而發出。若日後需要自動化,請在匯入結束後再切換。
歷史分段如何抵達?
亂序抵達,分階段由最新的訊息往回送:階段 0 涵蓋入職前的最後一天,階段 1 最遠至第 90 天,階段 2 最遠至第 180 天。若順序重要,請按 metadata.chunk_order 排序;並將 metadata.progress = 100 視為結束,因為 Meta 提醒階段本身並不代表某階段已完成。對話的 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 個月的對話,會令每次回覆都耗用權杖,並淹沒正在被問的問題。
作為比較,內建的「以 AI 回覆」步驟最多讀取 20 則較早的訊息(預設 10 則),而「呼叫我的 webhook」步驟則送出最後 10 則。兩者都取用依擁有者所選保留期限保存的文字,可選 30、90 或 365 天(預設 90 天),即自動化開啟那一刻起的內容,因此已匯入的 6 個月聊天必須存放在你自己的資料庫中。
匯入之後,記憶如何保持最新?
同一目的地會持續收到即時流量:來自客戶的訊息、透過應用程式輸入的回覆所對應的 smb_message_echoes,以及企業在應用程式中編輯聯絡人時的 smb_app_state_sync。以 source 為 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/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,而非幾個月。應用程式在手機上仍可繼續運作。
開始免費試用驗證日期