Skip to content

Connect Superchat to AI Agents: Automate Inbox & File Management

A definitive engineering guide to connecting Superchat to AI agents using Truto. Learn how to bind tools, automate messaging, and handle API rate limits.

Uday Gajavalli Uday Gajavalli · · 11 min read
Connect Superchat to AI Agents: Automate Inbox & File Management

You want to connect Superchat to an AI agent so your system can autonomously read multi-channel inboxes, search for customer context, manage file attachments, and reply to messages. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom Superchat integration from scratch.

The industry is shifting away from simple internal chatbots toward agentic AI - autonomous workflows that can operate directly within your SaaS stack. Giving a Large Language Model (LLM) the ability to execute API calls transforms it from a text generator into a digital worker. If your team uses ChatGPT, check out our guide on connecting Superchat to ChatGPT, or if you are building on Anthropic's ecosystem, read our guide on connecting Superchat to Claude. For developers building bespoke autonomous workflows across internal infrastructure, you need a programmatic way to fetch these tools and bind them to your agent framework.

Giving an LLM read and write access to Superchat 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 API boilerplate for you.

This guide breaks down exactly how to fetch AI-ready tools for Superchat, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex support operations. We will reference the overarching architecture described in our guide on architecting AI agents and the SaaS integration bottleneck.

The Engineering Reality of Superchat's API

Building an AI agent prototype is easy. Connecting it to an external messaging API in production is hard.

Exposing an external messaging platform to an LLM requires strict schema enforcement and an understanding of the underlying platform's domain model. Superchat is not a simple CRUD database. It is an omni-channel communication platform that aggregates WhatsApp, Instagram, Email, and SMS. This introduces specific API quirks that break standard LLM assumptions.

Rate Limits and the 429 Reality

Superchat enforces strict rate limits on its API to prevent abuse. When building an AI agent that might decide to summarize 50 historical conversations in a single loop, you will inevitably hit these limits.

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

The caller - your AI agent's execution loop - is strictly responsible for implementing retry and exponential backoff logic. Do not assume your agent framework will absorb these errors natively. If you do not catch the 429, read the ratelimit-reset header, and pause the agent, the workflow will crash and hallucinate a failure state to the user.

The Omni-Channel Time Window

LLMs assume they can reply to a message whenever they want. Superchat integrates heavily with WhatsApp Business, which enforces a strict 24-hour customer care window. If an AI agent attempts to send a free-free message to a WhatsApp contact more than 24 hours after their last inbound message, the API request will fail unless it uses an approved template.

When fetching a conversation, the Superchat API returns a time_window object. Your agent must be instructed to check this window before attempting to use the create message tool, otherwise it will waste execution cycles failing against the WhatsApp policy constraints.

File management in messaging APIs is inherently complex. When an agent requests file details in Superchat, it does not get raw binary data. It gets a link object containing a temporary download URL and a valid_until timestamp. If your agent is running a long background task and attempts to access that URL after it expires, the workflow breaks.

Similarly, exporting conversation history is an asynchronous operation. The agent cannot simply call "export" and receive a file. It must create an export job, receive a status, and poll the API until the job completes. LLMs are notoriously bad at asynchronous polling - they tend to enter infinite loops or guess the file URL. You must explicitly define this polling behavior in your agent's system prompt or handle it in the tool definition logic.

Exposing Superchat Tools to AI Agents

Truto maps Superchat's API endpoints into standardized Resources and Methods, wrapping them in a unified Proxy API layer. We then expose these methods via the /tools endpoint, returning JSON schemas optimized specifically for LLM tool calling (function calling).

Instead of writing custom Node.js wrappers for every Superchat endpoint, you dynamically load these definitions into your agent. Here are the highest-leverage hero tools to expose to your AI agent for Superchat automation.

Search Superchat Contacts

Tool Name: list_all_superchat_search_contacts

Before an agent can message a user or retrieve their history, it needs their internal Superchat identifier. This tool allows the LLM to query the workspace by specific fields like email or phone number. It requires the agent to pass a field (e.g., mail), an operator, and a value. It returns an array of contact objects including id, first_name, handles, and custom_attributes.

"A user emailed us from david.miller@example.com complaining about a delayed shipment. Search Superchat for this contact to get their internal ID, then find any active conversations associated with their profile."

Retrieve Conversation Context

Tool Name: get_single_superchat_conversation_by_id

Once the agent has a conversation ID, it needs the context. This tool returns the deep details of a thread, including the channel type (WhatsApp, Email, etc.), the status, assigned users, labels, and crucially, the time_window. Agents use this to understand if they are legally allowed to reply to a WhatsApp thread or if they need to fall back to an email.

"Fetch the details for conversation ID 8f72c-19a. Check the time_window property. If the window is closed, do not draft a reply. Instead, escalate it by reassigning the conversation to the human support tier."

Send a Message

Tool Name: create_a_superchat_message

