---
title: "Connect Botpress to AI Agents: Control conversations and workflows"
slug: connect-botpress-to-ai-agents-control-conversations-and-workflows
date: 2026-07-17
author: Sidharth Verma
categories: ["AI & Agents"]
excerpt: "Learn how to connect Botpress to AI agents using Truto's tools endpoint to automate conversations, manage workspaces, and orchestrate support workflows."
tldr: "Connecting Botpress to AI agents requires handling complex messaging payloads and asynchronous file indexing. Truto's unified tools layer abstracts authentication and pagination, exposing clean JSON schemas so your LLMs can safely read conversations, execute workflows, and search knowledge bases without hallucinating API quirks."
canonical: https://truto.one/blog/connect-botpress-to-ai-agents-control-conversations-and-workflows/
---

# Connect Botpress to AI Agents: Control conversations and workflows


You want to connect Botpress to an AI agent so your internal systems can independently read chat conversations, search knowledge bases, execute workflows, and audit [workspace usage](https://truto.one/what-is-the-best-solution-for-ai-agent-observability-in-2026/) based on historical context. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to maintain a fragile, custom-built API wrapper.

Giving a Large Language Model (LLM) read and write access to your Botpress instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector that understands the nuances of the Botpress Admin and Chat APIs, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on [connecting Botpress to ChatGPT](https://truto.one/connect-botpress-to-chatgpt-manage-bots-workspaces-and-analytics/), or if you are building on Anthropic's models, read our guide on [connecting Botpress to Claude](https://truto.one/connect-botpress-to-claude-search-knowledge-bases-and-manage-tables/). For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them directly to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for Botpress, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex automation workflows. For a deeper look at the architecture behind this approach, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## The Engineering Reality of Custom Botpress Connectors

Building AI agents is easy. Connecting them to external SaaS APIs is hard. 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, this approach collapses entirely, especially with an ecosystem as deep as Botpress.

If you decide to integrate Botpress yourself, you own the entire API lifecycle. The Botpress API introduces several highly specific integration challenges that break standard LLM assumptions.

### Polymorphic Message Payloads
Sending a message in Botpress requires understanding a polymorphic payload schema. The `payload` field is a content-type-specific object whose shape is entirely determined by a `type` discriminator. If you are sending a standard text message, the payload requires a `text` string. If you are sending a `carousel`, it requires an array of `cards`, each containing `image`, `title`, and `actions`. 

If you hand-code this integration, you have to write massive system prompts to teach the LLM the exact schema requirements for every single payload type. When the LLM inevitably hallucinates and tries to attach an `image_url` directly to a `text` payload, the API rejects it. Truto solves this by enforcing strict JSON schemas for every method at the tool generation layer. The LLM sees a deterministic schema for `create_a_botpress_message`, reducing the attack surface for hallucinations.

### Asynchronous File Indexing
Botpress handles file uploads and knowledge base indexing asynchronously. When you update the passages for a file via the API, the endpoint returns immediately with the file status set to `indexing_pending`. The indexing completes asynchronously in the background, eventually transitioning to `indexing_completed` or `indexing_failed`.

AI agents operate sequentially by default. If your agent uploads a file and immediately attempts to search the knowledge base in the next step, it will fail to find the content because the index is not yet built. Hand-coded integrations require you to build complex polling mechanisms to wait for state changes. By using a [standardized tool layer](https://truto.one/the-hands-on-guide-to-building-mcp-servers-for-ai-agents-2026/), you can design deterministic agent flows that check resource status before proceeding.

### Hierarchical ID Cross-Referencing
The Botpress API requires deep context tracking. Workspaces contain Bots. Bots contain Integrations and Conversations. Conversations contain Messages and Participants. When an agent wants to list messages, it needs the `conversation_id`. To find the conversation, it often needs to filter by `bot_id`. 

Direct API tools push these relational quirks into the LLM's context window. A unified tool layer maps these endpoints into clean, REST-based CRUD proxy methods. Truto handles the underlying query parameter processing, ensuring the LLM only ever chooses from stable function names with deterministic inputs.

## Why a Unified Tool Layer Matters for Agent Safety

Before writing a line of integration code, decide what layer your agent talks to. This choice determines how safe your production system will be.

Truto provides all the resources defined on an Integration as tools for your LLM frameworks to use. Every integration on Truto is essentially a comprehensive JSON object that represents how the underlying Botpress API behaves. Truto's `Resources` map to the endpoints on the upstream product's API, enabling Truto to map any API into a REST-based CRUD format.

The `Methods` on these resources are exposed as Proxy APIs. This is the first level of abstraction where Truto handles all pagination, authentication, and query parameter processing. When solving problems agentically, these Proxy APIs are sufficient because they handle data normalization on their own using the raw data from Botpress.

By calling the `/integrated-account/<id>/tools` endpoint, your agent dynamically fetches all these Proxy APIs with their descriptions and strict JSON schemas. If a tool call fails because the LLM provided an invalid argument, the schema validation rejects it before it even hits the Botpress API. A broken tool call fails fast, allowing the agent to observe the error and self-correct.

### A Note on Rate Limits
It is critical to understand that Truto does not retry, throttle, or apply backoff on rate limit errors automatically. When the upstream Botpress API returns an HTTP 429 Too Many Requests, Truto passes that error directly to the caller. 

However, Truto normalizes the upstream rate limit information into standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) according to the IETF specification. The caller - your agent framework - is entirely responsible for reading these headers and executing the appropriate retry and exponential backoff logic. 

## Botpress Hero Tools for AI Agents

Truto exposes dozens of Botpress operations, but injecting all of them into your LLM's context window will overwhelm the model. You should filter the tools down to the highest-leverage operations. Here are the core hero tools you need to build powerful Botpress workflows.

### 1. list_all_botpress_admin_bots
This tool allows the agent to discover all available bots within a workspace. It supports filtering by environment and tags, returning core metadata like deployment status and creation dates. This is the foundation for any cross-bot auditing workflow.

> "Fetch all production bots in our workspace and list their deployment timestamps to find which ones haven't been updated this year."

### 2. botpress_conversations_list_messages
Agents need context to make decisions. This tool lists the messages within a specific Botpress conversation, allowing the LLM to read the chat history, summarize user intent, or determine if an escalation is required.

> "Read the last 10 messages from conversation ID 12345 and summarize the user's primary technical issue."

### 3. create_a_botpress_message
This is the primary action tool for responding to users. It creates a new message in Botpress by sending a typed payload to a conversation. Because the schema enforces strict payload structures, the agent can safely send text, markdown, or choice dropdowns without breaking the API.

> "Send a markdown message to conversation ID 12345 containing the troubleshooting steps for resetting their router."

### 4. botpress_files_search
Before answering a user query, an agent should search the source of truth. This tool searches indexed Botpress files using natural language semantic search to retrieve matching text passages and their scores.

> "Search the bot's indexed files for 'refund policy for digital downloads' and return the top two matching passages."

### 5. create_a_botpress_chat_workflow
For complex orchestration, an agent can initiate a new Botpress chat workflow. This allows the AI agent to hand off specific procedural tasks back to the Botpress engine.

> "Create a new chat workflow for the current conversation to trigger the 'account verification' sequence."

### 6. botpress_admin_usages_activity
Ideal for FinOps and IT admin personas, this tool lists Botpress usage history and activity for a specific bot or workspace. It allows the agent to [monitor invocation calls and AI spend](https://truto.one/what-is-the-best-solution-for-ai-agent-observability-in-2026/).

> "Pull the AI spend activity for our main customer support bot for the last 30 days and flag if we are nearing our quota."

For the complete tool inventory, request schemas, and parameter details, visit the [Botpress integration page](https://truto.one/integrations/detail/botpress).

## Workflows in Action

How do these tools compose together in production? Here are two concrete scenarios showing exactly what the agent executes.

### Scenario 1: Support Escalation Triage
An IT support agent is tasked with monitoring a high-priority conversation queue. When a user gets stuck, the agent must intervene, figure out the problem, and provide an answer from the internal docs.

> "Check conversation ID 98765. Read the history, figure out what the user is asking, search our knowledge base files for the answer, and reply to them with the solution."

**Execution Steps:**
1. The agent calls `botpress_conversations_list_messages` using `conversation_id: 98765`.
2. The LLM processes the message array and determines the user is asking about "SSO configuration for Azure AD".
3. The agent calls `botpress_files_search` with the query string "Azure AD SSO configuration steps".
4. The LLM reads the returned semantic search passages.
5. The agent calls `create_a_botpress_message` to send a structured markdown payload to the user containing the exact steps, successfully triaging the issue.

### Scenario 2: Automated Workspace Auditing
A DevOps engineer needs to maintain a clean workspace and ensure experimental bots are not consuming resources.

> "List all bots in our workspace. For any bot tagged 'experimental', check its usage activity over the last week. If it has zero invocations, delete it."

**Execution Steps:**
1. The agent calls `list_all_botpress_admin_bots` to retrieve the array of bot objects.
2. The LLM filters the list for bots containing the tag "experimental".
3. For each experimental bot, the agent calls `botpress_admin_usages_activity` passing the `bot_id` and setting the type to `invocation_calls`.
4. If the returned usage array is empty or zero, the agent calls `delete_a_botpress_admin_bot_by_id` to remove the dead resource, effectively cleaning up the workspace autonomously.

## Building Multi-Step Workflows

To build these workflows, you need to bind Truto's tools to your agent framework. The code below demonstrates a realistic agent loop using TypeScript and LangChain, emphasizing how to handle the IETF rate limit headers that Truto passes through from Botpress.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@truto/langchainjs-toolset";
import { HumanMessage, AIMessage } from "@langchain/core/messages";

async function runBotpressAgent(accountId: string, userPrompt: string) {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });

  // 2. Initialize the Truto Tool Manager
  const toolManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
  });

  // 3. Fetch Botpress tools for the specific account
  // We filter to only include the tools we need to save context space
  console.log("Fetching tools from Truto...");
  const allTools = await toolManager.getToolsForAccount(accountId);
  const selectedTools = allTools.filter(tool => 
    ["botpress_conversations_list_messages", "botpress_files_search", "create_a_botpress_message"].includes(tool.name)
  );

  // 4. Bind the tools to the LLM
  const agentWithTools = llm.bindTools(selectedTools);

  // 5. Build the execution loop with rate limit handling
  const messages = [new HumanMessage(userPrompt)];
  let isComplete = false;

  while (!isComplete) {
    try {
      const response = await agentWithTools.invoke(messages);
      messages.push(response);

      if (!response.tool_calls || response.tool_calls.length === 0) {
        console.log("Agent finished execution.");
        console.log("Final Output:", response.content);
        isComplete = true;
        break;
      }

      // Execute each requested tool call
      for (const toolCall of response.tool_calls) {
        console.log(`Executing tool: ${toolCall.name}`);
        const tool = selectedTools.find((t) => t.name === toolCall.name);
        
        if (tool) {
          const toolResult = await tool.invoke(toolCall.args);
          messages.push(
            new AIMessage({
              content: JSON.stringify(toolResult),
              name: toolCall.name,
            })
          );
        }
      }
    } catch (error: any) {
      // 6. Handle HTTP 429 Rate Limits from Truto/Botpress
      if (error.response && error.response.status === 429) {
        const resetHeader = error.response.headers['ratelimit-reset'];
        const retryAfterSeconds = resetHeader ? parseInt(resetHeader, 10) : 5;
        
        console.warn(`Rate limit hit. Truto passed through a 429. Backing off for ${retryAfterSeconds} seconds...`);
        await new Promise(resolve => setTimeout(resolve, retryAfterSeconds * 1000));
        
        // The loop will automatically retry the last LLM invocation on the next pass
        // because we didn't push the failed tool call to the messages array.
      } else {
        console.error("Fatal error in agent execution:", error);
        break;
      }
    }
  }
}

