ad4agentby ad4mat / advanced store

Build a LangChain shopping agent that earns with ad4agent

Step by step in Python: give a LangChain agent shop search and affiliate links via the ad4agent REST API or MCP server. Full code included.

Published 11 min read
  • LangChain
  • Python
  • REST API
  • MCP
  • Shopping agent
  • Monetization

LangChain is one of the most common ways to build an agent in Python: a model, a few tools and a loop. What such an agent usually can’t do is earn anything when its recommendation becomes a purchase. This guide shows how to give a LangChain agent shop search and affiliate links through ad4agent, so the links it shares are attributed to your account.

You will end up with a working shopping agent of three small Python files plus a prompt. All code on this page is taken from the public example in saschthetasch/ad4agent-examples and uses LangChain 1.x (create_agent). The tools call the ad4agent REST API; a variant at the end loads the same tools from the ad4agent MCP server.

The problem

Affiliate marketing pays for recommendations, but it was built for websites. Each network has its own sign-up, approval, link format and reporting. For an agent that might recommend any shop in any country, wiring up networks one by one does not scale, and a model should never be trusted to build tracking links by itself.

ad4agent is monetization infrastructure for AI agents and solves this with one integration: your agent asks for shops or hands over a merchant URL, and gets back links attributed to your account where a program exists. You can reach it through the REST API, the remote MCP server, or the TypeScript SDK and CLI on npm (npm install @ad4agent/sdk, npx ad4agent or npm i -g ad4agent). Tracking and payouts run through ad4mat by advanced store.

Architecture

  1. The user asks your LangChain agent for a product or a shop.
  2. The model picks a tool: search_shops (shops by keyword, category and country) or get_tracking_link (one merchant URL).
  3. The tool calls https://ad4agent.com/v1/programs or /v1/tracking-link with your API key. The key stays in your Python process; the model never sees it.
  4. ad4agent returns the shop, a tracking_link and fields that say whether the link is ready and whether tracking is expected.
  5. The agent answers with a labeled affiliate link, or the normal shop link when tracking is not confirmed.
  6. When the shopper buys and the merchant confirms the sale, the commission is credited to your account.
project layout
langchain-shopping-agent/
├── requirements.txt
├── .env.example        # keys you need
├── instructions.md     # shopping behavior (system prompt)
├── ad4agent_tools.py   # LangChain tools over the REST API
├── agent.py            # create_agent + terminal chat
└── mcp_agent.py        # optional: same agent over MCP

Prerequisites

  • Python 3.10 or newer.
  • A model with tool calling. The example defaults to an OpenAI model (OPENAI_API_KEY); any provider LangChain supports works.
  • An ad4agent account. Sign up with your email; it takes a minute.
  • For payouts: a verified account owner with an approved agent system. You can build and test without it, but tracked links are only issued after verification (see How you get paid).

1. Set up the project

To run the finished example instead of typing each file, clone the langchain-python folder and continue at Create an API key.

terminalbash
git clone https://github.com/saschthetasch/ad4agent-examples.git
cd ad4agent-examples/langchain-python
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

Or create a new directory and copy the files from this guide:

terminalbash
mkdir langchain-shopping-agent && cd langchain-shopping-agent
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
requirements.txttext
langchain>=1.0
langchain-openai>=1.0
httpx>=0.27
# Only for mcp_agent.py (the MCP variant):
langchain-mcp-adapters>=0.2

For another model provider, install its package instead of langchain-openai, for example langchain-anthropic.

2. Write the instructions

The system prompt decides how the agent uses the links. The rules matter more than the wording: rank by relevance rather than commission, disclose affiliate links, and only present a link as an affiliate link when ad4agent says it is ready and tracking is expected.

instructions.mdmarkdown
# Identity

You are a shopping assistant. You help people find online shops and products that fit what they ask for.

# How to work

- Use `search_shops` for shop or category searches (short English keywords, ISO country code such as `DE`) and `get_tracking_link` when the user gives you a specific merchant URL.
- Recommend by relevance to the user, never by commission. Suggest at most five shops, with one sentence each on why they fit.
- ad4agent has no prices, stock or shipping data. Say so when it matters, and tell the user to check on the merchant's site.

