Skip to content

Connect Wati to AI Agents: Orchestrate Sales Pipelines & Support

Learn how to connect Wati to AI Agents using Truto's /tools endpoint. Build autonomous WhatsApp workflows for sales and support using LangChain.

Yuvraj Muley Yuvraj Muley · · 11 min read
Connect Wati to AI Agents: Orchestrate Sales Pipelines & Support

You want to connect Wati to an AI agent so your system can independently qualify WhatsApp leads, process support tickets, trigger automated templates, and assign conversations to human operators based on historical context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom WhatsApp Business integration from scratch.

Giving a Large Language Model (LLM) read and write access to your Wati instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Wati to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Wati to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for Wati, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex conversational operations workflows. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.

The Engineering Reality of the Wati API

Giving an LLM access to external data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production against complex messaging systems like Wati (built on top of the WhatsApp Business API), this approach collapses.

Wati's API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.

The Polymorphic Identifier Trap

Wati endpoints rely heavily on polymorphic target identifiers. When your agent wants to send a message or assign a tag, the target parameter can be a phone number, a Contact ID, a BSUID (Business Specific User ID), or a Channel-prefixed string (e.g., WhatsApp:1234567890).

Standard LLMs struggle with implicit formatting rules. If a model decides to send a message, it might guess the target format as +1 (555) 123-4567 or contact_12345. Wati will reject these immediately. If you expose raw Wati endpoints as tools, your model will hallucinate identifier types, causing high failure rates. A unified tool layer normalizes these inputs, allowing the agent to operate on a consistent schema while the integration layer handles identifier detection and formatting.

The Strict 24-Hour Session Window

WhatsApp Business enforces a strict 24-hour customer service window. You can only send free-form text messages (wati_conversations_send_session_message_v_1) if the customer has sent a message to your business within the last 24 hours. Outside of that window, you are legally restricted to sending pre-approved message templates (wati_message_templates_send).

If you expose the raw messaging endpoint to an LLM, the model will not inherently know how to check the session state before deciding which messaging endpoint to use. It will blindly attempt to send a free-form greeting to a three-day-old lead and crash with an API error. The agent tool layer needs strictly defined boundaries so the LLM understands when to query for a template and when it has permission to send a standard reply.

Interactive Message Constraints

Wati allows you to send highly engaging interactive messages (buttons, lists, products). However, the API enforces rigid structural constraints. Button messages are strictly limited to 1-3 buttons. Button text cannot exceed 20 characters. List section headers are capped at 60 characters, and body text at 1024 characters.

LLMs are notoriously bad at counting characters and adhering to arbitrary array length limits. If your agent invents a 4-button interactive message because "it makes more sense for the conversation," the Wati API will throw a validation error. Exposing these tools requires rigorous JSON schema validation at the integration boundary, ensuring the LLM's output is verified and corrected before it ever touches the upstream API.

Fetching Wati Tools via Truto

To safely expose Wati to your agent, you need a translation layer. Every integration on Truto is a comprehensive JSON object that represents how the underlying product's API behaves. Integrations define Resources, which map to the endpoints on the underlying API, enabling Truto to map any complex API into a REST-based CRUD API.

The Methods on these Resources are provided as proxy APIs. Truto handles all authentication, pagination, and query parameter processing. For AI agents, Truto provides a description and schema for all of these methods, which are exposed via the /integrated-account/:id/tools endpoint. This returns AI-ready tools that frameworks like LangChain can consume instantly.

Handling Rate Limits in Agent Loops

When your agent gets stuck in a retry loop or attempts to bulk-update contacts, it will inevitably hit Wati's rate limits. It is critical to understand how Truto handles these limits architecturally.

Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Wati API returns an HTTP 429 (Too Many Requests), Truto passes that error directly back to the caller. Truto normalizes upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification.

As the developer, your agent execution loop is responsible for reading these normalized headers and applying the correct retry/backoff logic. Do not assume the integration layer will absorb these errors for you.

High-Leverage Wati Agent Tools

When connecting an AI agent to Wati, you do not want to give the model access to dozens of low-level CRUD endpoints. You want to provide high-leverage tools that map to specific business outcomes. Here are the hero tools you should bind to your agent.

wati_conversations_send_session_message_v_1

This tool allows the agent to send a free-form text message to an open WhatsApp session. It is the primary tool for active support and sales conversations. The agent must ensure the conversation is within the 24-hour window before calling this.

Contextual usage notes: The whatsapp_number parameter automatically accepts Contact IDs or BSUID formats. The agent should be instructed to keep responses concise to fit the messaging medium.

"Send a message to the customer at +15550198234 letting them know their support ticket has been escalated to tier 2 and we will respond within 2 hours."

wati_message_templates_send

When the 24-hour session window has closed, or when initiating proactive outreach, the agent must use this tool to send a pre-approved template message.

Contextual usage notes: The agent needs to pass the exact template_name, broadcast_name, and a list of recipients. You should provide the agent with a separate read-tool to list available templates first so it does not hallucinate template names.