// Execute the triage workflow
runBotpressAgent(
  "acct_botpress_987654321", 
  "Read the last messages from conversation ID 'conv_123'. Search the files for a solution, and send a reply to the user."
);
```

### Visualizing the Architecture

The architecture relies on a strict separation of concerns. The LLM handles reasoning, Truto handles the schema normalization and API proxying, and Botpress executes the underlying business logic. 

```mermaid
sequenceDiagram
    participant App as Your AI App
    participant LLM as Agent Framework<br>(LangChain)
    participant Truto as Truto<br>Proxy Layer
    participant Botpress as Botpress API

    App->>LLM: Pass user prompt
    LLM->>Truto: GET /integrated-account/{id}/tools
    Truto-->>LLM: Return strict JSON schemas<br>(Proxy APIs)
    
    Note over LLM: LLM decides to search<br>knowledge base files
    
    LLM->>Truto: Call botpress_files_search<br>with arguments
    Truto->>Botpress: Authenticated REST request
    Botpress-->>Truto: Return semantic<br>search results
    Truto-->>LLM: Return normalized<br>JSON data
    
    Note over LLM: LLM decides to<br>send a message
    
    LLM->>Truto: Call create_a_botpress_message
    Truto->>Botpress: POST message payload
    
    alt Rate Limit Hit
        Botpress-->>Truto: HTTP 429 Too Many Requests
        Truto-->>LLM: HTTP 429 + ratelimit-reset header
        Note over LLM: Agent sleeps based on<br>reset header, then retries
    else Success
        Botpress-->>Truto: HTTP 200 OK
        Truto-->>LLM: Message ID created
    end
    
    LLM-->>App: Return final natural<br>language response
```

## Moving Beyond the Prototype

Connecting Botpress to an AI agent is fundamentally a schema and infrastructure challenge. By utilizing a unified tools endpoint, you abstract away the polymorphic payloads, hierarchical routing, and authentication headaches that plague custom API wrappers.

Your LLMs operate safely within the boundaries of deterministic JSON schemas, while your application code retains total control over error handling and rate limit backoffs. This architecture gives you the power to automate complex customer support, workspace administration, and knowledge retrieval workflows without dedicating engineering cycles to maintaining the underlying Botpress connector.

> Stop hand-coding fragile SaaS connectors for your AI agents. Let Truto handle the proxy architecture, schema normalization, and authentication layer so your team can focus on building intelligent workflows.
>
> [Talk to us](https://cal.com/truto/partner-with-truto)
