Skip to content

Connect Ocrolus to AI Agents: Sync Transactions & Verify Income

Learn how to connect Ocrolus to AI agents using Truto's unified tool layer. Build autonomous workflows for income verification, fraud detection, and transaction parsing.

Uday Gajavalli Uday Gajavalli · · 9 min read
Connect Ocrolus to AI Agents: Sync Transactions & Verify Income

You want to connect Ocrolus to an AI agent so your system can independently parse bank statements, extract enriched transactions, calculate self-employed income, and flag fraud signals based on historical context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to maintain complex, vendor-specific API wrappers.

Giving a Large Language Model (LLM) read and write access to your Ocrolus instance is a serious engineering undertaking. You either spend weeks building, hosting, and maintaining a custom connector that understands the nuances of Ocrolus's asynchronous job pooling, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Ocrolus to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Ocrolus 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 Ocrolus, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex underwriting 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 Custom Ocrolus 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 structurally opinionated as Ocrolus.

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

The Book and Document Hierarchy

Ocrolus does not just accept a file and return a flat JSON of transactions. Data is strictly organized into Books, which act as stateful containers for Documents. When an agent needs to extract income data from a borrower's uploaded PDF, it cannot simply "parse the PDF." It must first create a Book, upload the Document to that specific Book, wait for processing to complete, and then query the Book for analytics.

If you hand-code this, you must write complex prompts to teach the LLM this strict sequence of operations. When the LLM inevitably hallucinates and tries to run an income calculation on a raw Document UUID instead of the parent Book UUID, the API throws an error, and the agent loop crashes.

The Asynchronous Polling Trap for Large Datasets

Ocrolus handles massive volumes of transactional data. When requesting cash flow analytics or enriched transactions for a Book, the behavior changes based on data volume. For Books with over 100,000 transactions, you must append an async=true parameter. Instead of returning the payload, Ocrolus returns a job_id.

Standard LLM tool-calling assumes synchronous request-response cycles. An LLM does not natively understand how to park its current reasoning step, store a job ID, schedule a polling mechanism via ocrolus_cash_flow_get_job_status, and resume reasoning once a presigned URL is returned. Exposing raw Ocrolus endpoints forces the LLM to manage this complex state orchestration.

Mutually Exclusive Identifiers

Almost every major Ocrolus endpoint strictly enforces mutually exclusive identifiers. You must provide either a book_uuid OR a pk (primary key). If an LLM accidentally passes both because it found both in the context window from a previous response, the Ocrolus API rejects the request with a 400 Bad Request. Teaching an LLM conditional parameter exclusion via system prompts is highly unreliable and wastes tokens.

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.

Direct API tools (one tool per raw Ocrolus endpoint) push all of these provider quirks directly into the LLM's context. The model has to remember the Book hierarchy, the polling logic, and the mutually exclusive ID rules. Every one of those quirks is a hallucination waiting to happen.

A unified tool layer collapses these complexities behind a clean, deterministic schema. Your agent interfaces with a strictly typed set of proxy tools exposed by Truto's /tools endpoint.

  1. Smaller attack surface for hallucination: The LLM chooses from clearly defined function names with explicit parameter requirements. It never invents UUID formats or guesses query parameters.
  2. Deterministic input validation: Every tool has a strict JSON schema. Invalid arguments (like passing both a UUID and a PK) are rejected at the proxy layer before they hit Ocrolus, allowing the agent to instantly self-correct based on standard error formatting.
  3. Framework Agnosticism: You fetch standard JSON Schema definitions that compile perfectly into .bindTools() for LangChain, Vercel AI SDK, or CrewAI without rewriting wrapper functions.

Hero Tools for Ocrolus

Instead of exposing 70+ endpoints to your agent and polluting the context window, Truto exposes highly focused proxy tools. Here are the highest-leverage operations for building autonomous financial agents.

Extract Enriched Transactions

ocrolus_transactions_list_enriched

Retrieves fully categorized and enriched transactions from a processed Book. This tool abstracts away the raw optical character recognition (OCR) output and directly delivers actionable financial data, including enrichment tags, categories, and counterparties. Crucial for agents performing spend analysis or ledger reconciliation.

"Fetch the enriched transactions for Book UUID '8f7a6b5c-4d3e-2f1a' and filter the output to show only recurring subscription payments to software vendors."

Upload Mixed PDF Documents

ocrolus_documents_upload_mixed_pdf