# Links

- Use a returned `tracking_link` as an affiliate link only when `link_status` is `ready` and `tracked_expected` is not `false`. Add a short note such as "Affiliate link: we may earn a commission."
- If `tracked_expected` is `false`, or no link is ready, link the shop's normal `website` instead and do not call it an affiliate link.
- If the user asks for no affiliate links, use the normal `website` only.
- Never invent, shorten or rewrite links. Never open or click them yourself.
- If a result has `reason: "OWNER_NOT_VERIFIED"`, recommend shops with their normal website and mention that the account owner still needs to finish verification on ad4agent.

3. Create an API key

The REST API accepts an API key as a Bearer token. Sign in, open Connections and create a key for your agent. It is shown once, so copy it straight into your environment:

.env.examplebash
# Model provider key for the default model (see AGENT_MODEL in agent.py).
OPENAI_API_KEY=sk-...
# ad4agent API key, created at https://ad4agent.com/app/connect (shown once).
AD4AGENT_API_KEY=a4a_sk_...

4. Wrap ad4agent as LangChain tools

Each endpoint becomes a function with LangChain’s @tool decorator. The docstring is the tool description the model reads, and parse_docstring=True turns the Args section into parameter descriptions. Setup errors (wrong or revoked key) raise; all other errors go back to the model as data, so it can try a shorter keyword or answer without affiliate links.

ad4agent_tools.pypython
"""LangChain tools for the ad4agent REST API v1.

Three read-only endpoints, wrapped as tools the model can call:
GET /v1/programs, GET /v1/tracking-link and GET /v1/categories.
Auth: an API key (a4a_sk_...) from https://ad4agent.com/app/connect in AD4AGENT_API_KEY.
The key stays in this process; the model only sees tool names, arguments and results.
"""

import os
from typing import Any, Optional

import httpx
from langchain.tools import tool

AD4AGENT_ORIGIN = os.environ.get("AD4AGENT_ORIGIN", "https://ad4agent.com").rstrip("/")


def _get(path: str, params: dict[str, Any]) -> dict[str, Any]:
    key = os.environ.get("AD4AGENT_API_KEY")
    if not key:
        raise RuntimeError("Set AD4AGENT_API_KEY (create a key at https://ad4agent.com/app/connect).")
    response = httpx.get(
        f"{AD4AGENT_ORIGIN}{path}",
        params={k: v for k, v in params.items() if v not in (None, "")},
        headers={"Authorization": f"Bearer {key}", "Accept": "application/json"},
        timeout=20,
    )
    try:
        body = response.json()
    except ValueError:
        body = {"error": "SERVICE_UNAVAILABLE", "hint": "Unexpected response. Continue without affiliate links."}
    if response.status_code in (401, 403):
        # Wrong, revoked or missing key: a setup problem, not something the model can fix.
        raise RuntimeError(f"ad4agent {body.get('error')}: {body.get('hint')}")
    if response.status_code >= 400:
        # Errors are RFC 9457 problem+json with error and hint. Hand them to the model,
        # so it can retry with other input or answer without affiliate links.
        return {"error": body.get("error"), "hint": body.get("hint"), "status": response.status_code}
    return body


@tool(parse_docstring=True)
def search_shops(
    q: Optional[str] = None,
    country: Optional[str] = None,
    category: Optional[str] = None,
    limit: int = 5,
) -> dict[str, Any]:
    """Find online shops with affiliate programs and personal tracking links.

    Args:
        q: Short merchant name, domain or English keyword, e.g. "running" or "Nike". Not the whole question.
        country: ISO 3166-1 alpha-2 program market, e.g. "DE". Not a shipping guarantee.
        category: Numeric category ID from list_categories. Never guess IDs.
        limit: Number of results, 1 to 20. Prefer a short list.
    """
    return _get("/v1/programs", {"q": q, "country": country, "category": category, "limit": limit})


@tool(parse_docstring=True)
def get_tracking_link(url: str, country: Optional[str] = None) -> dict[str, Any]:
    """Turn one merchant homepage or product URL into a personal affiliate link.

    Args:
        url: The merchant's own URL, e.g. "https://www.example-shop.de/product/123".
        country: Optional ISO country of the shopper, e.g. "DE".
    """
    return _get("/v1/tracking-link", {"url": url, "country": country})