This is the primary actuation tool. It allows the agent to dispatch a message through Superchat. The agent must specify the channel (from) and the recipient (to). It handles the routing through the correct omni-channel gateway based on the provided identifiers.

"Draft a polite response to the customer explaining that their refund has been processed. Send this message to the current active WhatsApp channel in their conversation thread."

Add Internal Notes

Tool Name: create_a_superchat_note

AI agents often operate as background analysts rather than customer-facing bots. This tool allows an agent to append a private internal note to a conversation. It requires the conversation_id and the content. This is vital for summarize-and-triage workflows where the agent reads a long thread and leaves a TL;DR for the human agent taking over the shift.

"Read the transcript of the last 15 messages in this conversation. Summarize the customer's technical issue in three bullet points and add it as an internal note to the conversation so the engineering team has context."

Upload Files

Tool Name: create_a_superchat_file

Agents that generate reports, invoices, or log files need a way to push those assets into the communication stream. This tool uploads a new file to the Superchat workspace (under the 5MB limit). It returns the unique file id, the mime_type, and a temporary link.url. The agent can then attach this file ID to subsequent message operations.

"Generate a PDF summary of the user's billing history. Upload the file to Superchat, extract the returned file ID, and send it in a new message to the customer confirming their request."

Export Conversation History

Tool Name: create_a_superchat_conversation_export

For compliance, auditing, or deep RAG (Retrieval-Augmented Generation) ingestion, an agent might need the complete historical export of a thread. This tool initiates the export job. The agent must provide the conversation_id. It returns an id and a status. The agent must be instructed to handle the asynchronous nature of this request.

"The legal team requested a full log of our interactions with this vendor. Trigger a conversation export for conversation ID 99a-b42. Note the export ID and inform me when the job is initiated."

To view the complete schema definitions and the full inventory of available capabilities - including template management, inbox routing, and custom attribute handling - visit the Superchat integration page.

Workflows in Action

Providing an LLM with tools is only the first step. The true value emerges when the agent chains these tools together to execute multi-step logic. Here are two concrete examples of how an AI agent navigates the Superchat API.

1. The Automated Support Triager

Customer support teams waste hours reading backlogs just to figure out who needs to reply to a ticket. An AI agent can run as a cron job, analyzing unassigned conversations, checking time constraints, and routing them appropriately.

"Find the contact associated with phone number +15550198. Get their most recent open conversation. If the WhatsApp time window is expiring in less than 2 hours, add a high-priority internal note and reassign the conversation to the urgent inbox."

Execution Steps:

  1. Search Contacts: The agent calls list_all_superchat_search_contacts with field="phone" and value="+15550198". It parses the returned JSON array and extracts the contact_id.
  2. Get Conversations: The agent calls list_all_superchat_contact_conversations using the contact_id to find the active thread ID.
  3. Check Context: The agent calls get_single_superchat_conversation_by_id. It examines the time_window object in the response. It calculates the delta between the current UTC time and the window expiration.
  4. Add Note: Detecting the impending expiration, the agent calls create_a_superchat_note with content="URGENT: WhatsApp window closes in 90 minutes. Immediate reply required."
  5. Update Conversation: Finally, it calls update_a_superchat_conversation_by_id to change the inbox routing and update the assigned status.

Result: The human agent logs in and immediately sees a prioritized, annotated escalation, saving them from missing a critical SLA.

2. The GDPR/Compliance Data Exporter

Handling Data Subject Access Requests (DSAR) is tedious. An agent can completely automate the retrieval of a user's communication history across all channels.

"A user named Sarah Connor requested her data history. Search for her contact profile, find all her conversations, and trigger an export for each. Return the export job IDs to me."

Execution Steps:

  1. Search Contacts: The agent calls list_all_superchat_search_contacts with field="name" and value="Sarah Connor". It isolates the correct internal ID.
  2. List Conversations: The agent calls list_all_superchat_contact_conversations and iterates through the returned array of conversation IDs.
  3. Trigger Exports: In a loop, the agent calls create_a_superchat_conversation_export for each ID.
  4. Return Data: The agent compiles the returned export ids and status fields, presenting them back to the IT administrator to monitor for completion.

Result: A process that typically takes an admin twenty minutes of clicking through a UI is condensed into a ten-second autonomous script.

Building Multi-Step Workflows

To build these workflows, you need an integration architecture that natively connects the LLM framework (like LangChain or Vercel AI SDK) to the upstream SaaS API.

Truto's SDK automatically translates the Superchat Proxy APIs into standard tool definitions. More importantly, you must wrap your agent execution loop in logic that gracefully handles the HTTP 429 rate limit errors that Truto passes through.

Below is an architectural example using TypeScript and the truto-langchainjs-toolset. This code demonstrates fetching the tools, binding them to an Anthropic Claude model, and constructing a robust execution loop that respects the IETF rate limit headers.

import { ChatAnthropic } from "@langchain/anthropic";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
 