Uploads a mixed PDF (containing multiple statement types or interleaved pages) to an Ocrolus Book for automatic classification. The agent does not need to know how to split the PDF; it just passes the file and the target Book UUID, relying on Ocrolus's machine learning backend to classify forms appropriately.

"Take this user-provided bank statement PDF and upload it as a mixed document to their existing underwriting Book (UUID: '3a2b1c0d'). Let me know when the upload is confirmed."

Calculate Fannie Mae Self-Employed Income

ocrolus_income_calculate_self_employed_fm

Executes complex income calculations for a borrower using Fannie Mae underwriting guidelines. Instead of the LLM attempting to do math on raw bank statement lines (which leads to catastrophic hallucinations), the agent invokes this tool to let Ocrolus handle the strict regulatory calculation engine.

"Calculate the self-employed income using Fannie Mae guidelines for Borrower '7x8y9z' in Book '1a2b3c'. Return the final calculated monthly average."

Retrieve Cash Flow Features

ocrolus_cash_flow_get_features

Analyzes all bank statements in a Book to generate deep cash flow analytics. This provides the agent with structured data regarding average balances, overdraft frequencies, and revenue trajectories, which the agent can then use to synthesize a final credit memo.

"Get the cash flow feature analytics for Book '99aa88bb'. Summarize the borrower's risk of insolvency based on their historical overdraft frequency."

Detect Fraud Signals

ocrolus_books_get_fraud_signals

Retrieves forensic fraud detection signals for a specific Book. If documents have been tampered with, digitally altered, or contain inconsistent metadata, this tool exposes those signals. The agent can use this to autonomously route high-risk applications to a human underwriter.

"Check the fraud signals for Book '55cc44dd'. If any document shows signs of digital tampering or font mismatches, flag the application and write a warning note."

For the complete tool inventory, request schemas, and parameter details, visit the Ocrolus integration page.

Workflows in Action

Here is how an AI agent strings these tools together to execute complex, multi-step financial operations autonomously.

Scenario 1: Mortgage Underwriting Automation

An agent is tasked with evaluating a self-employed borrower's ability to pay based on raw uploaded bank statements.

"Process the new documents uploaded by John Doe. Verify there are no signs of fraud, calculate his self-employed income according to Fannie Mae guidelines, and draft a summary for the loan committee."

Agent Execution Steps:

  1. ocrolus_documents_upload_mixed_pdf: The agent takes the raw files provided in the prompt context and uploads them to the borrower's Book.
  2. ocrolus_books_get_status: The agent polls the status until the documents are fully digitized and classified.
  3. ocrolus_books_get_fraud_signals: The agent checks the forensic integrity of the uploaded statements. Seeing a clean return, it proceeds.
  4. ocrolus_income_calculate_self_employed_fm: The agent runs the compliance-grade math on the processed Book.

Output: The agent generates a confident credit memo based on deterministic mathematical outputs from the Ocrolus engine, rather than attempting to calculate income by parsing text itself.

Scenario 2: Commercial Credit Risk Assessment

A B2B fintech needs to assess the cash flow health of a small business applicant.

"Review the recent statement history for Acme Corp. I need to know if they have volatile cash flow and what their primary expenditure categories are."

Agent Execution Steps:

  1. ocrolus_cash_flow_get_features: The agent requests the cash flow analytics to determine balance volatility and revenue velocity.
  2. ocrolus_transactions_list_enriched: The agent pulls the categorized transaction ledger.

Output: The agent synthesizes the raw JSON from both tools. It provides the user with a plain-English summary highlighting that Acme Corp has high cash flow volatility and that 40% of their expenditures are tagged as short-term debt servicing.

Building Multi-Step Workflows

To build these autonomous systems, you need an architecture that scales safely. Rather than hardcoding Axios requests for every Ocrolus endpoint, you use Truto's /tools endpoint. This returns a dynamic, OpenAPI-compliant list of JSON Schemas representing the integration's capabilities.

Here is how you fetch the tools and bind them to an agent using LangChain.js. This approach works equally well with Vercel AI SDK or LangGraph.

import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";
 