"The customer's trial expired 3 days ago. Send them the 'trial_expired_discount' template message to offer a 20% discount on their first month."

wati_contacts_bulk_update

Sales agents need to update contact states rapidly after qualifying a lead. This tool allows the agent to update multiple Wati contacts simultaneously, adjusting custom parameters, names, or tags based on polymorphic target identifiers.

Contextual usage notes: Highly efficient for post-processing a list of prospects after an agent reviews a lead qualification report.

"Update the custom attributes for +15550198234 and +15550198235. Set their 'Lead Status' to 'Qualified' and 'Interest Level' to 'High'."

wati_conversations_update_status_v_1

AI support agents need the ability to close out conversations or mark them as pending when waiting on external input. This tool updates the ticket status of a Wati conversation to OPEN, SOLVED, PENDING, or BLOCK.

Contextual usage notes: At least one of whatsappNumber or target must be provided. The agent should always transition the status to SOLVED when the user explicitly confirms their issue is resolved.

"The user confirmed their login issue is fixed. Update their conversation ticket status to SOLVED."

wati_conversations_assign_operator_v_1

Agents are not meant to handle every interaction indefinitely. When a conversation requires human empathy, a specialized process, or the user requests human escalation, this tool allows the AI to assign an operator by email to the WhatsApp conversation.

Contextual usage notes: If the email is omitted, the chat is assigned to the bot. Ensure the agent has the correct human operator email addresses in its system prompt or state.

"The customer is extremely frustrated about a billing error. Assign this conversation to sarah.j@company.com immediately."

wati_calls_get_summary

For teams utilizing Wati's calling features, this tool retrieves AI-generated summaries for specific calls. Agents can use this to quickly digest past interactions before engaging a user via text.

Contextual usage notes: Requires the call_id. Useful for context-gathering steps in an agentic loop.

"Retrieve the call summary for call ID 8839210 to understand what the sales rep discussed with the client yesterday before I send a follow-up message."

To view the complete JSON schemas and the full list of available Wati proxy tools, visit the Wati integration page.

Building Multi-Step Workflows

An AI agent is not a single API call; it is an execution loop that reasons, acts, observes, and iterates. To build a robust Wati agent, you need to implement a framework-agnostic loop that fetches tools from Truto, binds them to your LLM, executes the model, and handles the Truto-normalized HTTP 429 rate limits defensively.

Here is how you structure this architecture using standard TypeScript and the Truto LangChain SDK.

flowchart TD
    Start["User Input / Trigger"] --> Agent["Agent Reasoner<br>(LangChain/LangGraph)"]
    Agent -->|"Function Call"| TM["Truto Tool Manager"]
    TM -->|"Execute Proxy API"| Truto["Truto API Gateway"]
    Truto -->|"Standardized Headers"| RateLimit{"HTTP 429?"}
    
    RateLimit -->|"Yes"| Backoff["Read ratelimit-reset<br>Apply Delay"]
    Backoff --> TM
    
    RateLimit -->|"No"| WatiAPI["Wati API"]
    WatiAPI -->|"JSON Response"| Truto
    Truto -->|"Normalized Output"| TM
    TM -->|"Tool Observation"| Agent
    Agent -->|"Final Output"| End["Workflow Complete"]

Fetching and Binding Tools

To start, you fetch the tools directly from your integrated Wati account using the TrutoToolManager. This maps Wati's endpoints into strict JSON schemas that the LLM natively understands.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
 
async function initializeWatiAgent() {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // 2. Fetch Wati tools from Truto for your specific Integrated Account
  const toolManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
    integratedAccountId: process.env.WATI_ACCOUNT_ID,
  });
 
  // Retrieve all available Wati proxy tools
  const tools = await toolManager.getTools();
 
  // 3. Define the agent prompt
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are an autonomous WhatsApp revenue operations agent. You manage Wati conversations, update contact attributes, and escalate to human operators when necessary."],
    ["placeholder", "{chat_history}"],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);
 
  // 4. Bind tools and create the executor
  const agent = await createOpenAIToolsAgent({
    llm,
    tools,
    prompt,
  });
 
  return new AgentExecutor({
    agent,
    tools,
    maxIterations: 10,
  });
}

Defending Against Rate Limits

Because Truto strictly passes rate limits through to the caller, your agent execution code must be wrapped in a handler that respects the ratelimit-reset header. If your agent executes a loop that bulk-updates 50 contacts sequentially, it will hit limits.

When a tool call fails with a 429, you must intercept the error, pause execution based on the IETF header, and retry the tool execution before returning the result to the LLM.

async function executeWithRateLimitHandling(executor, input) {
  let retries = 3;
  
  while (retries > 0) {
    try {
      const result = await executor.invoke({ input });
      return result;
    } catch (error) {
      if (error.response && error.response.status === 429) {
        // Read Truto's normalized IETF headers
        const resetTimeHeader = error.response.headers.get('ratelimit-reset');
        
        if (resetTimeHeader) {
          const resetTimeMs = parseInt(resetTimeHeader, 10) * 1000;
          const delay = Math.max(0, resetTimeMs - Date.now());
          
          console.log(`Rate limit hit. Waiting ${delay}ms before retrying...`);
          await new Promise(resolve => setTimeout(resolve, delay));
          retries--;
          continue;
        }
      }
      // Re-throw if it's not a 429 or we ran out of retries
      throw error;
    }
  }
}

