Connect LearnWorlds to AI Agents: Automate User and Group Data
Learn how to connect LearnWorlds to AI agents using Truto's tools endpoint. Automate user management, group enrollments, and complex LMS workflows with LangChain.
You want to connect LearnWorlds to an AI agent so your system can automatically manage student lifecycles, audit instructor roles, and orchestrate group enrollments based on behavioral triggers. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom Learning Management System (LMS) connector from scratch.
If your team uses ChatGPT, check out our guide on connecting LearnWorlds to ChatGPT, or if you are looking to build within the Anthropic ecosystem, read our guide on connecting LearnWorlds to Claude. For engineering teams building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework. This approach works natively across LangChain, LangGraph, CrewAI, and the Vercel AI SDK.
Giving a Large Language Model (LLM) read and write access to your LearnWorlds instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector, dealing with undocumented API behaviors and pagination edge cases, or you use a managed infrastructure layer that handles the boilerplate for you. If you are evaluating different providers, see our comparison of the best unified APIs for LLM function calling and AI agent tools.
This guide breaks down exactly how to fetch AI-ready tools for LearnWorlds, bind them natively to an LLM, and execute complex LMS workflows. For context on the overarching architecture of this approach, refer to our guide on Architecting AI Agents: LangGraph, LangChain, and the SaaS Integration Bottleneck.
The Engineering Reality of the LearnWorlds API
Building AI agents is straightforward in isolation. Connecting them to external SaaS APIs in production is difficult. Giving an LLM access to external data sounds simple in a local prototype: you write a Node.js function that makes a fetch request to the LearnWorlds API and wrap it in an @tool decorator.
In production, this approach collapses entirely. If you decide to build a custom integration for LearnWorlds, you own the entire API lifecycle. The LearnWorlds API introduces specific integration challenges that break standard CRUD assumptions and will quickly cause a naive LLM agent to hallucinate or crash.
The User Object State Machine
In standard SaaS applications, a user is just an identity profile - a name and an email address. In an LMS like LearnWorlds, a user is a complex state machine. The LearnWorlds user object contains deeply nested arrays governing access states: is_admin, is_instructor, is_suspended. It also houses behavioral data like nps_score, nps_comment, and dynamic tags. If you pass an unoptimized schema to an LLM, the model will struggle to determine whether it should update a core profile attribute or an access flag, often hallucinating parameters that the API will reject with a 400 Bad Request error.
Group to Product Entanglements
LearnWorlds relies heavily on Groups to manage cohorts of students. However, Groups are not just isolated directories. They are entangled with products (courses). When an agent interacts with a LearnWorlds Group, it encounters the enroll_users_on_courses flag and the products array. Moving a user into a group can trigger cascading enrollments. An AI agent needs strict, explicit tool descriptions to understand that adding a user to a group is a high-leverage action that changes course access, not just a cosmetic tag update.
Rate Limits and the IETF Spec
LearnWorlds enforces rate limits to protect its infrastructure. If an AI agent attempts to iterate through thousands of students to identify inactive users without proper throttling, LearnWorlds will return an HTTP 429 Too Many Requests error.
It is critical to understand that Truto does not retry, throttle, or apply backoff on rate limit errors automatically. When an upstream API returns a 429, 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) per the IETF spec. The engineering responsibility lies entirely with you: your agent loop must intercept these headers and implement exponential backoff or explicit waiting mechanisms before retrying the tool call. For sophisticated workflows, you should also consider how to handle long-running SaaS API tasks in AI agent tool-calling workflows.
Exposing LearnWorlds to the LLM
Truto maps underlying SaaS endpoints into REST-based proxy APIs, handling all pagination, authentication, and query parameter processing. We then expose descriptions and JSON schemas for all the methods defined on these resources. To understand the underlying mechanics of how these schemas enable agentic behavior, check out our 2026 guide on LLM function calling for integrations.
When solving problems agentically, these Proxy APIs are highly effective because the LLM can handle data normalization on its own using the raw data, provided the tools are clearly defined.
Here are the highest-leverage LearnWorlds tools available via Truto's /tools endpoint for AI agents.
list_all_learn_worlds_users
This tool enables the agent to pull a directory of all users in the LMS. It returns an array of user objects including fields like email, username, created dates, role, tags, and account status. It also handles the pagination metadata under the meta object.
Usage note: Agents should use this tool when auditing massive cohorts or identifying users based on specific status flags before diving into individual user operations.
"Retrieve a list of all active users in the LearnWorlds instance who have logged in within the last 30 days, and extract their associated tags."
get_single_learn_worlds_user_by_id
This tool fetches the complete, nested profile of a specific LearnWorlds user using their unique ID. It returns complex states including admin/instructor flags, suspension status, billing information, UTMs, and direct NPS survey results.
Usage note: Always chain this tool after a search or list operation. The detailed payload is too large to request in bulk, making this the precision instrument for investigating an individual student's engagement or satisfaction.
"Fetch the full profile for user ID 'xyz-123'. Check their recent nps_score and nps_comment. If the score is below 6, summarize their feedback."
list_all_learn_worlds_roles
This tool queries the LMS to return all user roles. It provides the ID, title, description, access level, and whether it is a custom role, sorted alphabetically by title.
Usage note: Use this for security and governance workflows. An agent can ingest the available roles before making decisions about promoting a student to an instructor or restricting access.
"List all available roles in LearnWorlds and identify any custom roles that have administrative access levels."
list_all_learn_worlds_groups
This tool retrieves all user cohorts within the system. It returns the group ID, title, description, associated products (courses), and the group_managers object detailing who owns the cohort.
Usage note: Essential for mapping the organizational structure of your LMS. Agents can use this to figure out which group a specific corporate client or class is tied to.
"Audit all groups in the system. Return a list of group titles alongside the emails of their designated group managers."
get_single_learn_worlds_group_by_id
This tool fetches the exact state of a specific group, exposing its internal structure, timestamps, and whether the enroll_users_on_courses rule is active for the associated products.
Usage note: Before an agent adds a batch of users to a group, it should call this tool to understand the consequences - specifically, which exact courses those users will instantly gain access to.
"Check the configuration for group ID 'grp-789'. Confirm which course products are tied to this group and whether automatic enrollment is enabled."
To view the complete inventory of available proxy tools, endpoint schemas, and required parameters, visit the LearnWorlds integration page.
Workflows in Action
When you provide an LLM with these standardized, schema-backed tools, it can string together complex operational workflows that would normally require a human administrator clicking through the LearnWorlds dashboard for hours.
Workflow 1: The At-Risk Student Intervention
Managing student retention requires identifying unhappy learners before they churn or request refunds. An AI agent can monitor NPS scores and orchestrate interventions autonomously.
"Find the user profile for the student with email 'alex@example.com'. Check their recent NPS score. If it is a detractor score (0-6), find out which groups they belong to and notify the group manager."
- The agent calls
list_all_learn_worlds_userswith a query filter for the specific email address to retrieve the user's ID. - The agent calls
get_single_learn_worlds_user_by_idto inspect the nestednps_scoreandnps_comment. - Recognizing a low score, the agent reads the user's tags or metadata to identify their cohort.
- The agent calls
list_all_learn_worlds_groupsto match the cohort, then callsget_single_learn_worlds_group_by_idto extract thegroup_managersarray. - The agent synthesizes the NPS comment and the manager's contact info, outputting a highly contextual alert.
Workflow 2: Instructor Role Auditing
Security and governance in an LMS demand constant vigilance. You need to ensure that only authorized personnel hold instructor or admin roles across various groups.
"Audit the 'Corporate Compliance Q3' group. Check all designated group managers and verify that none of them have suspended accounts. Also, confirm what roles they hold."
- The agent searches for the group using
list_all_learn_worlds_groupsto find the ID for 'Corporate Compliance Q3'. - The agent calls
get_single_learn_worlds_group_by_idand extracts the array of users listed undergroup_managers. - For each manager ID, the agent iterates through
get_single_learn_worlds_user_by_id. - The agent inspects the
is_suspendedflag and theroleattribute for each manager. - The agent compiles an audit report detailing any managers with non-instructor roles or suspended accounts.
Building Multi-Step Workflows
To implement these workflows in your own infrastructure, you need to bind Truto's dynamically generated tools to your agent framework. Truto provides a TrutoToolManager in the truto-langchainjs-toolset SDK that calls the GET https://api.truto.one/integrated-account/<id>/tools endpoint.
This endpoint returns the Proxy APIs with their exact OpenAPI descriptions and JSON schemas, transforming them instantly into executable LLM tools. Because these tool schemas update automatically as soon as you customize a resource description in the Truto UI, your agent always has the most accurate instructions on how to interact with LearnWorlds.
Crucially, you must architect your agent loop to handle HTTP 429 rate limit errors natively. Truto passes these through with standard IETF headers. Your application logic must catch the 429, read the ratelimit-reset header, and pause execution.
Here is an architectural example of how to fetch tools, bind them to a LangChain model, and construct a resilient agent loop capable of handling strict LearnWorlds rate limits:
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
import { TrutoToolManager } from "truto-langchainjs-toolset";
async function runLearnWorldsAgent() {
// 1. Initialize the LLM
const llm = new ChatOpenAI({
modelName: "gpt-4-turbo-preview",
temperature: 0,
});
// 2. Fetch LearnWorlds Tools from Truto
const toolManager = new TrutoToolManager({
trutoApiKey: process.env.TRUTO_API_KEY,
integratedAccountId: "learnworlds-account-id-123",
});
// Fetch dynamically generated proxy tools
const tools = await toolManager.getTools();
console.log(`Loaded ${tools.length} LearnWorlds tools.`);
// 3. Define the System Prompt
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a senior LMS administrator managing a LearnWorlds environment. Use the provided tools to query user states, audit groups, and analyze data. If a tool request fails, assess the error and adjust your parameters."],
["user", "{input}"],
new MessagesPlaceholder("agent_scratchpad"),
]);
// 4. Create the Agent
const agent = await createOpenAIToolsAgent({
llm,
tools,
prompt,
});
const executor = new AgentExecutor({
agent,
tools,
});
// 5. Execute with Custom Rate Limit Handling Wrapper
const input = "Find the group manager for the 'Onboarding 2026' group and check if their account is currently suspended.";
try {
const result = await executeWithRateLimitHandling(executor, input);
console.log("Agent Result:", result.output);
} catch (error) {
console.error("Agent execution failed after retries.", error);
}
}
/**
* Wrapper to catch Truto's pass-through 429s and respect IETF ratelimit-reset headers.
*/
async function executeWithRateLimitHandling(executor: AgentExecutor, input: string, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
return await executor.invoke({ input });
} catch (error: any) {
// Check if the error is a 429 passed through from Truto
if (error?.response?.status === 429) {
attempt++;
const headers = error.response.headers;
// Extract IETF standard header passed by Truto
const resetTimeInSeconds = parseInt(headers['ratelimit-reset'] || '60', 10);
console.warn(`[429 Rate Limit Hit] LearnWorlds API throttling. Retrying in ${resetTimeInSeconds} seconds...`);
// Wait for the duration specified by the upstream API before letting the agent retry
await new Promise(resolve => setTimeout(resolve, resetTimeInSeconds * 1000));
continue;
}
throw error; // Throw non-429 errors immediately
}
}
throw new Error("Max rate limit retries exceeded.");
}
runLearnWorldsAgent();By leveraging Truto's Proxy APIs and dynamically binding them via the /tools endpoint, you drastically reduce the engineering surface area of your AI integration. Instead of hand-rolling authentication flows, mapping rigid data models, and hardcoding JSON schemas for complex LearnWorlds objects, you allow the LLM to inspect the raw API capabilities natively.
Remember, AI agents are only as capable as the infrastructure connecting them to external systems. When you separate the business logic of your LangGraph or Vercel AI framework from the chaotic reality of third-party REST APIs, your engineering team can focus on agent behavior instead of maintaining broken LMS connectors.
FAQ
- Does Truto automatically handle rate limits for the LearnWorlds API?
- No. Truto does not retry, throttle, or apply backoff on rate limit errors. When LearnWorlds returns an HTTP 429, Truto passes that error to the caller and normalizes the rate limit info into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). The caller's application logic must handle the retry and backoff.
- Can I use Truto's LearnWorlds tools with LangGraph or CrewAI?
- Yes. Truto's tools endpoint is framework-agnostic. While our SDK natively supports LangChain.js via TrutoToolManager, the dynamically generated JSON schemas can be bound to any multi-agent framework including LangGraph, CrewAI, or the Vercel AI SDK.
- Why should I use Truto Proxy APIs instead of Unified APIs for my AI agent?
- Unified APIs force a standardized data model, which is helpful for programmatic data syncs but can strip out unique platform features. When building autonomous agents, Proxy APIs are better because they provide direct access to the raw LearnWorlds data structures, allowing the LLM to process custom tags, states, and nested objects autonomously.