---
title: "Connect Perkville to AI Agents: Orchestrate Tiers & Transactions"
slug: connect-perkville-to-ai-agents-orchestrate-tiers-and-transactions
date: 2026-08-04
author: Roopendra Talekar
categories: ["AI & Agents"]
excerpt: "Learn how to connect Perkville to AI agents using Truto's /tools endpoint. Build autonomous workflows for loyalty tiers, point transactions, and referrals."
tldr: Connect Perkville to AI agents using Truto's /tools endpoint. Bypass custom integration boilerplate and safely orchestrate loyalty programs and points.
canonical: https://truto.one/blog/connect-perkville-to-ai-agents-orchestrate-tiers-and-transactions/
---

# Connect Perkville to AI Agents: Orchestrate Tiers & Transactions


You want to connect Perkville to an AI agent so your internal systems can independently manage loyalty programs, update point balances, process reward redemptions, and orchestrate referral workflows based on customer behavior. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to manually wire up complex loyalty API logic.

Giving a Large Language Model (LLM) read and write access to your Perkville instance is a significant engineering challenge. You either spend weeks building, hosting, and maintaining a custom connector that understands the nuanced relationships between global users and business-specific connections, or you use a managed infrastructure layer that handles the abstraction for you. If your team uses ChatGPT, check out our guide on [connecting Perkville to ChatGPT](https://truto.one/connect-perkville-to-chatgpt-sync-loyalty-rules-and-user-points/), or if you are building on Anthropic's models, read our guide on [connecting Perkville to Claude](https://truto.one/connect-perkville-to-claude-manage-rewards-and-referral-programs/). 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](https://truto.one/the-best-unified-apis-for-llm-function-calling-ai-agent-tools-2026/) for Perkville, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex customer loyalty operations. 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](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/) of Custom Perkville Connectors

Building AI agents is easy in isolation. Connecting them to external SaaS APIs is hard. Giving an LLM access to external loyalty data sounds simple in a Jupyter notebook prototype. You write a short Python script that makes a fetch request and wrap it in an `@tool` decorator. In production, this approach collapses entirely, especially with an ecosystem as structurally specific as Perkville.

If you decide to build a Perkville integration yourself, you own the entire API lifecycle. Perkville's API introduces several highly specific integration challenges that break standard LLM assumptions.

### The Global User vs. Local Connection Trap

Perkville operates on a multi-tenant loyalty model where a single human `User` exists globally across the platform, but their loyalty points, tier status, and rewards only exist within the context of a specific `Business`. The bridge between these two entities is called a `Connection`.

When a customer asks an AI agent to "check my point balance," a standard CRUD API design would look for `GET /users/me/points`. In Perkville, the agent must first identify the global user, locate the specific business ID for your brand, and then query the `Connection` or `Connection Balance` object. If you hand-code this integration, you have to write exhaustive system prompts teaching the LLM this exact bipartite relationship. When the LLM inevitably hallucinates and tries to query a user ID for points without specifying the business ID, the API rejects the request. 

### Earning vs. Redeeming State Machines

Another specific quirk of the Perkville API is the strict separation between earning mechanisms and redemption mechanics. Users earn points through `Challenges`, `Frequency Bonus Perks`, and `Transactions`. When they want to use those points, they don't simply "subtract" points. They redeem a reward which generates a `Voucher`. That voucher then exists in an `INITIAL` state and must be explicitly updated to a `USED` status when the customer actually claims the reward at the point of sale.

If you expose raw Perkville endpoints to an LLM, the model has to infer this state machine. It has to know that a reward redemption requires querying the `Perk` catalog, generating a `Voucher`, and later mutating that voucher. Exposing the raw OpenAPI spec directly to an LLM pushes all of these provider quirks into the model's context window, increasing latency, consuming expensive tokens, and maximizing the surface area for hallucinations.

### Rate Limits and The 429 Reality

When AI agents execute multi-step reasoning loops (like searching for fifty users and checking their balances one by one), they generate sudden spikes in API traffic. Perkville, like all production SaaS APIs, enforces rate limits.

It is critical to understand how Truto handles these limits: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Perkville API returns an HTTP 429 Too Many Requests, Truto passes that error directly back to the caller. 

However, Truto standardizes the chaos. It normalizes the upstream rate limit information into standard IETF headers across all integrations: `ratelimit-limit`, `ratelimit-remaining`, and `ratelimit-reset`. Your agent framework is responsible for reading these headers and executing the appropriate retry or backoff logic. This prevents your agent from entering an infinite fail-loop and gives you exact programmatic control over API consumption.

## Why a Unified Tool Layer Matters for Agent Safety

Before writing a line of integration code, you must decide what layer your agent talks to. This architectural choice dictates the safety and reliability of your production system.

Direct API tools (one tool per raw Perkville endpoint) look convenient, but they force the LLM to understand custom object structures, pagination cursors, and deeply nested JSON schemas. A [unified tool layer](https://truto.one/the-best-unified-apis-for-llm-function-calling-ai-agent-tools-2026/) collapses these complexities.

Truto provides a proxy abstraction by exposing every `Method` defined on a `Resource` as an isolated, [schema-validated tool](https://truto.one/what-is-llm-function-calling-for-integrations-2026-guide/). Your agent sees `create_a_perkville_transaction`, `get_single_perkville_connection_by_id`, and `update_a_perkville_voucher_by_id`. That gives you concrete safety wins:

1.  **Deterministic input validation.** Every tool has a strict JSON schema. If the LLM tries to pass a string to a boolean field, the tool layer rejects it before it hits Perkville, failing fast.
2.  **Smaller attack surface for hallucination.** The LLM only ever chooses from stable function names with explicitly defined parameters. It never invents query parameter syntax.
3.  **Automatic context management.** Truto's tools handle authentication injection and endpoint routing dynamically based on the active integrated account, keeping bearer tokens out of the LLM context window entirely.

## Essential Perkville Tools for AI Agents

Truto exposes the complete Perkville API surface area through the `/integrated-account/<id>/tools` endpoint. Rather than dumping the entire inventory into your prompt, you should selectively bind high-leverage tools that match your agent's specific persona. 

Here are six hero tools that enable the most powerful autonomous loyalty workflows.

### create_a_perkville_connection

This tool is the entry point for onboarding. It joins a global Perkville user to your specific business's loyalty program. It creates the critical `Connection` object that tracks their point balance and lifetime earned points.

> "A new customer, sarah.connor@example.com, just completed her first purchase. Enroll her in our rewards program under our main business ID."

### get_single_perkville_connection_by_id

Agents use this tool to fetch the current state of a user's loyalty profile. It returns the point balance, lifetime earned points, membership status, and level progress. This is the foundation for any agent answering customer support queries about points.

> "Look up the loyalty profile for connection ID 987654. How many points does this customer have, and what tier are they currently in?"

### create_a_perkville_transaction

This is the engine for custom earning workflows. When an agent detects a trigger outside of standard Perkville tracking (like a customer attending a webinar, or resolving a major support issue), it calls this tool to award points. It requires the business ID and either a user ID or email.

> "Award 500 bonus points to james.holden@example.com for completing our annual feedback survey. Tag the transaction classification as 'Bonus'."

### list_all_perkville_challenges_view

Challenges are complex gamification mechanics. This tool fetches challenges from the perspective of the user, showing their display status, requirements, and progress. Agents use this to intelligently recommend next actions to a user to maximize their rewards.

> "Check the active challenges for user 12345 at our business. Tell me how close they are to completing the 'Summer Spend' challenge."

### create_a_perkville_referral

Referrals are a massive driver of organic growth. This tool allows an agent to programmatically generate a referral record between two users, tracking the source, status, and associated reward voucher.

> "Customer A (ID 4455) just recommended Customer B (email: newuser@example.com) in their chat support session. Log this as a formal referral in Perkville so they both get their points when the new user buys."

### update_a_perkville_voucher_by_id

When a user wants to redeem a reward, they receive a voucher. This tool allows the agent to update the status of that voucher to `USED` once the customer actually applies the discount code or receives the physical item, closing the loop on the redemption state machine.

> "The customer just applied their $10 off reward on their current order. Mark voucher ID 883321 as USED in Perkville so it cannot be claimed again."

For the complete tool inventory, detailed schemas, and parameter requirements, refer to the [Truto Perkville integration page](https://truto.one/integrations/detail/perkville).

## Workflows in Action

Exposing individual tools is just the first step. The real value of AI agents emerges when they chain these tools together to execute complex, multi-step operations that would normally require human intervention.

Here are two concrete examples of how an agent uses the Truto tools layer to solve real business problems.

### Workflow 1: The Apology Point Concierge

Customer support agents often need to manually issue "make-good" points to customers who experience shipping delays or broken products. An autonomous agent can monitor support tickets, verify the user's loyalty status, and issue points automatically based on the severity of the issue.

> **User Prompt:** "Ticket #9921 states that Alice (alice@example.com) received a damaged item. We verified the damage. She is upset. Check her loyalty tier, and if she is active, award her 1,000 points as an apology."

**Execution Steps:**
1.  The agent receives the prompt and extracts the email `alice@example.com`.
2.  It calls `list_all_perkville_connections` filtered by email to find her specific `Connection` ID and current `status`.
3.  Observing the status is `ACTIVE` and her point balance is 4,500, the agent decides to proceed.
4.  The agent calls `create_a_perkville_transaction` with the business ID, Alice's email, and `points: 1000`, setting a classification of 'Support Apology'.
5.  The agent replies: *"Alice is an active loyalty member with 4,500 points. I have successfully awarded her an additional 1,000 apology points. Her new balance will reflect shortly."*

```mermaid
sequenceDiagram
  participant SupportSystem as Support Agent
  participant AIAgent as AI Agent
  participant TrutoAPI as Truto API
  participant Perkville as Perkville API

  SupportSystem->>AIAgent: "Check Alice's tier and give 1000 points"
  AIAgent->>TrutoAPI: Call list_all_perkville_connections (email=alice@...)
  TrutoAPI->>Perkville: GET /v1/connection?email=alice@...
  Perkville-->>TrutoAPI: 200 OK (Connection ID 102)
  TrutoAPI-->>AIAgent: Returns Connection Data
  AIAgent->>TrutoAPI: Call create_a_perkville_transaction (points=1000)
  TrutoAPI->>Perkville: POST /v1/transaction
  Perkville-->>TrutoAPI: 201 Created
  TrutoAPI-->>AIAgent: Returns Transaction Success
  AIAgent-->>SupportSystem: "1000 points awarded successfully."
```

### Workflow 2: Gamification Nudge Campaigns

Marketing teams want to send personalized emails pushing users to complete loyalty challenges. An AI agent can run a daily cron job to evaluate user progress and generate customized email copy based on their exact distance from a reward.

> **User Prompt:** "Analyze the challenge progress for user ID 77665. Figure out what they need to do to complete their active challenge, and write a two-sentence personalized SMS nudge to encourage them."

**Execution Steps:**
1.  The agent calls `list_all_perkville_challenges_view` for the specific user ID.
2.  It identifies the 'Visit 5 Times' challenge, noting the user has a `progress_count` of 4 and needs 1 more visit.
3.  The agent synthesizes this structured JSON data into natural language.
4.  The agent replies: *"Hey there! You are only 1 visit away from unlocking your free coffee reward. Stop by today and claim your prize!"*

## Building Multi-Step Workflows

To implement these workflows in code, you need to connect your agent framework to Truto. Truto is [framework-agnostic](https://truto.one/the-best-unified-apis-for-llm-function-calling-ai-agent-tools-2026/). Because the `/tools` endpoint returns tools formatted with standard JSON schemas, they map directly into LangChain, LangGraph, CrewAI, or the Vercel AI SDK.

Below is a production-ready TypeScript example using `TrutoToolManager` from the `truto-langchainjs-toolset`. This implementation demonstrates fetching the tools, binding them to an OpenAI model, and explicitly handling the API rate limits we discussed earlier.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { TrutoToolManager } from "truto-langchainjs-toolset";

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

// 2. Define the system prompt with strict operational rules
const prompt = ChatPromptTemplate.fromMessages([
  ["system", `You are a loyalty operations agent managing a Perkville account.
   You have access to tools that can read point balances and award transactions.
   Always verify a user's connection status before awarding points.
   If a tool returns an error, explain the failure concisely.`],
  ["human", "{input}"],
  ["placeholder", "{agent_scratchpad}"],
]);

async function runPerkvilleAgent(integratedAccountId: string) {
  try {
    // 3. Fetch specific Perkville tools from Truto for this tenant
    const trutoManager = new TrutoToolManager({
      integratedAccountId: integratedAccountId,
    });
    
    // Filter tools to only include the ones we need for safety
    const tools = await trutoManager.getTools();
    const loyaltyTools = tools.filter(tool => 
      ['get_single_perkville_connection_by_id', 'create_a_perkville_transaction'].includes(tool.name)
    );

    // 4. Bind the tools to the agent
    const agent = createToolCallingAgent({ llm, tools: loyaltyTools, prompt });
    const executor = new AgentExecutor({
      agent,
      tools: loyaltyTools,
      maxIterations: 5,
    });

    // 5. Execute a multi-step query
    const result = await executor.invoke({
      input: "Check the profile for connection ID 5544. If they are ACTIVE, award them 200 points for a store visit."
    });

    console.log("Agent Action Complete:", result.output);

  } catch (error: any) {
    // 6. Handle HTTP 429 Rate Limits from Truto passthrough
    if (error.response && error.response.status === 429) {
      const limit = error.response.headers.get('ratelimit-limit');
      const reset = error.response.headers.get('ratelimit-reset');
      console.error(`Rate limit exceeded! Limit: ${limit}. Try again at UNIX timestamp: ${reset}`);
      // Implement your application-level backoff/retry queue here
    } else {
      console.error("Agent execution failed:", error.message);
    }
  }
}
```

Notice how the error handling explicitly checks for `status === 429` and reads the normalized `ratelimit-reset` header. Because Truto standardizes these headers according to the IETF specification, you can write this retry logic once, and it will work identically whether your agent is talking to Perkville, Salesforce, or HubSpot.

```mermaid
graph TD
  A["LLM Framework<br>(LangChain/CrewAI)"] -->|"Agent requests tool call"| B["Truto Tool Layer<br>(Schema Validation)"]
  B -->|"Valid JSON"| C["Truto Proxy Layer<br>(Auth Injection)"]
  B -.->|"Invalid Schema"| E["Fast Fail<br>(Returned to Agent)"]
  C -->|"HTTP POST /transaction"| D["Perkville API"]
  D -->|"HTTP 429 Too Many Requests"| C
  C -->|"Standardized ratelimit-* headers"| A
```

## Architecting for Production

Connecting Perkville to AI agents fundamentally changes how your business operates customer loyalty. By utilizing a unified tool layer, you remove the burden of maintaining auth lifecycles, translating complex OpenAPI specs, and manually validating JSON payloads. 

Instead of wasting engineering cycles on custom API wrappers, your team can focus on designing sophisticated reasoning loops that drive revenue. Your agent can check point balances, execute tier upgrades, manage referral lifecycles, and automatically resolve support tickets - all executed safely within strict operational boundaries.

> Stop hardcoding SaaS integrations for your AI agents. Partner with Truto to instantly give your LLMs secure, schema-validated access to Perkville and 150+ other business APIs.
>
> [Talk to us](https://cal.com/truto/partner-with-truto)
