Agentic AI 工具調用:如何設計不易被智能體誤用的工具
Tool Use in Agentic AI: Designing Tools Your Agent Won’t Misuse
文章提出跨 WhatsApp、Instagram 和 Telegram 建立統一客戶檔案,並透過受限的工具調用讓 AI 智能體使用相關資料。各渠道身份只在資料經驗證後才合併,並保留復原方式。提供給智能體的工具應採唯讀、最少資料原則,由伺服器注入 customer_id,不讓模型直接存取資料庫。
Table of Contents
- What Is a Unified Customer Profile?
- Why Each Channel Gives You a Different Identity
- The Data Model
- Identity Resolution: Linking the Same Person
- Building the Single Customer View
- Syncing Data to Your CRM
- Giving AI Agents Access Through Tool Calling
- Pitfalls to Avoid
- Conclusion
What Is a Unified Customer Profile?
A unified customer profile (also called a single customer view) is one record that represents one real person, no matter which channel they used to reach you. It combines their identities, conversation history, attributes, tags, and consent status into a single unified customer database entry.
Without it, you get duplicate contacts, repeated questions ("What's your order number?" asked three times), and broadcasts that hit the same person on three channels.
Note: A unified profile is not a bigger contact table. It is a graph: one person node connected to many channel identities.
Why Each Channel Gives You a Different Identity
The core problem is that every platform identifies users differently, and none of them hands you a universal ID.
| Channel | Primary identifier | What you usually get |
|---|---|---|
Phone number (wa_id) |
Phone, profile name | |
| Instagram-scoped ID (IGSID) | Username, name; no phone or email by default | |
| Telegram |
chat_id / user ID |
Name, optional username; phone only if the user shares it |
That means:
- WhatsApp gives you a strong identifier (the phone number).
- Instagram and Telegram give you platform-scoped IDs that mean nothing outside their platform.
- The link between them has to come from something the user tells you or verifies.
The Data Model
Keep three concepts separate: the person, their channel identities, and the events that happen to them.
Core Tables
CREATE TABLE customers (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
full_name TEXT,
email TEXT UNIQUE,
phone_e164 TEXT UNIQUE,
attributes JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT now(),
merged_into UUID REFERENCES customers(id)
);
CREATE TABLE channel_identities (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL REFERENCES customers(id),
channel TEXT NOT NULL CHECK (channel IN ('whatsapp','instagram','telegram')),
external_id TEXT NOT NULL,
verified BOOLEAN DEFAULT false,
opted_in BOOLEAN DEFAULT false,
last_seen_at TIMESTAMPTZ,
UNIQUE (channel, external_id)
);
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
customer_id UUID NOT NULL REFERENCES customers(id),
channel TEXT NOT NULL,
type TEXT NOT NULL, -- message_in, message_out, order, tag_added
payload JSONB,
occurred_at TIMESTAMPTZ DEFAULT now()
);
Why This Shape Works
-
UNIQUE (channel, external_id)guarantees one identity row per platform account. -
merged_intolets you merge duplicates without deleting history. -
eventsis append-only, so the omnichannel customer profile is always reconstructable.
Tip: Store phone numbers in E.164 format (
+8801XXXXXXXXX) from day one. Matching017...against+8801...is a classic source of silent duplicates.
Identity Resolution: Linking the Same Person
Identity resolution is the process of deciding that two identities belong to the same human. For messaging, keep it conservative: a wrong merge (two people combined) is much worse than a missed merge.
Deterministic Rules First
Only auto-merge when you have a verified shared key:
- The user shares a phone number on Telegram (via the contact button) that matches a WhatsApp number.
- The user clicks a link from one channel that carries a signed token for another.
- The user confirms the same email on two channels.
A Simple Linking Flow
When someone on Instagram or Telegram says "my WhatsApp number is...", don't merge on the spot. Verify first:
- Generate a short-lived one-time code.
- Send it to the WhatsApp number.
- Ask the user to type it into the other channel.
- Merge only when the code matches.
import secrets, time
PENDING = {} # use Redis with a TTL in production
def start_link(customer_id: str, phone_e164: str) -> str:
code = f"{secrets.randbelow(10**6):06d}"
PENDING[(customer_id, phone_e164)] = (code, time.time() + 600)
send_whatsapp(phone_e164, f"Your verification code is {code}")
return "Code sent. Please reply with it here."
def confirm_link(customer_id: str, phone_e164: str, code: str) -> bool:
entry = PENDING.get((customer_id, phone_e164))
if not entry or entry[1] < time.time() or entry[0] != code:
return False
merge_customers(customer_id, find_customer_by_phone(phone_e164))
return True
Merging Without Losing Data
def merge_customers(source_id, target_id):
with db.transaction():
db.execute("UPDATE channel_identities SET customer_id=%s WHERE customer_id=%s",
(target_id, source_id))
db.execute("UPDATE events SET customer_id=%s WHERE customer_id=%s",
(target_id, source_id))
db.execute("UPDATE customers SET merged_into=%s WHERE id=%s",
(target_id, source_id))
Warning: Never use display name alone as a matching key. "Ahmed Khan" is not a unique identifier.
Building the Single Customer View
With identities linked, the single customer view is one query:
SELECT c.id, c.full_name, c.email,
jsonb_agg(DISTINCT jsonb_build_object(
'channel', ci.channel, 'opted_in', ci.opted_in, 'last_seen', ci.last_seen_at
)) AS channels,
(SELECT jsonb_agg(e ORDER BY e.occurred_at DESC)
FROM (SELECT type, channel, occurred_at FROM events
WHERE customer_id = c.id
ORDER BY occurred_at DESC LIMIT 20) e) AS recent_activity
FROM customers c
JOIN channel_identities ci ON ci.customer_id = c.id
WHERE c.id = $1 AND c.merged_into IS NULL
GROUP BY c.id;
This is the object your inbox, your automations, and your reports should all read from. Treat it as the single source of truth for unified customer data.
Syncing Data to Your CRM
Most teams need to sync data to a CRM (HubSpot, Salesforce, Zoho, or a custom one). Two rules keep it sane:
-
Use your
customers.idas the external key. Don't let the CRM become the identity authority for messaging. - Sync events, not just fields. Push "opted in on Telegram" or "asked about pricing on Instagram" as timeline entries.
def push_to_crm(customer):
payload = {
"external_id": str(customer["id"]),
"email": customer["email"],
"phone": customer["phone_e164"],
"properties": {"channels": ",".join(c["channel"] for c in customer["channels"])},
}
crm_client.upsert_contact(payload) # idempotent upsert, never blind insert
Use idempotent upserts and a retry queue. Webhooks arrive twice, and CRMs rate-limit.
Giving AI Agents Access Through Tool Calling
Once you have a unified profile, the best consumer of it is an AI agent that answers customers on any channel with full context. This is where AI tool calling (also called function calling in AI) comes in: the model doesn't query your database directly. It calls AI agent tools that you define, and you control what each tool can do.
Here is how AI agents use tools in this setup:
- A message arrives on any channel and is resolved to a
customer_id. - The AI agent orchestration layer passes the message to the LLM along with the tool definitions.
- The model decides to call a tool, such as
get_customer_profile. - Your code executes it and returns the result. The model never gets raw database access.
Designing AI Agent Tools That Can't Be Misused
Good AI agent tool design is mostly about limiting blast radius. Following LLM function calling best practices:
-
Split read and write tools.
get_customer_profileis safe.merge_customersshould never be exposed to the model. -
Never let the model pass
customer_id. Inject it from the authenticated session, so a prompt injection can't read someone else's profile. - Return only what's needed. Don't hand the model the full event log or raw phone numbers.
- Validate every argument server-side, as you would any public API.
{
"name": "get_customer_profile",
"description": "Returns the current customer's name, linked channels, open orders, and last 5 interactions. Read-only.",
"input_schema": {
"type": "object",
"properties": {
"include_orders": { "type": "boolean", "default": true }
},
"required": []
}
}
Notice there is no customer_id parameter. The server adds it. That one decision removes a whole class of tool calling in AI agents security problems.
Note: For anything that changes data (updating an email, requesting a link to another channel), use a separate write tool that triggers a confirmation step instead of acting immediately.
Pitfalls to Avoid
- Auto-merging on weak signals. Names and "similar" usernames cause wrong merges. Use verified keys only.
-
Ignoring channel rules. WhatsApp and Instagram restrict when you can message outside a 24-hour window, and Telegram bots can't message a user who hasn't started them. Store
opted_inandlast_seen_atper identity, not per customer. - One consent flag for everything. Opting in on WhatsApp doesn't mean consent on Telegram.
- No deletion path. A unified profile makes "delete my data" requests easier and more important. Build the delete-by-customer flow early.
-
Merging without an undo. Keep
merged_intoso you can split a bad merge later.
Conclusion
A single customer profile across WhatsApp, Instagram, and Telegram comes down to a few decisions:
- Model person → channel identities → events, not a flat contact list.
- Run identity resolution on verified keys only, and make merges reversible.
- Build one single customer view and make every tool read from it.
- Sync data to your CRM with idempotent upserts, keyed on your own ID.
- Expose the profile to AI agents through narrow, read-only tool calling with server-injected identity.
If you'd rather not build all of this from scratch, platforms like Botsailor are built for omnichannel automation across WhatsApp, Instagram, and Telegram, and are worth a look as a customer data solution if you want a unified inbox without owning the plumbing.
What's your biggest challenge when linking users across channels? Drop a comment below, share this with a teammate who's fighting duplicate contacts, and follow for more posts on agentic AI and omnichannel automation.
來源:DEV Community · dev.to