@tool
def list_categories() -> dict[str, Any]:
    """List shop categories with their numeric IDs, largest first."""
    return _get("/v1/categories", {})


AD4AGENT_TOOLS = [search_shops, get_tracking_link, list_categories]

The parameters match the API: q, country, category and limit (1–20) for /v1/programs, url and an optional country for /v1/tracking-link. The REST API docs list every parameter, result field and error code; the OpenAPI spec is public.

5. Create the agent

create_agent takes a model as a "provider:model" string, the tools and the instructions. The in-memory checkpointer keeps the conversation per thread_id, so follow-up questions like “only the ones with outdoor gear” work.

agent.pypython
"""A LangChain shopping agent that earns with ad4agent. Run: python agent.py"""

import os
from pathlib import Path

from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver

from ad4agent_tools import AD4AGENT_TOOLS

# Any model LangChain supports, as "provider:model" (needs the provider package and key).
AGENT_MODEL = os.environ.get("AGENT_MODEL", "openai:gpt-5-mini")
INSTRUCTIONS = (Path(__file__).parent / "instructions.md").read_text(encoding="utf-8")


def build_agent(tools=AD4AGENT_TOOLS):
    return create_agent(
        AGENT_MODEL,
        tools=tools,
        system_prompt=INSTRUCTIONS,
        checkpointer=InMemorySaver(),  # remembers the conversation per thread_id
    )