// 1. Initialize the LLM
const llm = new ChatAnthropic({
  modelName: "claude-3-5-sonnet-latest",
  temperature: 0,
});
 
// 2. Fetch Superchat tools for a specific integrated account via Truto
// This calls GET https://api.truto.one/integrated-account/<id>/tools
const trutoManager = new TrutoToolManager({
  trutoApiKey: process.env.TRUTO_API_KEY,
});
 
async function runSuperchatAgent(accountId: string, userPrompt: string) {
  // Dynamically load the tools defined on the Truto Superchat integration
  const tools = await trutoManager.getTools(accountId);
  
  // 3. Define the Agent Prompt
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are an autonomous support operations engineer managing a Superchat instance. You must handle files, notes, and messages carefully. If you trigger an export, do not poll indefinitely."],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);
 
  // 4. Bind the tools to the LLM and create the executor
  const agent = createToolCallingAgent({
    llm,
    tools,
    prompt,
  });
 
  const agentExecutor = new AgentExecutor({
    agent,
    tools,
  });
 
  // 5. Execute the Workflow with Rate Limit Handling
  let retries = 0;
  const maxRetries = 3;
 
  while (retries < maxRetries) {
    try {
      const result = await agentExecutor.invoke({ input: userPrompt });
      console.log("Agent Workflow Complete:", result.output);
      break; // Success, exit loop
      
    } catch (error: any) {
      // Check if the error is a 429 passed through by Truto
      if (error.status === 429) {
        retries++;
        // Extract the normalized IETF rate limit reset header
        const resetHeader = error.headers?.['ratelimit-reset'];
        
        // Calculate backoff: Either delta seconds or standard exponential fallback
        let waitSeconds = resetHeader ? parseInt(resetHeader, 10) : Math.pow(2, retries);
        console.warn(`Rate limit hit. Truto passed 429. Backing off for ${waitSeconds} seconds...`);
        
        await new Promise(res => setTimeout(res, waitSeconds * 1000));
      } else {
        // Re-throw if it's not a rate limit issue
        console.error("Agent execution failed due to non-429 error.", error);
        throw error;
      }
    }
  }
}
 
// Execute the agent
runSuperchatAgent(
  "superchat_acct_88f9a2", 
  "Search for user 'john.doe@example.com', find his active conversation, and leave an internal note saying his account is verified."
);

Architectural Considerations

Notice the exception handling block. Because Truto acts as a transparent proxy for rate limits, your infrastructure maintains full control over the backoff strategy. If Truto swallowed the 429 and held the connection open, your serverless functions would time out, and your agent frameworks would lock up waiting for a response. By standardizing the ratelimit-reset header, Truto allows your execution loop to parse exactly how long the Superchat API requires you to wait before dispatching the next tool call.

Furthermore, by dynamically fetching the tools via trutoManager.getTools(), your agent automatically inherits any schema updates. If Superchat adds a new required parameter to their messaging endpoint, or if your team customizes a method description in the Truto UI to improve the LLM's prompting accuracy, the agent receives the updated JSON schema on the next run without requiring a code deployment.

The Strategic Advantage of Unified Tool Calling

The most expensive part of building AI agents is not the LLM inference; it is maintaining the integration layer connecting the agent to the outside world.

Superchat has dozens of endpoints, complex pagination schemas, and strict operational rules regarding omni-channel messaging. Hand-coding these API calls, maintaining the TypeScript types, writing the JSON schemas for the agent framework, and building the OAuth token refresh infrastructure drains engineering resources away from core product development.

By leveraging Truto's /tools endpoint, you abstract away the API lifecycle management. You interact with a standardized set of tools, while Truto handles the underlying authentication, pagination, and schema normalization. Your AI agents get immediate, reliable access to Superchat - allowing your engineering team to focus on building better autonomous logic, rather than debugging undocumented webhook payloads.

FAQ

How do AI agents handle Superchat API rate limits?
Truto does not retry or absorb rate limit errors. When Superchat returns an HTTP 429, Truto passes it to the caller and standardizes the headers (ratelimit-reset). Your agent execution loop must parse this header and implement its own backoff logic before retrying the tool call.
Can an AI agent reply to WhatsApp messages via Superchat at any time?
No. Superchat enforces WhatsApp's 24-hour customer care window. The AI agent must check the time_window property returned by the conversation tool before attempting to send a free-form message, otherwise the API request will fail.
How do AI agents handle file uploads in Superchat?
Agents must use the create_a_superchat_file tool to upload the document first. The API returns a temporary link and a unique file ID. The agent then passes this file ID into subsequent message creation tool calls to attach the document to the conversation.
Does Truto support multi-agent frameworks like CrewAI or LangGraph?
Yes. Truto's /tools endpoint returns standardized JSON schemas that are framework-agnostic. You can bind these tools natively using LangChain's .bindTools(), making them compatible with LangGraph, CrewAI, Vercel AI SDK, and standard MCP servers.

More from our Blog