Connect Cin7 Core to AI Agents: Orchestrate Sales and CRM Workflows
Give your AI agent Cin7 Core tools.
Connect Cin7 Core to AI agents (LangChain, Vercel AI) using Truto. This guide covers bypassing ERP API quirks, handling multi-stage order states, and fetching dynamic LLM tools for revenue ops.
In this guide
- 01Define the AI Agent Architecture
- 02Fetch Cin7 Core Tools via Truto
- 03Bind Tools to the LLM
- 04Implement Rate Limit Backoff
- 05Execute Multi-Step Workflows
The guide
Learn how to connect Cin7 Core to AI agents using Truto's /tools endpoint. Build autonomous workflows for inventory, sales, and supply chain orchestration.
You want to connect Cin7 Core to an AI agent so your system can autonomously process wholesale orders, audit inventory levels, dispatch fulfillments, and sync CRM data. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom ERP integration from scratch.
Enterprise Resource Planning (ERP) systems are inherently unforgiving. When you give a Large Language Model (LLM) read and write access to your Cin7 Core instance, it cannot afford to hallucinate API payloads, guess at multi-stage task states, or ignore strict inventory constraints. If your team uses ChatGPT, check out our guide on connecting Cin7 Core to ChatGPT, or if you are building on Anthropic's models, read our guide to connecting Cin7 Core to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.
Building an AI agent is largely an exercise in state management and deterministic prompting. Giving that agent reliable access to an external ERP API is where projects typically stall. If you decide to build a custom connector, you own the entire API lifecycle. You must write the JSON schemas for the LLM to understand the endpoints, handle the OAuth token lifecycle, normalize pagination, and manage rate limits.
This guide breaks down exactly how to fetch AI-ready tools for Cin7 Core, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex supply chain workflows. For a broader look at this design pattern, read our research on Architecting AI Agents: LangGraph, LangChain, and the SaaS Saas Integration Bottleneck.
The Engineering Reality of the Cin7 Core API
Giving an LLM access to external data sounds simple in a Jupyter Notebook. You write a Python function that makes a fetch request and wrap it in an @tool decorator. In production against complex ERPs like Cin7 Core, this approach collapses under its own weight.
Cin7 Core (formerly DEAR Inventory) has a highly specific architectural model. If you hardcode standard REST assumptions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities.
The Multi-Stage Task System
Cin7 Core does not treat a "Sale" or a "Purchase" as a single flat database row. Almost all major operations in Cin7 Core are multi-stage tasks. For example, a single Sale object (SaleID) acts as a parent container for multiple distinct sub-objects: Quotes, Orders, Invoices, and Fulfillments.
Standard LLMs expect to call create_sale and be done. In Cin7 Core, an agent must first initialize the sale, then transition the state to AUTHORISED, then specifically target the fulfillment sub-task to generate picking lists. Pushing this state-machine logic into the LLM's prompt context requires massive token overhead and leads to frequent hallucinations where the model attempts to pack invoice data into a quote payload.
Strict Payload Validations
Cin7 Core enforces strict validation rules that change based on the document's state. You cannot create a payment against a DRAFT invoice. You cannot use the Simple Purchase endpoints for transactions requiring put-away workflows (you must use Advanced Purchases). The model has to remember all these rules unless your tool layer normalizes them into separate, safely constrained functions.
Punishing Rate Limits
Cin7 Core applies strict rate limiting (often 60 calls per minute, per account). When this limit is hit, the API aggressively rejects requests.
Truto does not hide this from your agent. Truto does not retry, throttle, or apply backoff on rate limit errors. When an upstream API returns an HTTP 429, Truto passes that error directly to the caller. However, Truto normalizes the upstream rate limit info into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF spec. Your agent framework is strictly responsible for handling the retry and backoff logic. If your LLM gets trigger-happy with a pagination loop, your code must catch the 429 and pause execution deterministically.
Hero Tools for Cin7 Core AI Agents
To safely expose Cin7 Core to an LLM, Truto provides pre-configured tools via the /tools endpoint. These tools abstract away the pagination and authentication boilerplate while exposing strict JSON schemas that the LLM can reliably satisfy.
Here are the highest-leverage tools available for orchestrating sales and CRM workflows in Cin7 Core.
1. list_all_cin_7_core_products
Before an agent can create a quote or order, it must identify the correct SKU and product ID. This tool allows the agent to search the Cin7 Core product catalog, optionally filtering by SKU, name, or modification date.
Contextual Usage Notes: Agents should always use this tool to verify product availability and extract the exact ProductID before attempting to construct an order payload. Guessing SKUs is a primary source of 400 Bad Request errors.
"Find the product ID and current price tier for the SKU 'WIDGET-200' in our catalog."
2. create_a_cin_7_core_sale
This tool initializes a new sale container in Cin7 Core. It creates the parent record including the customer details, billing/shipping addresses, and the base currency.
Contextual Usage Notes: Creating a sale does not automatically invoice the customer. The agent must first create the sale, extract the returned ID, and pass that ID to the downstream order and invoice tools.
"Create a new sales record for 'Acme Corp'. They are a wholesale customer using USD. Use their default billing address."
3. create_a_cin_7_core_sale_order
Once the parent sale exists, this tool attaches the actual line items, quantities, and prices to the order phase.
Contextual Usage Notes: The agent must explicitly set the Status to AUTHORISED if the order is finalized. Leaving it in DRAFT will prevent downstream fulfillment tools from executing successfully. The agent must supply the SaleID from the previous step.
"Add 50 units of product ID 12345 to Sale ID 98765. Set the price to $12.50 per unit and authorize the order."
4. list_all_cin_7_core_customers
CRM workflows require accurate customer records. This tool allows the agent to lookup existing customers, fetch their credit limits, and retrieve their specific tax rules and default sales reps.
Contextual Usage Notes: Encourage your agents to fetch customer records by email or exact name match before creating new ones to prevent duplicate CRM entries.
"Look up the customer record for 'Stark Industries'. Return their CustomerID and current credit limit."
5. create_a_cin_7_core_sale_fulfilment
This is a critical operations tool. It instructs Cin7 Core to begin the fulfillment process for an authorized sale, transitioning the task into the Pick, Pack, and Ship stages.
Contextual Usage Notes: This tool will fail if the underlying order is not authorized or if there is insufficient stock in the selected location. Agents must be prompted to handle inventory shortfall errors gracefully.
"Initialize the fulfillment process for Sale ID 98765 from the 'Main Warehouse' location."
6. list_all_cin_7_core_stocktakes
For autonomous inventory management, agents need visibility into active stocktakes (audits). This tool lists stocktake tasks, returning the effective dates, locations, and line-item variances.
Contextual Usage Notes: Use this tool to allow an agent to build a discrepancy report, comparing expected system stock against the physical counts recorded in a COMPLETED stocktake.
"Retrieve all stocktakes that were completed last week for the 'East Coast Hub' and list any items with negative variances."
To view the complete schema definitions and the full inventory of over 100 available methods, visit the Cin7 Core integration page.
Workflows in Action
Giving an agent isolated tools is only half the architecture. The true value of AI agents emerges when they chain these tools together to execute complex, multi-step business logic autonomously. Here are two real-world examples of how agents orchestrate Cin7 Core workflows.
Scenario 1: Autonomous B2B Wholesale Ordering
Persona: Sales Operations Automation
When a large wholesale client sends an unstructured email requesting a restock, the AI agent can parse the request and execute the entire order-to-cash pipeline in Cin7 Core without human intervention.
"Acme Corp just emailed us asking for 500 units of the Pro Widget and 200 units of the Basic Widget. Process this order in Cin7 Core and prepare the invoice."
Execution Steps:
- The agent calls
list_all_cin_7_core_customerssearching for "Acme Corp" to retrieve theirCustomerID, default tax rules, and price tier. - The agent calls
list_all_cin_7_core_productsto look up the exactProductIDs for "Pro Widget" and "Basic Widget", verifying current stock levels. - The agent calls
create_a_cin_7_core_salepassing theCustomerIDto generate the parent sale container, storing the returnedSaleID. - The agent calls
create_a_cin_7_core_sale_orderusing theSaleID, appending the line items for the widgets, and setting theStatustoAUTHORISED. - Finally, the agent calls
create_a_cin_7_core_sale_invoiceto generate the financial record for the accounting sync.
Outcome: The user receives a confirmation that a fully authorized sales order and invoice have been generated in the ERP, complete with correct wholesale pricing, saving 15 minutes of manual data entry.
Scenario 2: Proactive Inventory Auditing and Reordering
Persona: Supply Chain Manager
Agents can monitor system health and trigger supply chain workflows when inventory anomalies are detected.
"Check our recent stock adjustments. If any key products in the Main Warehouse dropped below their reorder point, draft a purchase order for our primary supplier."
Execution Steps:
- The agent calls
list_all_cin_7_core_stockadjustment_listsfiltering for recentCOMPLETEDadjustments. - The agent identifies a massive write-off for a specific component and calls
list_all_cin_7_core_productsto check the currentOnHandmetrics for that item. - Detecting a shortfall, the agent calls
list_all_cin_7_core_product_suppliersto find the default vendor and unit cost for the missing component. - The agent calls
create_a_cin_7_core_advanced_purchaseto initialize a new advanced purchase order with the supplier. - The agent calls
create_a_cin_7_core_advanced_purchase_invoice(draft mode) and surfaces the PO number to the user for final approval.
Outcome: The user receives an actionable summary of the inventory drop along with a pre-drafted PO ready for a single-click approval, ensuring the supply chain never stalls due to unmonitored write-offs.
Building Multi-Step Workflows
To implement these workflows in production, you need to connect the Truto tools to your chosen agent framework. Truto's architecture is framework-agnostic. We provide SDKs (like truto-langchainjs-toolset) that map Truto Proxy APIs directly into native tool schemas.
Because Truto handles the OAuth token lifecycle and normalizes the data structures, your application code only needs to handle the agent orchestration and the upstream rate limit backoff.
Here is the architectural flow of how a multi-step agent request traverses the system:
sequenceDiagram
participant User as User
participant Agent as Agent Framework (LangGraph)
participant Truto as Truto Unified API
participant Upstream as Upstream API (Cin7 Core)
User->>Agent: "Create a B2B wholesale order for Acme Corp."
Agent->>Truto: fetch("https://api.truto.one/integrated-account/<id>/tools")
Truto-->>Agent: Returns JSON schema for Cin7 Core methods
Agent->>Agent: LLM selects create_a_cin_7_core_sale
Agent->>Truto: POST /proxy/cin7core/sales
Truto->>Upstream: POST /Sale
Upstream-->>Truto: HTTP 429 Too Many Requests
Truto-->>Agent: HTTP 429 (with ratelimit-reset header)
Agent->>Agent: Caller pauses and retries
Agent->>Truto: POST /proxy/cin7core/sales
Truto->>Upstream: POST /Sale
Upstream-->>Truto: 200 OK (Sale Created)
Truto-->>Agent: 200 OK (Normalized response)
Agent-->>User: "Sale created successfully."Handling Rate Limits in the Agent Loop
As noted in the diagram, Truto does not absorb rate limit errors. Cin7 Core restricts API traffic, and Truto respects that by returning the 429 status code directly to your agent.
However, Truto normalizes the arbitrary rate limit headers from the underlying provider into the IETF standard. Your agent execution loop must read the ratelimit-reset header and apply a programmatic pause.
Here is how you initialize the tools in TypeScript using LangChain, and implement a basic execution wrapper to handle the rate limit backoff:
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
async function runCin7CoreAgent(prompt: string) {
// 1. Initialize the LLM
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
});
// 2. Fetch tools dynamically from Truto
const toolManager = new TrutoToolManager({
trutoApiKey: process.env.TRUTO_API_KEY,
integratedAccountId: process.env.CIN7_CORE_ACCOUNT_ID,
});
// Filter for tools relevant to sales and products to save context space
const tools = await toolManager.getTools({
methods: ["read", "write"],
});
// 3. Create the Agent
const promptTemplate = ChatPromptTemplate.fromMessages([
["system", "You are a senior supply chain assistant. Execute Cin7 Core tasks meticulously. Always check product IDs before creating orders."],
["user", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
const agent = await createOpenAIToolsAgent({
llm,
tools,
prompt: promptTemplate,
});
const executor = new AgentExecutor({
agent,
tools,
// Return early if the LLM gets stuck in a loop
maxIterations: 10,
});
// 4. Execute with Rate Limit awareness
try {
const result = await executor.invoke({ input: prompt });
console.log("Agent Result:", result.output);
} catch (error) {
if (error.status === 429) {
const resetTime = error.headers.get('ratelimit-reset');
console.warn(`Rate limit hit. Agent framework must pause until ${resetTime}`);
// Implement your application-specific sleep/queue logic here
} else {
console.error("Agent execution failed:", error);
}
}
}
// Execute the B2B Wholesale workflow
runCin7CoreAgent("Create a sales record for 'Acme Corp'. Find their CustomerID, then add 50 units of SKU 'WIDGET-200' to the order.");By relying on Truto's /tools endpoint, you completely sidestep the integration maintenance burden. When Cin7 Core updates their API schema, Truto updates the JSON definitions automatically. Your agent fetches the latest schema on initialization and adjusts its function calls accordingly, ensuring your workflows remain durable over time.
Orchestrating the ERP Lifecycle
Connecting AI agents to a monolithic ERP like Cin7 Core is not about mapping basic CRUD operations - it is about orchestrating deeply connected state machines. A single LLM prompt might touch customer records, inventory ledgers, tax rules, and financial invoicing pipelines.
If you push the complexity of the raw Cin7 Core API into your LLM's context window, you guarantee high token costs, brittle execution loops, and dangerous data hallucinations. By placing a unified tool layer between your agent and the ERP, you collapse that complexity into deterministic, strictly validated schemas.
Your agents can navigate the multi-stage complexities of advanced purchasing, stocktakes, and wholesale ordering with confidence, while your engineering team avoids writing a single line of OAuth or pagination boilerplate.
FAQ
- How do AI agents interact with the Cin7 Core API?
- AI agents interact with Cin7 Core by consuming OpenAPI or JSON schemas that map to the underlying API endpoints. Using Truto's /tools endpoint, developers can provide frameworks like LangChain with native function-calling schemas for operations like creating sales or syncing stock.
- Does Truto automatically handle Cin7 Core rate limits?
- No. Truto passes HTTP 429 Too Many Requests errors directly back to the caller. However, Truto normalizes the upstream rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset), allowing your agent framework to execute deterministic retry and backoff logic.
- Can I use these tools with the Vercel AI SDK?
- Yes. Truto's tool definitions are framework-agnostic. They output standard JSON schemas that can be bound directly to LLMs using Vercel AI SDK, LangChain, LangGraph, CrewAI, or any other agent orchestration framework.
- Why not use a standard REST integration for Cin7 Core?
- Cin7 Core's data model heavily relies on nested multi-stage tasks (e.g., a sale contains separate sub-objects for quotes, orders, invoices, and fulfillment). Hand-rolling these state transitions for an AI agent introduces massive hallucination risks. A unified tool layer collapses these complexities into strict, verifiable schemas.