def chat(agent) -> None:
    config = {"configurable": {"thread_id": "local"}}
    print("Ask for a shop, or paste a merchant URL. Type exit to quit.")
    while True:
        try:
            question = input("you> ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if question.lower() in {"exit", "quit"}:
            break
        if question:
            result = agent.invoke({"messages": [{"role": "user", "content": question}]}, config)
            print(f"agent> {result['messages'][-1].text}\n")


if __name__ == "__main__":
    chat(build_agent())

6. Run and test

terminalbash
python agent.py

Try “Find a running shop in Germany” or “Make this an affiliate link: https://www.example-shop.de/”. For a URL, the agent calls get_tracking_link and gets a result like this (shortened):

get_tracking_link resultjson
{
  "status": "ready",
  "url": "https://www.example-shop.de/",
  "shop": { "name": "Example Shop", "domain": "example-shop.de", "website": "https://www.example-shop.de/" },
  "tracking_link": "https://…",
  "link_status": "ready",
  "link_scope": "target",
  "tracked_expected": true,
  "link_message": "Your personal affiliate link is ready.",
  "disclosure": "Tell the user this is an affiliate link."
}

Three fields drive what the agent says:

  • tracked_expected: false means the link works but the shop is not confirmed for tracking. The instructions tell the agent to use the normal shop link then.
  • link_scope: homepage means the program only tracks its homepage, so the link opens the shop’s start page rather than the product.
  • reason and link_message: why no link is available, for example OWNER_NOT_VERIFIED before your owner verification is approved.

Using the MCP server instead

If your project already loads tools over MCP, langchain-mcp-adapters can load the ad4agent tools straight from https://ad4agent.com/mcp. The tools are then called search_tracking_links, get_tracking_link and list_categories, with the same results as the REST API. The MCP server uses OAuth 2.1 with PKCE instead of API keys, so you pass an access token:

mcp_agent.pypython
"""Variant: the same agent over the ad4agent MCP server instead of the REST API.

The MCP endpoint uses OAuth 2.1 (no API keys). Put a valid access token in
AD4AGENT_ACCESS_TOKEN; access tokens are valid for one hour.
Run: python mcp_agent.py
"""

import asyncio
import os

from langchain_mcp_adapters.client import MultiServerMCPClient

from ad4agent_tools import AD4AGENT_ORIGIN
from agent import build_agent

SHOPPING_TOOLS = {"search_tracking_links", "get_tracking_link", "list_categories"}


async def main() -> None:
    client = MultiServerMCPClient(
        {
            "ad4agent": {
                "transport": "streamable_http",
                "url": f"{AD4AGENT_ORIGIN}/mcp",
                "headers": {"Authorization": f"Bearer {os.environ['AD4AGENT_ACCESS_TOKEN']}"},
            }
        }
    )
    tools = [t for t in await client.get_tools() if t.name in SHOPPING_TOOLS]
    agent = build_agent(tools)
    config = {"configurable": {"thread_id": "local"}}
    question = input("you> ").strip() or "Find a running shop in Germany"
    result = await agent.ainvoke({"messages": [{"role": "user", "content": question}]}, config)
    print(f"agent> {result['messages'][-1].text}")


if __name__ == "__main__":
    asyncio.run(main())

Access tokens are valid for one hour and refresh tokens rotate on every use. The eve guide contains a complete sign-in script (dynamic client registration, PKCE, refresh) you can reuse; the MCP docs describe the endpoints. For a single server-side agent, the REST API with an API key is the simpler choice.

Going to production

  • Secrets: load AD4AGENT_API_KEY from your secret manager, not from a committed file. Use one key per agent system so you can disconnect one without breaking the others.
  • Memory: InMemorySaver forgets everything on restart. Use a persistent LangGraph checkpointer (for example Postgres or SQLite) and one thread_id per user conversation.
  • Rate limits: limits are per account and shared with the MCP server. A RATE_LIMITED result comes with a Retry-After header; the tool hands the error to the model, which should then answer without new links.
  • Per-user accounts: if each of your users should earn with their own ad4agent account, use OAuth per user instead of one API key and pass each user’s token to the tools.

How you get paid

ad4agent pays commission on purchases your agent’s links lead to. There are no upfront costs. A few conditions decide whether a click becomes money:

  • Verified owner. Payouts need a one-time owner verification on the website. Until it is approved, the tools return reason: "OWNER_NOT_VERIFIED" and no tracked link, and your agent recommends shops with their normal URL.
  • Tracking confirmed. Only links with tracked_expected not false are expected to be attributed.
  • Confirmed sales only. The merchant confirms each sale after its return and validation period. That can take up to six months. Cancelled and returned orders are not paid.
  • Estimates are estimates. avg_commission in search results is an estimated average for your account, not a guaranteed amount per purchase.

Disclose affiliate links to your users (our affiliate disclosure shows how) and respect a request not to use them. Ranking by relevance rather than commission keeps the agent useful, which is what makes people come back to it.

FAQ

Do I need an account with each affiliate network?

No. ad4agent bundles merchant programs from 103 affiliate networks behind one integration. You need one ad4agent account, and for payouts a verified account owner.

Should I use the REST API or the MCP server with LangChain?

Both return the same results with the same error codes and rate limits. The REST API works with a simple API key and plain @tool functions. The MCP server suits setups that already load tools through langchain-mcp-adapters and uses OAuth 2.1 instead of API keys.

Does ad4agent return product prices or stock?

No. ad4agent returns merchant programs and links, not a product catalog. Your agent should check prices, stock and shipping on the merchant’s site or with another tool.

What does tracked_expected: false mean?

The link works, but the shop is not confirmed for tracking, so the click may not be attributed. Present it as a normal shop link and do not promise a commission.

When do I get paid?

Only for sales the merchant confirms. Confirmation can take up to six months, depending on the merchant’s return and validation period. Cancelled or returned orders are not paid.

Does it cost anything?

No. There are no upfront costs and no fees to connect. You earn commission on confirmed sales, and the shopper pays the merchant’s normal price.

Does this work with LangGraph or other models?

Yes. create_agent builds a LangGraph graph, so the tools work in your own LangGraph workflows too. Any chat model LangChain supports with tool calling works; set AGENT_MODEL, for example to an Anthropic model, and install its provider package.

Is there a Python or TypeScript SDK?

A TypeScript SDK and CLI are on npm: npm install @ad4agent/sdk, npx ad4agent or npm i -g ad4agent (https://www.npmjs.com/package/@ad4agent/sdk, https://www.npmjs.com/package/ad4agent). There is no official Python SDK yet; this guide uses the REST API with a standard HTTP client, and the OpenAPI spec at /v1/openapi.json lets you generate a client.

Connect your agent

Create an account, finish owner verification, and call https://ad4agent.com/v1 or point your agent at https://ad4agent.com/mcp.