Skip to content

Connect Lob to AI Agents: Orchestrate Print Mail & Identity Checks

Learn how to connect Lob to AI Agents using Truto's tools endpoint. Execute print mail workflows, identity checks, and address verifications natively in LangChain.

Uday Gajavalli Uday Gajavalli · · 9 min read
Connect Lob to AI Agents: Orchestrate Print Mail & Identity Checks

You want to connect Lob to an AI agent so your system can autonomously verify addresses, generate physical mail, orchestrate identity checks, and manage mailing campaigns. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build a custom Lob integration from scratch.

If your team uses ChatGPT, check out our guide on connecting Lob to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Lob to Claude. For developers building custom autonomous workflows across any LLM framework - like LangChain, LangGraph, CrewAI, or the Vercel AI SDK - you need a programmatic way to fetch these tools and bind them to your agent.

Building an AI agent is an exercise in context management and state transitions. Giving that agent reliable access to a physical mail API is where projects 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 API key lifecycle, normalize pagination, and deal with rate limiting.

This guide breaks down exactly how to fetch AI-ready tools for Lob, bind them natively to an LLM, and execute complex print and mail operations. For a broader look at this design pattern across all enterprise SaaS, read our guide on Architecting AI Agents: LangGraph, LangChain, and the SaaS Integration Bottleneck.

The Engineering Reality of the Lob API

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 against a physical fulfillment system like Lob, this approach collapses.

Lob's API introduces specific integration challenges tied to the physical reality of print and mail. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.

The XOR Address Constraint

Address verification is strict. When validating a US address or creating a mail piece, the Lob API accepts address input in two formats: structured components (primary_line, city, state, zip_code) or a single-line freeform address string. Crucially, it accepts one or the other - never both.

Standard LLMs are eager to please and prone to over-populating JSON payloads. If a model extracts an address from a user prompt, it will frequently attempt to send both the parsed components and the full string in the same API request. Lob rejects this with a 422 error. You must rely on strict JSON schema validation at the tool layer to enforce these mutually exclusive payload constraints before the request leaves your infrastructure.

Temporal State and the Cancellation Window

Physical mail operates on a strict timeline. Unlike standard CRUD APIs where you can issue a DELETE request at any time to remove a database record, canceling a Lob postcard or letter is bounded by physical production.

You can only successfully execute a delete operation if the mail piece's send_date has not passed. Once it enters production, the API will reject cancellation attempts. When giving an AI agent the ability to cancel mail, the agent must be able to query the resource, interpret the send_date timestamp against the current UTC time, and determine if the cancellation window is still open. Failing to provide this context results in agents hallucinating successful cancellations that actually failed.

Microdeposit Verification Logic

When setting up bank accounts for payments or check creation, live-mode accounts must be verified. Lob uses two different verification methods depending on the account's microdeposit_type. You either submit two deposit amounts in cents, or a 6-character SM-prefixed descriptor code. Submitting the wrong parameter type based on the account state returns an immediate error. Agents need the capability to read the account state first before selecting the verification path.

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 push provider quirks into the LLM's context window. A unified tool layer collapses the complexity behind stable schemas. Your agent sees deterministic functions with strict JSON definitions. That gives you concrete safety wins:

  1. Smaller attack surface for hallucination. The LLM chooses from specific, stable function names. It never invents query strings or invalid payload structures.
  2. Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments are rejected before they hit the upstream API, so a broken tool call fails fast.
  3. Decoupled authentication. The agent never sees bearer tokens or API keys. The execution layer handles the request signing securely.

Hero Tools for Lob Automation

Truto automatically maps Lob's API endpoints into a standardized REST structure and exposes them via the /tools endpoint. Here are the highest-leverage tools you should expose to your agent for print and mail automation.

create_a_lob_letter

Generates a physical letter from an HTML string, a PDF URL, or an existing template ID. This tool handles the core payload construction including recipient and sender addresses, color settings, and scheduling parameters.

"Generate a formal offer letter to Jane Doe at 123 Main St, Austin TX using template id tmpl_8675309. Set it to print in color, double-sided, and schedule the send date for next Monday."

create_a_lob_us_verification

Verifies a single US or US territory address. Crucial for agent workflows that need to validate data quality before initiating expensive print jobs. It returns a standardized response including deliverability status and normalized address lines.