Workflows in Action

Once the tool binding and execution loop are in place, the agent is capable of running complex, multi-step workflows entirely autonomously. Here are concrete examples of how an AI agent interacts with the Wati tools.

Scenario 1: Automated Lead Qualification & CRM Handoff

A marketing campaign drives traffic to a WhatsApp number. The AI agent is responsible for greeting the user, determining their intent, qualifying their budget, and handing them off to the correct sales rep.

"A new inbound message just arrived from +44 7700 900077 saying 'I want to upgrade my team's software.' Qualify this lead, update their contact attributes, and assign them to a human sales rep."

Agent Execution Trace:

  1. Tool Call: wati_conversations_send_session_message_v_1
    • Agent action: Sends an immediate reply asking: "Hi! We'd love to help your team upgrade. Roughly how many seats are you looking to purchase?"
  2. User replies: "We have about 45 people."
  3. Tool Call: wati_contacts_bulk_update
    • Agent action: Updates the contact's custom attributes, setting Company Size to 45 and Lead Score to High.
  4. Tool Call: wati_conversations_send_session_message_v_1
    • Agent action: Sends: "Great, I'm connecting you with our mid-market specialist now."
  5. Tool Call: wati_conversations_assign_operator_v_1
    • Agent action: Assigns the conversation target to alex.sales@company.com based on the routing rules for 40+ seat deals.

Outcome: The user is instantly engaged, their data is cleanly categorized in the Wati database, and the human operator takes over a warm, qualified lead without doing data entry.

Scenario 2: Proactive Customer Support & Ticket Resolution

A backend system detects that a user experienced an error on the web app. The AI agent is triggered to proactively reach out to the user on WhatsApp, diagnose the issue, and update the ticket.

"User ID +14155552671 experienced a payment failure. Check if they have an active session. If not, send them the 'payment_failed_alert' template. If they reply and the issue is resolved, close the ticket."

Agent Execution Trace:

  1. Tool Call: wati_conversations_list_messages_v_1
    • Agent action: Queries the recent messages for the target to determine if there is an open 24-hour window.
    • Observation: No messages found in the last 48 hours.
  2. Tool Call: wati_message_templates_send
    • Agent action: Executes the template push, sending the pre-approved alert to the user's phone.
  3. User replies: "Oh, I updated my credit card. It should work now."
  4. Tool Call: wati_conversations_send_session_message_v_1
    • Agent action: The session is now open. The agent replies: "Thank you, we see the payment went through successfully!"
  5. Tool Call: wati_conversations_update_status_v_1
    • Agent action: Updates the conversation status to SOLVED.

Outcome: The agent navigated WhatsApp's complex 24-hour compliance rules autonomously, successfully reached the user, and managed the ticket lifecycle completely hands-free.

Moving Beyond the Integration Bottleneck

Building an AI agent is an exercise in managing state, memory, and reasoning. Building the integrations for that agent is an exercise in reading API docs, managing OAuth lifecycles, and writing endless TypeScript interfaces.

Directly wrapping raw vendor APIs forces your LLM to deal with provider-specific quirks, polymorphic identifiers, and arbitrary JSON constraints. This vastly increases the attack surface for hallucinations and brittle execution.

By routing your agent's capabilities through a unified tool layer, your LLM operates against a stable, predictable, and strictly validated schema. Truto abstracts away the authentication, normalization, and endpoint mapping, allowing your engineering team to focus entirely on prompting and workflow logic. When you give your agent reliable tools, the SaaS integration bottleneck disappears.

FAQ

How do AI agents handle Wati's 24-hour session window?
AI agents must be given distinct tools for session messages and template messages. Through system prompting and querying message history, the agent determines if the 24-hour window is open. If closed, it is instructed to use the template sending tool.
Does Truto automatically handle Wati rate limits for AI agents?
No. Truto passes HTTP 429 rate limit errors directly back to the caller. However, Truto normalizes the upstream rate limit information into standard IETF headers (ratelimit-reset, etc.). The developer must implement a backoff/retry loop in the agent executor based on these headers.
Why shouldn't I give my LLM direct access to Wati's raw API endpoints?
Wati's API uses polymorphic target identifiers and strict JSON constraints for interactive messages. LLMs frequently hallucinate formatting for these complex payloads. A unified tool layer normalizes these schemas, dramatically reducing hallucination rates and brittle execution.
Can I use frameworks other than LangChain to connect Wati tools?
Yes. Truto's /tools endpoint returns standard JSON schemas that can be ingested by any modern agent framework, including LangGraph, CrewAI, and the Vercel AI SDK.

More from our Blog