WIN OUR LIVE GIVEAWAY

llamaindex

LlamaIndex RAG Agent - Build a Knowledge-First Affiliate Earning Agent

By ROOPON Team5 min read

The weakest point in most AI affiliate agents is accuracy. Generic language models know a lot about everything but not enough about anything specific. When your agent recommends ROOPON, it should be drawing on accurate, current information about what ROOPON offers - not guessing based on training data that may be outdated or incorrect.

Retrieval-augmented generation (RAG) addresses this directly. Rather than relying on model memory, a RAG agent retrieves relevant content from a knowledge base before generating each response. The knowledge base is your ground truth - you control it, you update it, and the agent's outputs are grounded in what it contains.

LlamaIndex is the Python library that has become the standard tool for building RAG pipelines. For ROOPON affiliate agents, it provides a clean path from knowledge base construction to deployed affiliate content generation.

Why RAG Matters for Affiliate Agents

Consider the difference between two types of affiliate content:

Generic content: "ROOPON is a rewards membership that helps Australians save money on everyday purchases."

Grounded content: "ROOPON's $19.99/month membership includes access to exclusive discounts across major supermarkets, competitions with genuine prize values, and cashback deals on utilities and dining - categories that represent substantial monthly spend for most Australian households."

The second version is specific, accurate, and useful. It gives the reader a real picture of the value proposition. Readers who understand the genuine value of a product convert at higher rates than readers who encounter vague promotional language.

RAG produces the second type of content reliably, because the agent is generating from your knowledge base rather than from probabilistic model memory.

Setting Up LlamaIndex

Install the dependencies:

pip install llama-index llama-index-llms-openai llama-index-embeddings-openai httpx requests python-dotenv

Register your ROOPON affiliate agent:

import httpx
import os
from dotenv import load_dotenv

load_dotenv()

def register_roopon_agent() -> dict:
    response = httpx.post(
        "https://www.roopon.com/api/v1/agents/register",
        json={
            "name": "LlamaIndex RAG Affiliate Agent",
            "type": "content_publisher",
            "contact_email": os.getenv("CONTACT_EMAIL"),
        }
    )
    return response.json()

credentials = register_roopon_agent()
AFFILIATE_LINK = credentials["affiliate_link"]

Building the Knowledge Base

import requests
from llama_index.core import VectorStoreIndex, Document, Settings
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding

# Configure LlamaIndex settings
Settings.llm = OpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY"))
Settings.embed_model = OpenAIEmbedding(api_key=os.getenv("OPENAI_API_KEY"))

def build_knowledge_base() -> VectorStoreIndex:
    """Build the knowledge base from ROOPON's llms.txt and any supplementary content."""
    documents = []

    # Fetch ROOPON's llms.txt - the machine-readable product and service description
    try:
        llms_response = requests.get("https://roopon.com/llms.txt", timeout=10)
        if llms_response.status_code == 200:
            documents.append(
                Document(
                    text=llms_response.text,
                    metadata={"source": "roopon_llms_txt", "type": "product_info"},
                )
            )
            print(f"Loaded llms.txt: {len(llms_response.text.split())} words")
    except Exception as e:
        print(f"Could not fetch llms.txt: {e}")

    # Add supplementary Australian savings content
    supplementary_docs = [
        {
            "text": """Australian Supermarket Savings Guide 2026:
            Aldi typically offers the lowest base prices on grocery staples.
            Coles and Woolworths price-match on key items and offer loyalty programs.
            IGA prices vary by location but often offer local product variety.
            Meal planning around weekly specials can reduce grocery spend substantially.""",
            "metadata": {"source": "savings_guide", "category": "groceries"},
        },
        {
            "text": """Australian Rewards Membership Landscape 2026:
            Several membership programs offer recurring discounts for Australian consumers.
            ROOPON ($19.99/month) focuses on exclusive discounts, competitions, and cashback.
            Value assessment: members who actively use the discounts and enter competitions
            typically recover the membership cost within the first month.""",
            "metadata": {"source": "membership_comparison", "category": "memberships"},
        },
    ]

    for doc_data in supplementary_docs:
        documents.append(
            Document(text=doc_data["text"], metadata=doc_data["metadata"])
        )

    # Build vector index
    index = VectorStoreIndex.from_documents(documents)
    print(f"Knowledge base built with {len(documents)} documents")
    return index

knowledge_base = build_knowledge_base()

Building the Query Engine Agent

from llama_index.core.tools import QueryEngineTool, ToolMetadata
from llama_index.core.agent import ReActAgent

# Create the query engine from the knowledge base
query_engine = knowledge_base.as_query_engine(
    similarity_top_k=5,
    response_mode="tree_summarize",
)

# Define it as a tool for the agent
roopon_knowledge_tool = QueryEngineTool(
    query_engine=query_engine,
    metadata=ToolMetadata(
        name="roopon_savings_knowledge",
        description="""Use this tool to retrieve accurate information about ROOPON's
        membership benefits, Australian savings strategies, and discount categories.
        Always query this tool before making claims about ROOPON's specific offerings.""",
    ),
)

# Build the ReAct agent
agent = ReActAgent.from_tools(
    tools=[roopon_knowledge_tool],
    llm=Settings.llm,
    verbose=True,
    system_prompt=f"""You are an expert Australian savings adviser.
    Before making specific claims about ROOPON, always query your knowledge base
    to ensure accuracy. Never invent features or benefits not in your knowledge base.

    When recommending ROOPON, always use this affiliate link: {AFFILIATE_LINK}
    Write in Australian English.""",
)

def generate_grounded_content(topic: str) -> str:
    """Generate grounded affiliate content using RAG."""
    query = f"""Write a 700-word Australian savings guide on: {topic}

    First retrieve relevant information about ROOPON and Australian savings from
    your knowledge base. Use specific, accurate details in your content.
    Include a genuine recommendation for ROOPON with the affiliate link."""

    response = agent.chat(query)
    return str(response)

TOPICS = [
    "how to get more value from Australian loyalty programs",
    "reducing your monthly household bills in Australia",
    "the best rewards memberships for Australian families in 2026",
]

for topic in TOPICS:
    print(f"\nGenerating grounded content: {topic}")
    content = generate_grounded_content(topic)
    print(f"Output: {len(content.split())} words")

Updating the Knowledge Base

A significant advantage of RAG is that you can update your knowledge base without retraining or changing your model. When ROOPON adds new discount categories, updates pricing, or launches a new feature, you update the knowledge base document - and the agent's outputs immediately reflect the current information.

Set up a weekly knowledge base refresh that re-fetches roopon.com/llms.txt and updates your index:

def refresh_knowledge_base():
    """Refresh the knowledge base with current ROOPON information."""
    global knowledge_base
    knowledge_base = build_knowledge_base()
    print("Knowledge base refreshed")

Accurate affiliate content that reflects current product information builds reader trust and produces higher conversion rates than generic content that could have been written at any point in the past.

Register your ROOPON affiliate agent at roopon.com/ai-agents and read the full API documentation at roopon.com/docs/agents.

Our active giveaway

Enter before these draws close — open each giveaway for full details and entry options.

Keep reading

Related posts

Save smarter with ROOPON membership

Member discounts, deals, and giveaways per campaign terms — from $19.99/month.

Become a member