async function runUnderwritingAgent() {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // 2. Initialize the Truto Tool Manager
  // This SDK handles fetching the proxy schemas from the /tools endpoint
  const trutoManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
  });
 
  // 3. Fetch tools specifically for your Ocrolus integration
  // The integratedAccountId represents the specific user's connected Ocrolus instance
  const ocrolusTools = await trutoManager.getTools(
    "your-ocrolus-integrated-account-id"
  );
 
  // 4. Create the prompt instructing the agent on its role
  const prompt = ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a senior credit analyst. You have access to tools that interact with the Ocrolus API. Always check for fraud before calculating income. If a rate limit error occurs, inform the user you are backing off.",
    ],
    ["human", "{input}"],
    new MessagesPlaceholder("agent_scratchpad"),
  ]);
 
  // 5. Bind the tools and create the agent
  const agent = await createOpenAIToolsAgent({
    llm,
    tools: ocrolusTools,
    prompt,
  });
 
  const agentExecutor = new AgentExecutor({
    agent,
    tools: ocrolusTools,
    // Ensure the agent doesn't get stuck in an infinite loop if API errors occur
    maxIterations: 5, 
  });
 
  // 6. Execute the workflow
  const result = await agentExecutor.invoke({
    input: "Fetch the cash flow features for Book UUID 'b3f5c9a1' and summarize their risk profile.",
  });
 
  console.log(result.output);
}

Architecting for Resilience: Rate Limits and Retries

When putting AI agents into production, they will hit rate limits. Because an agent operates autonomously, it can fire off dozens of API requests in seconds as it loops through reasoning steps.

It is a critical factual architectural point: Truto does not retry, throttle, or apply backoff on rate limit errors. Truto is designed as a low-latency proxy layer. When the upstream Ocrolus API returns an HTTP 429 Too Many Requests, Truto passes that error directly to the caller (your application).

To ensure uniformity, Truto normalizes the upstream rate limit information into standardized IETF headers across all integrations:

  • ratelimit-limit: The total number of requests allowed in the current window.
  • ratelimit-remaining: The number of requests remaining.
  • ratelimit-reset: The time at which the limit resets.

The caller (your agent framework or wrapper code) is strictly responsible for inspecting these headers and implementing retry/backoff logic. If you do not catch 429s in your tool execution logic, the LLM will see a raw error, hallucinate a fix, and likely burn tokens trying to call the API repeatedly until it hits the maxIterations cap.

Here is how that flow looks architecturally:

sequenceDiagram
    participant Agent as AI Agent Framework
    participant Truto as Truto Tool Layer
    participant Ocrolus as Ocrolus API

    Agent->>Truto: Execute tool: ocrolus_cash_flow_get_features
    Truto->>Ocrolus: Forward standardized HTTP request
    Ocrolus-->>Truto: 429 Too Many Requests (Vendor format)
    Truto-->>Agent: 429 Error with normalized ratelimit-* headers
    Note over Agent: Agent logic reads ratelimit-reset.<br>Sleeps thread, then retries.
    Agent->>Truto: Retry tool: ocrolus_cash_flow_get_features
    Truto->>Ocrolus: Forward request
    Ocrolus-->>Truto: 200 OK (Cash flow payload)
    Truto-->>Agent: Returns JSON payload to context window

By injecting an interceptor or wrapper around the LLM's tool execution phase that reads Truto's normalized headers, you can safely pause the agent, wait out the ratelimit-reset window, and resume execution without failing the entire workflow.

Moving Forward

Connecting AI agents to complex financial apis like Ocrolus requires structural rigor. If you expose raw endpoints, your LLM will inevitably hallucinate query parameters, mishandle UUIDs, and crash on pagination loops. By abstracting the integration through Truto's /tools endpoint, you collapse the attack surface, enforce deterministic schema validation, and ensure your agent focuses on reasoning rather than reverse-engineering API quirks.

FAQ

Does Truto automatically handle API rate limits for Ocrolus?
No. Truto passes upstream HTTP 429 Too Many Requests errors directly back to the caller. However, Truto normalizes the rate limit information into standard headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset), allowing your agent framework to accurately implement its own retry and backoff logic.
Can I use Truto's tools with any agent framework?
Yes. Truto's /tools endpoint exposes standard JSON Schemas that are completely framework-agnostic. You can bind them natively using LangChain, LangGraph, CrewAI, or Vercel AI SDK.
How does an AI agent handle large Ocrolus books exceeding 100k transactions?
For massive datasets, Ocrolus requires asynchronous processing. The agent triggers the tool, receives a job_id, and must use a separate polling tool (like ocrolus_cash_flow_get_job_status) to retrieve the data once processing is complete.

More from our Blog