ログイン無料トライアルを開始
Meta Tech Provider

AI エージェントにメモリを持たせる:WhatsApp の 6 か月分のチャットと連絡先

Coexistence で接続した番号では、接続から 24 時間以内に直接の Webhook 送信先が保存され、ビジネス側がアプリで同意していれば、Meta は WhatsApp Business アプリの連絡先と最大 180 日間の 1 対 1 チャットを、一度だけお使いのサーバーに送信できます。チャンクは順不同で届くことがあり、progress 100 が完了を示します。メッセージは id で、相手は BSUID で保存し、直近のやり取りをエージェントに渡してください。

easyCoexistence は、Meta の Coexistence フローで番号を接続します。

180 days

オンボーディング時点から履歴同期が遡る期間。Meta の機能表では直近 6 か月と記載されています。

24 hours

オンボーディング後、連絡先と履歴をリクエストできるまでの時間。各リクエストは 1 回に限られます。

100

履歴同期が完了したことを示す metadata.progress の値。Meta は phase だけでは完了とみなせないとしています。

2593109

WhatsApp Business アプリで履歴の共有をオフにしている場合に、履歴 Webhook に含まれるエラーコード。

3 phases

phase 0 はオンボーディング前の 0 日目から 1 日目、phase 1 は 1 日目から 90 日目、phase 2 は 90 日目から 180 日目までを対象とします。

3 MB

Meta が送信する Webhook ペイロードの最大サイズ。エンドポイントに必要なボディサイズの上限を決めます。

インポートで届くものと残るもの

データは、スマートフォン上の WhatsApp Business アプリから 2 つの流れで届きます。連絡先は smb_app_state_sync Webhook として届き、連絡先 1 件につき 1 エントリーで、action は add または remove です。同じフィールドで、ビジネス側がアプリで後から追加、編集、削除した連絡先も報告され続けます。チャットは履歴 Webhook として届きます。対象はオンボーディングの最大 180 日前までの 1 対 1 の会話で、双方向のメッセージと配信ステータスを含みます。届かないものは以下に示しますので、インポートに基づくメモリでは、それらを前提にしないでください。

Contactsfull_name, first_name, phone_number, user_id (BSUID), username
One-to-one chatsUp to 180 days, sent and received, grouped by conversation
Message statushistory_context.status: sent, delivered, read, played, pending or error
Mediamedia_placeholder without the file; separate webhooks carry ids for media from about the last 14 days
Group chatsNot included
App toolsLabels, quick replies, greeting and away messages stay on the phone

インポートをサーバーに確実に届かせる方法

接続前にエンドポイントを稼働させておき、番号の接続から 24 時間以内に、その番号の直接 Webhook 送信先として保存してください。保存する場所は 3 つあります。番号のページにある「受信メッセージを自分の Webhook にルーティング」、AI からの set_webhook_destination、または Partner API の接続セッションの webhook_url です。保存すると easyCoexistence が Meta にリクエストを送り、まず連絡先、次に履歴の順に、オンボーディングごとに 1 回だけ同期されます。リクエストと Meta のリクエスト ID は、番号のイベントログに history_sync_requested として表示されます。

接続中にアプリが共有を求めたら、ビジネス側は履歴の共有に同意する必要があります。メッセージが easyCoexistence を経由する番号(「Where incoming messages go」カードの「Through easyCoexistence」)は、Forward URL があっても取り込みを受けられません。リクエストは直接の送信先の場合にのみ行われるためです。後から自動化が必要になった場合は、取り込みの完了後に切り替えてください。

履歴チャンクの届き方

順不同で、直近のメッセージから過去へさかのぼるフェーズで届きます。phase 0 はオンボーディング直前の 1 日分、phase 1 は 90 日目まで、phase 2 は 180 日目までを対象とします。順序が重要な場合は metadata.chunk_order で並べ替え、終了の判定には metadata.progress = 100 を使ってください。Meta は、phase だけでは完了を示せないと注意しています。会話の id は顧客の電話番号ですが、共有できない場合は省かれます。その context には wa_id、user_id、username が含まれます。ビジネスが送ったメッセージには、from にビジネス番号が設定され、to フィールドがあります。

history webhook value, trimmed
{
  "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" }
        }
      ]
    }]
  }]
}

エージェントのメモリの保存方法