"Check if the address '456 Tech Boulevard, Suite 200, San Francisco CA 94105' is deliverable. If it is valid, extract the primary line and the urbanization code."

delete_a_lob_letter_by_id

Cancels a scheduled Lob letter and removes it from production. This tool can only be executed before the send_date has passed. It is essential for workflows that require an approval step or allow users to catch mistakes.

"The user spotted a typo in the campaign. Cancel the scheduled letter with ID ltr_12345abcde immediately so we don't get charged for the print run."

list_all_lob_postcards

Lists Lob postcards ordered by creation date. Essential for auditing campaigns, checking the expected delivery dates of recent mailers, and retrieving IDs for subsequent operations.

"Pull the list of all postcards sent in the last week. Filter down to the ones that have an expected delivery date of today and list their tracking events."

create_a_lob_bank_account

Creates a new Lob bank account record, which is required before your system can issue physical checks. The agent must provide routing and account numbers, along with signatory details.

"Onboard the new vendor by creating a bank account record for Acme Corp using routing number 122000661 and their provided checking account details. Return the new bank ID so we can initiate microdeposit verification."

This is just a subset of the available operations. To see the complete inventory of supported tools and their JSON schemas, visit the Lob integration page.

Building Multi-Step Workflows

Agents rarely execute a single task. The real value of connecting Lob to AI Agents comes from multi-step orchestration where the output of one tool drives the logic of the next.

To build this, you need a framework-agnostic execution loop. The following example uses LangChain.js, but the architectural pattern applies equally to the Vercel AI SDK or CrewAI.

Truto provides a /tools endpoint that returns a list of Proxy APIs formatted specifically for LLM function calling. You fetch these tools, bind them to your model, and enter an execution loop.

Fetching Tools from Truto

Instead of manually writing JSON schemas for Lob's endpoints, you request them programmatically. Truto handles the schema generation.

// 1. Fetch AI-ready tools from Truto
async function getLobTools(integratedAccountId: string) {
  const response = await fetch(
    `https://api.truto.one/integrated-account/${integratedAccountId}/tools`,
    {
      headers: {
        Authorization: `Bearer ${process.env.TRUTO_API_KEY}`
      }
    }
  );
  
  if (!response.ok) {
    throw new Error(`Failed to fetch tools: ${response.statusText}`);
  }
  
  const { tools } = await response.json();
  return tools;
}

Handling Upstream Rate Limits (HTTP 429)

Factual note on rate limits: Truto does not retry, throttle, or absorb backoff on rate limit errors. When the upstream Lob API returns an HTTP 429, Truto passes that error directly to the caller. Truto normalizes the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) following the IETF spec.

The caller is entirely responsible for retry and backoff logic. Your agent execution loop must inspect these headers and pause execution if a limit is hit.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
 
async function executeLobWorkflow(prompt: string, accountId: string) {
  const llm = new ChatOpenAI({ modelName: "gpt-4o", temperature: 0 });
  
  // Initialize the Truto tool manager for the specific Lob account
  const toolManager = new TrutoToolManager({
    trutoApiKey: process.env.TRUTO_API_KEY!,
    integratedAccountId: accountId
  });
 
  // Fetch and bind the tools to the model
  const tools = await toolManager.getTools();
  const modelWithTools = llm.bindTools(tools);
  
  let messages = [{ role: "user", content: prompt }];
  
  // Agent execution loop
  while (true) {
    const response = await modelWithTools.invoke(messages);
    messages.push(response);
    
    if (!response.tool_calls || response.tool_calls.length === 0) {
      // The model has finished its task
      return response.content;
    }
    
    // Execute the requested tool calls
    for (const call of response.tool_calls) {
      try {
        // toolManager.execute executes the API request through Truto
        const toolResult = await toolManager.execute(call.name, call.args);
        messages.push({
          role: "tool",
          tool_call_id: call.id,
          name: call.name,
          content: JSON.stringify(toolResult)
        });
      } catch (error: any) {
        // Handle standard IETF rate limit headers passed through by Truto
        if (error.status === 429) {
          const resetTimeStr = error.headers['ratelimit-reset'];
          const resetMs = resetTimeStr ? parseInt(resetTimeStr) * 1000 : 5000;
          
          console.warn(`Rate limit hit. Waiting ${resetMs}ms before allowing retry...`);
          // In a production system, you would pause or enqueue the job here.
          // For this loop, we return the failure to the LLM so it knows it failed.
          messages.push({
            role: "tool",
            tool_call_id: call.id,
            name: call.name,
            content: `Error: Rate limit exceeded. Try again in ${resetMs}ms.`
          });
        } else {
          // Standard error reporting back to the agent
          messages.push({
            role: "tool",
            tool_call_id: call.id,
            name: call.name,
            content: `Error executing tool: ${error.message}`
          });
        }
      }
    }
  }
}

