---
title: "Connect Refersion to AI Agents: Automate Prospects & Manual Credits"
slug: connect-refersion-to-ai-agents-automate-prospects-manual-credits
date: 2026-09-16
author: Uday Gajavalli
categories: ["AI & Agents"]
excerpt: Learn how to connect Refersion to AI agents using Truto's /tools endpoint. Build autonomous affiliate marketing workflows and manual credit loops.
tldr: "Connect Refersion to AI agents to autonomously manage affiliates, generate prospect pitches, and issue manual credits. This guide shows how to fetch Refersion tools via Truto and bind them to frameworks like LangChain or Vercel AI SDK."
canonical: https://truto.one/blog/connect-refersion-to-ai-agents-automate-prospects-manual-credits/
---

# Connect Refersion to AI Agents: Automate Prospects & Manual Credits


You want to connect Refersion to an AI agent so your system can autonomously evaluate affiliate prospects, issue manual conversion credits, and resolve payment disputes without human intervention. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to build and maintain a custom Refersion integration from scratch.

Giving a Large Language Model (LLM) read and write access to your affiliate tracking platform is an engineering challenge. You either spend weeks reading API documentation, configuring OAuth flows, and writing JSON schemas by hand, or you leverage a unified integration layer that handles the boilerplate natively. If your team uses ChatGPT, check out our guide on [connecting Refersion to ChatGPT](https://truto.one/connect-refersion-to-chatgpt-manage-affiliates-track-performance/), or if you are building on Anthropic's models, read our guide on [connecting Refersion to Claude](https://truto.one/connect-refersion-to-claude-optimize-offers-promotion-workflows/). 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 Refersion, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex affiliate operations workflows. 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 of the Refersion API

Giving an LLM access to external affiliate 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 complex financial and marketing systems, this approach collapses.

Refersion's API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities.

### Mutually Exclusive State Transitions

When updating an affiliate in Refersion, an LLM naturally assumes it can pass a flat JSON object containing all the fields it wants to change. For example, if an agent decides to approve and lock a high-risk affiliate simultaneously, it might attempt to send `{"status": "APPROVED", "locked": true}`.

Refersion rejects this. The API enforces strict state machine rules where the `locked` field cannot be combined with `status` in the same request. Furthermore, the `locked` field is only accepted if the affiliate's current status is already `APPROVED`. If your agent has raw access, it will repeatedly hallucinate invalid state transitions. By passing this through a normalized tool schema, the agent is forced to execute a sequential logic chain: check status, update status to approved, wait for success, then update lock state.

### Polymorphic Activity Feeds

The Refersion activity timeline is highly polymorphic. When you request an affiliate's recent activity, the API merges conversions, payments, and clicks into a single chronological array. 

Standard LLMs struggle heavily with polymorphic JSON arrays because the expected keys shift entirely from object to object. A conversion entry includes `conversionCount` and `currency`, while a payment entry contains entirely different settlement fields. Without strict JSON schema definitions defining a `oneOf` or `anyOf` relationship for these types, the LLM will hallucinate fields across types - for example, assuming a payment object has a `conversionCount`.

### The Manual Credit Matrix

Generating a manual credit is not just inserting a record into a database; it triggers an ecosystem of side effects. Creating a manual credit in Refersion requires specifying exact approval statuses (`PENDING`, `APPROVED`, `DENIED`). If the status is `APPROVED` or `DENIED`, Refersion automatically dispatches webhook notifications and generates secondary audit records (`conversion_info`). 

If an agent haphazardly pushes manual credits to test an endpoint, it will spam external affiliates with automated emails. You need a tool layer that restricts the agent's parameters to safe, bounded inputs before they ever touch the upstream API.

## Rate Limits and Architectural Delegation

Before deploying your agent, you must fundamentally understand [how rate limits work in an AI context](https://truto.one/how-to-handle-third-party-api-rate-limits-when-an-ai-agent-is-scraping-data/). Agentic loops - especially those utilizing frameworks like LangGraph or AutoGen - can generate hundreds of API requests in seconds as they iterate through reasoning steps.

When using Truto to connect to Refersion, **Truto does not retry, throttle, or apply backoff on rate limit errors.** This is an intentional architectural decision to prevent hidden latency loops.

When the Refersion API returns an HTTP 429 (Too Many Requests), Truto passes that error directly to the caller. However, Truto normalizes the upstream [rate limit information](https://truto.one/how-to-handle-third-party-api-rate-limits-when-an-ai-agent-is-scraping-data/) into standardized headers per the IETF specification:

*   `ratelimit-limit`: The maximum number of requests allowed in the current window.
*   `ratelimit-remaining`: The number of requests left.
*   `ratelimit-reset`: The time at which the rate limit window resets.

Your orchestration layer (the agent loop) is entirely responsible for reading these headers, parsing the reset time, and executing the appropriate retry and backoff logic. Do not assume the integration layer will magically absorb rate limit errors on behalf of an overactive LLM.

## Hero Tools for Refersion Workflows

Truto exposes Refersion endpoints as pre-configured tools with strict JSON schemas. You fetch these dynamically via the `/tools` endpoint. Here are the core "hero" tools that enable high-leverage affiliate operations.

### list_all_refersion_affiliates

This tool retrieves Refersion affiliates along with their profile information, offer details, and performance metrics. It supports complex filtering by status, search terms, offer IDs, and performance thresholds.

**Contextual Usage:** Agents use this as the primary discovery mechanism. Before taking action on an account, the agent must pull the affiliate's `id` and current `status`. The rich performance metrics returned make it ideal for agents tasked with auditing low-performing accounts or identifying top earners.

> "Find all affiliates assigned to the 'Summer Campaign' offer who have a status of APPROVED and more than 50 conversions this month."

### update_a_refersion_affiliate_by_id

This tool allows partial updates to an affiliate's details, including status, custom fields, and URL configurations. 

**Contextual Usage:** Agents use this for automated account remediation. Because of Refersion's mutually exclusive field rules, agents must use this tool sequentially - for instance, first calling it to set `status` to `APPROVED`, and then calling it again to set `locked` to `true`. It requires the `id` obtained from the list tool.

> "Approve affiliate ID 84920 and update their custom registration field for 'Tax ID' with the provided string."

### refersion_affiliates_get_activity

Retrieves weekly conversion, payment, and click activity for a specific affiliate, returning a merged, time-bounded timeline.

**Contextual Usage:** This is the agent's primary analytical tool. When investigating a sudden drop in affiliate performance or verifying activity before issuing a manual credit, the agent calls this tool to ingest the rolling 10-week polymorphic activity feed. The strict schema provided by Truto prevents the LLM from confusing a click record with a payment record.

> "Pull the recent activity feed for affiliate ID 3921. Summarize their click-to-conversion ratio over the last 10 weeks."

### refersion_conversions_create_manual_credit

Creates a manual credit conversion for an affiliate. It requires the affiliate ID, commission total, currency, and a strict approval status.

**Contextual Usage:** Revenue Operations agents use this tool to resolve tracking disputes. If an affiliate proves they drove a sale that was missed by cookie tracking, the agent can autonomously issue the credit. Because passing `APPROVED` triggers real emails to the affiliate, agents should often be instructed to pass `PENDING` to require human-in-the-loop sign-off.

> "Issue a manual credit of $50.00 USD to affiliate ID 1044 for the missed referral. Set the status to PENDING for final manager review."

### refersion_prospects_get_pitch

Retrieves an existing pitch or generates a personalized AI pitch message for contacting a prospect within the Refersion ecosystem.

**Contextual Usage:** A prime example of recursive AI utility. Your custom marketing agent can orchestrate outreach by calling this tool to fetch Refersion's natively generated pitch copy. The agent can then take that pitch, refine it against your brand voice guidelines, and push it to an email API.

> "Get the personalized pitch message for prospect ID 992. I need to format it into our company's standard email template."

### refersion_conversions_bulk_update

Updates the status of a Refersion conversion, supporting transitions between PENDING, APPROVED, DENIED, and UNQUALIFIED.

**Contextual Usage:** Used for massive cleanup operations. If your fraud detection agent flags a series of orders as high-risk, it can iterate over the conversion IDs and use this tool to transition them to `DENIED`. This automatically handles the transition matrix and dispatches the necessary webhook notifications upstream.

> "Update the status of conversion ID 55219 to DENIED based on the high fraud score returned from the payment processor."

To view the complete inventory of available Refersion operations, required parameters, and JSON schemas, visit the [Refersion integration page](https://truto.one/integrations/detail/refersion).

## Workflows in Action

Connecting these tools to an LLM unlocks autonomous workflows that typically require hours of manual work from Affiliate Managers and Revenue Operations teams. Here is how specific personas utilize these capabilities in production.

### 1. Automated Prospect Discovery & Pitching (Marketing Manager)

Marketing teams spend countless hours identifying potential partners and drafting outreach emails. An AI agent handles this loop autonomously.

> "Find 5 new high-value prospects in the SaaS category, fetch their personalized pitches, rewrite the pitches to include our Q3 bonus structure, and prepare the email drafts."

**Execution Steps:**
1.  The agent calls `list_all_refersion_prospects` with `more=true` to trigger a discovery job and filter for the specified category.
2.  The agent loops through the returned prospect IDs.
3.  For each ID, it calls `refersion_prospects_get_pitch` to retrieve the baseline messaging context.
4.  The LLM processes the returned text internally, applies the prompt instructions regarding the Q3 bonus, and outputs the final drafts to the user.

**Result:** The Marketing Manager receives five highly tailored, data-backed email drafts ready to send, cutting prospect research time from hours to seconds.

### 2. Affiliate Dispute Resolution & Manual Crediting (Affiliate Ops)

When a top-tier affiliate complains about a missing commission, response time is critical to maintaining the relationship. An agent can verify the claim and stage the remedy instantly.

> "Affiliate John Doe is claiming he missed a $100 commission for an enterprise referral last week. Check his recent activity to see if there is a pending conversion. If not, stage a manual credit of $100 USD as PENDING and alert me."

**Execution Steps:**
1.  The agent calls `list_all_refersion_affiliates` using the search term "John Doe" to extract the affiliate's exact `id`.
2.  The agent calls `refersion_affiliates_get_activity` for that ID to analyze the 10-week timeline, specifically scanning for recent uncredited conversions.
3.  Upon finding no matching conversion, the agent calls `refersion_conversions_create_manual_credit` passing the `id`, `commissionTotal` as 100, `currency` as USD, and `approvalStatus` as PENDING.
4.  The agent returns a summary confirming the action is ready for manager approval.

**Result:** The Affiliate Ops team simply logs in, sees the staged manual credit, clicks approve, and closes the ticket.

```mermaid
sequenceDiagram
    participant User as User
    participant Agent as AI Agent
    participant Truto as Truto Tool Layer
    participant Refersion as Refersion API

    User->>Agent: "Check John Doe's activity & stage $100 credit"
    Agent->>Truto: list_all_refersion_affiliates (Search: John Doe)
    Truto->>Refersion: GET /api/affiliates
    Refersion-->>Truto: Affiliate ID 442
    Truto-->>Agent: JSON Schema Response
    Agent->>Truto: refersion_affiliates_get_activity (ID: 442)
    Truto->>Refersion: GET /api/affiliates/442/activity
    Refersion-->>Truto: Polymorphic Activity Array
    Truto-->>Agent: Clean JSON Schema
    Agent->>Truto: refersion_conversions_create_manual_credit (ID 442, $100, PENDING)
    Truto->>Refersion: POST /api/conversions/manual_credit
    Refersion-->>Truto: 201 Created
    Truto-->>Agent: Success Confirmation
    Agent-->>User: "Credit staged for approval."
```

## Building Multi-Step Workflows

To build these agents, you need to bind the Refersion tools provided by Truto's API directly to your LLM. This approach is completely framework-agnostic - whether you are building a graph in LangGraph, defining crews in CrewAI, or streaming UI components with the Vercel AI SDK, the methodology remains the same.

The critical engineering task is building a resilient execution loop. Because Truto passes HTTP 429s directly to your system, your code must inspect tool execution errors, read the standard `ratelimit-reset` header, and halt the agent loop until the window clears.

Here is an architectural example using TypeScript and the `truto-langchainjs-toolset`:

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

// 1. Initialize the Truto Tool Manager
const toolManager = new TrutoToolManager({
    trutoApiKey: process.env.TRUTO_API_KEY,
    integratedAccountId: process.env.REFERSION_ACCOUNT_ID,
});

async function runAffiliateAgent() {
    // 2. Fetch all available Refersion tools dynamically
    const tools = await toolManager.getTools();
    
    const llm = new ChatOpenAI({
        modelName: "gpt-4o",
        temperature: 0,
    });

    // 3. Bind the fetched tools to the LLM
    const llmWithTools = llm.bindTools(tools);

    const prompt = ChatPromptTemplate.fromMessages([
        ["system", "You are a Revenue Operations agent managing Refersion. Do not invent IDs. Always lookup affiliates first. If a tool call fails due to a rate limit (429), inform the user."],
        ["human", "{input}"],
        ["placeholder", "{agent_scratchpad}"],
    ]);

    const agent = await createOpenAIToolsAgent({
        llm: llmWithTools,
        tools,
        prompt,
    });

    const executor = new AgentExecutor({
        agent,
        tools,
        maxIterations: 10,
    });

    try {
        // 4. Execute the multi-step workflow
        const result = await executor.invoke({
            input: "Find affiliate John Doe and check his activity timeline."
        });
        
        console.log(result.output);

    } catch (error) {
        // 5. Handle Rate Limits explicitly
        if (error.status === 429) {
            const resetTime = error.headers['ratelimit-reset'];
            console.error(`Refersion API rate limited. Reset at: ${resetTime}. Pausing agent execution.`);
            // Implement your backoff/retry queue logic here
        } else {
            console.error("Agent execution failed:", error);
        }
    }
}

runAffiliateAgent();
```

In this setup, the LLM decides which tools to call and in what order based on the rich descriptions provided by Truto. If the agent hits a limit, the catch block intercepts the 429 status and extracts the `ratelimit-reset` header, preventing the agent from burning tokens in a panicked retry loop.

> Need to connect AI agents to Refersion, Salesforce, or NetSuite? Truto handles the schema [normalization, auth, and tool definitions](https://truto.one/the-best-unified-apis-for-llm-function-calling-ai-agent-tools-2026/) so you can focus on building intelligent workflows. Talk to our engineering team today.
>
> [Talk to us](https://truto.one/book-a-demo/)

## Moving Beyond Point-to-Point Scripts

Building AI agents that reliably manipulate financial data and marketing relationships requires abandoning point-to-point integration scripts. Direct integrations push API quirks, nested data objects, and polymorphic arrays directly into your LLM's context window, radically increasing the surface area for hallucinations.

By leveraging Truto's unified tool layer, your agents interact with a deterministic, sanitized interface. They know exactly what parameters are required for a manual credit, they process polymorphic activity feeds seamlessly, and they fail predictably when encountering strict rate limits. Stop fighting API documentation and start building autonomous workflows that scale.