2 つのテーブルで十分です。人は BSUID をキーにします。BSUID は Meta が連絡先、会話、メッセージに付与する user_id で、横に電話番号を保持します。ユーザー名のあるユーザーは電話番号なしで届く場合があるためです。Meta の公式リファレンスでも、連絡先の特定には user_id を使うよう書かれています。メッセージは wamid をキーとするので、インポート、ライブの Webhook、再送された同じメッセージは 1 行にまとまります。from_business フラグで発言者を記録します。人と時刻でインデックスを作成してください。エージェントは一人の直近のやり取りを必要とするためです。

memory.sql (PostgreSQL)
-- 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 は履歴の変更 1 件を読み込みます。2593109 の拒否をログに記録して次へ進みます。会話は context.user_id またはその id をキーにします。from が metadata.display_phone_number と等しい場合、そのメッセージをビジネスのものとしてマークし、テキストがない場合は [type] のプレースホルダーを保存します。ingestContacts は user_id または電話番号で upsert し、削除された連絡先は、そのメッセージを削除せずフラグを立てます。直接の送信先では change.value を渡し、転送の event が history または smb_app_state_sync の場合は、ボディの value を渡して呼び出してください。

memory.mjs: ingest and recall (Node.js, pg)
// 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 は type が user_changed_number または user_changed_user_id のシステムメッセージを送信します。previous_user_id を伴うため、その人の行を新しい BSUID に移すきっかけになります。

後から自動化をオンにすると、直接の送信先は削除されます。同じ URL を Forward URL として追加し、署名付きの各 POST から event と value を読み取ってください。切り替える前に progress 100 を待ってください。待たないと、残りのチャンクは転送経由でしか届きません。

設定方法

  1. 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.
  2. Connect the numberRun the connection from the dashboard, and accept sharing chat history when the WhatsApp Business app asks.
  3. 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.
  4. Store chunks until progress 100Insert contacts and messages as they come; the event log shows history_sync_requested once the request went to Meta.
  5. 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.

よくある間違い

  • 2 日目に送信先を保存すること。同期は接続から 24 時間以内にしかリクエストされないため、後で保存したエンドポイントは、ライブのメッセージからしか始まりません。
  • progress が 100 に達する前に自動化をオンにすること。直接の送信先は直ちに削除され、後続のチャンクは Forward URL がすでに設定されている場合にしか届きません。
  • phase 2 をインポートの完了とみなすこと。完了を示すのは metadata.progress = 100 だけで、チャンクは順番どおりには届きません。
  • メモリを電話番号だけでキーにすること。ユーザー名を持つユーザーが電話番号を共有できない場合、会話の id と連絡先から電話番号が抜けますが、user_id は残っています。
EasyCoexistence で実現する

接続から 24 時間以内にエンドポイントを直接の Webhook 送信先として保存すると、連絡先と最大 180 日間のチャットを一度だけ Meta にリクエストし、データはお使いのサーバーに直接届きます。リクエストは番号のイベントログに記録され、その後は番号を 24 時間体制で監視します。料金は番号 1 件あたり月額 US$ 9 から、番号を増やすほど下がり US$ 0.75 まで。最初の 3 日間は無料です。

よくある質問

インポートを 2 回実行できますか?

新しいオンボーディングを行った場合のみです。Meta はオンボーディングごとに 1 回のリクエストしか許可しないため、番号を一度切断して再接続する必要があり、チャットも再び届きます。メッセージ id で挿入すれば、2 回目の取り込みで同じデータが二重に追加されることはありません。

easyCoexistence はインポートしたチャットのコピーを保持しますか?

いいえ。履歴と連絡先は Meta からお使いのエンドポイントへ直接送られ、既定では保存されません。自動化がオンの番号では、easyCoexistence はメッセージテキストを選択した期間(30 日、90 日、365 日、既定は 90 日)保持し、Conversations 画面に表示されます。転送された配信は最大 7 日間、実行ログは 30 日間保持されます。

ペイロードはどのくらい大きくなりますか?

1 件の Meta Webhook は最大 3 MB になることがあり、利用の多い番号は多くの履歴チャンクを送ります。フレームワークのボディサイズ上限を引き上げ(Express の既定値は 100 kb)、データベースに書き込む前に受信応答を返してください。

エージェントが機能するにはインポートが必要ですか?

いいえ。インポートがなくても、メモリは接続後の最初のメッセージから始まり、ライブのトラフィックから増えていきます。インポートが役立つのは、過去のやり取りを初日から回答に反映させたい場合です。たとえば、リピーターのお客様の直近のご注文などです。

続きを読む

始める準備はできましたか?

WhatsApp Coexistence の設定は数分で完了し、数か月もかかりません。スマートフォン上のアプリも引き続き使えます。

無料トライアルを始める

確認日