This architecture keeps your integration logic isolated from your agent logic. The LLM dictates the what, while the tools dictate the how.

Workflows in Action

When you give an agent access to these tools, it stops being a chatbot and becomes a revenue operations engine. Here are two concrete examples of how an AI agent uses Lob tools in production.

Use Case 1: Automated HR Onboarding Kits

When a new employee is added to your HRIS, an agent is triggered to verify their address and send a physical welcome kit via a trackable postcard.

"We just hired John Smith. His home address is listed as 789 Pine Lane, Apt 4B, Seattle WA. Verify this address. If it is deliverable, send the 'Welcome Aboard' postcard using template tmpl_welcome_99 to that exact address and return the expected delivery date."

Step-by-step Execution:

  1. The agent calls create_a_lob_us_verification passing the raw address string to ensure it meets USPS standards.
  2. The API returns a successful verification with standardized address components.
  3. The agent calls create_a_lob_postcard using the validated address data and the specified template ID.
  4. The user receives a summary confirming the mail piece is scheduled, including the expected_delivery_date parsed from the response.
sequenceDiagram
    participant User as User / Trigger
    participant Agent as AI Agent
    participant Truto as Truto Tool Layer
    participant Upstream as Lob API

    User->>Agent: Verify address & send postcard
    Agent->>Truto: call create_a_lob_us_verification
    Truto->>Upstream: POST /v1/us_verifications
    Upstream-->>Truto: 200 OK (Deliverable)
    Truto-->>Agent: Validation Result
    Agent->>Truto: call create_a_lob_postcard
    Truto->>Upstream: POST /v1/postcards
    Upstream-->>Truto: 200 OK (Postcard ID, Dates)
    Truto-->>Agent: Postcard Created
    Agent-->>User: Mission Accomplished. Delivery expected Friday.

Use Case 2: Campaign Audit and Erroneous Cancellation

A marketing operations manager realizes a massive batch of letters was scheduled with the wrong discount code and asks the agent to halt production.

"Audit all letters created today. Find any letter scheduled with the description 'Q4 Promo'. If its send date has not yet passed, cancel it immediately to save our print budget. Give me a list of all successfully canceled IDs."

Step-by-step Execution:

  1. The agent calls list_all_lob_letters with date filters applied to today.
  2. The agent parses the array, matching descriptions for 'Q4 Promo' and comparing the send_date against current UTC time.
  3. For every eligible letter, the agent calls delete_a_lob_letter_by_id iteratively.
  4. The user gets back a definitive list of IDs that were caught and canceled before entering the physical print queue.

The Strategic Move Away from Custom Integration Code

Connecting Lob to AI Agents requires treating the API as a strictly typed, immutable layer. If you hand-roll this integration, you are committing your engineering team to maintaining OAuth lifecycles, monitoring JSON schema drift, and fighting edge cases in physical mail fulfillment.

By routing agent tool calls through Truto, you decouple your AI logic from external API debt. Your agents get stable, deterministic functions to call, and your engineers get to focus on optimizing prompts and building better autonomous workflows.

FAQ

Does Truto automatically retry Lob API rate limits?
No. Truto passes upstream HTTP 429 rate limit errors directly to your agent, normalizing them into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your agent execution loop must handle the retry and backoff logic.
Can AI agents cancel Lob mail pieces?
Yes, using the delete_a_lob_letter_by_id or delete_a_lob_postcard_by_id tools. However, the agent must check the send_date timestamp, as Lob only permits cancellation if the send date has not yet passed.
Which LLM frameworks work with Truto's AI tools?
Truto's tools endpoint returns standardized JSON schemas that are framework-agnostic. You can bind them to LangChain, LangGraph, CrewAI, the Vercel AI SDK, or custom multi-agent orchestrators.
How does Truto handle Lob's strict address formatting?
Truto enforces strict JSON schemas on the tool inputs. This prevents the LLM from hallucinating payloads that contain both freeform address strings and structured components, resolving common HTTP 422 errors.

More from our Blog