Zero Framework · Native Tool Loop ~85% Token Savings · mode="summary" HTTP 504 = 0 Credits Charged OpenAI · Anthropic · TypeScript · cURL 8 min build

OpenAI & Anthropic Native Function Calling Product Research (Zero Framework)

Skip heavyweight agent abstractions and wire OpenAI Chat Completions tools or Anthropic Claude Messages tool_use straight to EdgeData’s 60+ commercial REST endpoints. This production blueprint combines Amazon verified-review mining, Walmart US Buy Box offers, and Shopify Markets localized pricing in ~80 lines of code—with HTTP 504 zero-credit exponential backoff retry and ~85% token savings via mode="summary".

0 Framework Lock-In
Pure openai / anthropic SDK + httpx or native TS fetch
~85% Token Savings
mode="summary" keeps 3-platform tool turns under ~3.2k tokens
HTTP 504 = 0 Credits
Upstream timeouts never deduct credits—retry with zero double-charge risk
$0 / $47 / $49 / $149
100 free credits, $47 once (25k), $49/mo (15k), or $149/mo (60k)

1. Three Real Commercial Endpoints Mapped to Native LLM Tools

When an LLM conducts cross-channel product research, it needs deterministic, flat-schema JSON—not raw HTML pages or brittle third-party scraper Actors. Below are the three live EdgeData commercial endpoints wired directly into our OpenAI and Anthropic tool schemas (all part of EdgeData’s 60+ REST endpoint catalog across 13 platforms):

TOOL 1 · AMAZON REVIEWS

get_amazon_reviews

POST /v1/amazon/reviews extracts deduplicated verified-purchase reviews with enable_deep_bypass: true, star_rating filters, GDPR 0-PII defaults, and mode: "summary".

TOOL 2 · WALMART BUY BOX

get_walmart_offers

GET /v1/walmart/items/{item_id}/offers?mode=summary isolates the live Buy Box winner, landed shipping price, WFS vs. 3P seller fulfillment, and min/max/avg price stats (1 credit/call).

TOOL 3 · SHOPIFY MARKETS

check_shopify_market

POST /v1/shopify/products/market returns country-localized Shopify pricing (US, GB, DE, CA), currency, VAT-inclusive compare-at prices, and SKU variant availability (1 credit/call).

60+ ENDPOINTS · ONE KEY

X-API-Key + mode="summary"

Swap or expand tools anytime across TikTok Shop, Mercado Libre, Target, eBay, Temu, Trustpilot, Google Ads, App Store, Google Play, and LinkedIn Public Jobs (0-PII) using the exact same retry wrapper.

2. HTTP 504 Zero-Credit Billing Guarantee & Safe Backoff Retry

Live e-commerce upstreams occasionally spike in latency during peak traffic or deep review pagination. With many legacy scraping APIs, retrying an upstream timeout silently bills you twice. EdgeData enforces strict post-success metering: credits are finalized and deducted only after a valid HTTP 200 payload is assembled.

Billing Safety Guarantee — HTTP 504 = Strictly 0 Credits Charged

If an upstream retail marketplace times out and EdgeData returns HTTP 504 Gateway Timeout (error.code = "UPSTREAM_TIMEOUT"), 0 credits are charged to your account. Your OpenAI or Anthropic tool loop can safely execute jittered exponential backoff (1.5s → 3.0s → 6.0s) with mathematical certainty that you will never be double-billed.

HTTP 504 · 0 CREDITS

Upstream Timeout → Retry Safely

Zero credits deducted. Back off exponentially with random jitter (up to 3 attempts) before returning a graceful fallback error object to the LLM.

HTTP 429 · 0 CREDITS

Rate Limit → Honor Retry-After

Zero credits deducted. Read the Retry-After response header (or fall back to exponential backoff) so parallel tool calls stay smooth.

HTTP 4xx · 0 CREDITS

Schema / Auth Error → Fail Fast

400, 401, 402, and 422 never consume credits. Return the structured JSON error message to the model so it can self-correct invalid ASINs or parameters.

$0 Free Trial
100 free monthly credits · No credit card required
$49/mo (15k)
Pro tier · 15,000 monthly credits + NDJSON streaming
$149/mo (60k)
Scale tier · 60,000 monthly credits & 200 RPM

3. Zero-Framework Production Code (OpenAI, Anthropic, TypeScript & cURL)

Every tab below is copy-paste ready and uses the exact live request schemas against https://api.upp3.com. Both Python loops embed call_edgedata_with_retry so transient 504 and 429 responses recover automatically at 0 credit cost.

openai_product_research.py — OpenAI SDK + httpx (Zero Framework + 504 Free Retry)
"""Zero-framework OpenAI Function Calling product research agent with HTTP 504 zero-credit retry."""
import json
import os
import random
import time
from typing import Any

import httpx
from openai import OpenAI

EDGEDATA_BASE = "https://api.upp3.com"
EDGEDATA_API_KEY = os.environ["EDGEDATA_API_KEY"]
RETRYABLE_STATUSES = {429, 504}  # EdgeData guarantees 0 credits charged on 429/504

OPENAI_TOOLS: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "get_amazon_reviews",
            "description": "Fetch deduplicated Amazon customer reviews in token-efficient summary mode.",
            "parameters": {
                "type": "object",
                "properties": {
                    "asin": {"type": "string", "description": "10-character Amazon ASIN (e.g. B0BSHF7WHW)."},
                    "country": {"type": "string", "default": "US"},
                    "star_rating": {
                        "type": "string",
                        "enum": ["all_stars", "critical", "positive", "one_star", "two_star"],
                        "default": "critical",
                    },
                    "max_reviews": {"type": "integer", "minimum": 1, "maximum": 200, "default": 40},
                    "verified_purchases_only": {"type": "boolean", "default": True},
                },
                "required": ["asin"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_walmart_offers",
            "description": "Fetch Walmart US Buy Box winner, WFS vs 3P fulfillment, and competing seller offers.",
            "parameters": {
                "type": "object",
                "properties": {
                    "item_id": {"type": "string", "description": "Numeric Walmart US item ID (e.g. 5296511223)."},
                },
                "required": ["item_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "check_shopify_market",
            "description": "Fetch localized Shopify Markets product pricing, currency, and SKU availability by country.",
            "parameters": {
                "type": "object",
                "properties": {
                    "store": {"type": "string", "description": "Public Shopify store domain (e.g. allbirds.com)."},
                    "handle": {"type": "string", "description": "Product handle (e.g. mens-wool-runners)."},
                    "country": {"type": "string", "description": "2-letter ISO country code (US, GB, DE, CA).", "default": "GB"},
                    "language": {"type": "string", "description": "2-letter ISO language code.", "default": "EN"},
                },
                "required": ["store", "handle"],
            },
        },
    },
]


def call_edgedata_with_retry(
    http_client: httpx.Client,
    method: str,
    path: str,
    *,
    params: dict[str, Any] | None = None,
    json_body: dict[str, Any] | None = None,
    max_retries: int = 3,
    base_delay: float = 1.5,
) -> dict[str, Any]:
    """Call EdgeData with jittered exponential backoff on HTTP 504/429 (0 credits charged on failures)."""
    headers = {"X-API-Key": EDGEDATA_API_KEY}
    for attempt in range(max_retries + 1):
        try:
            resp = http_client.request(
                method,
                f"{EDGEDATA_BASE}{path}",
                headers=headers,
                params=params,
                json=json_body,
                timeout=45.0,
            )
        except (httpx.TimeoutException, httpx.ConnectError) as exc:
            if attempt == max_retries:
                return {"ok": False, "error": f"network_timeout: {exc}", "credits_charged": 0}
            time.sleep(base_delay * (2 ** attempt) + random.uniform(0.1, 0.5))
            continue

        if resp.status_code == 200:
            return resp.json()

        # HTTP 504 (UPSTREAM_TIMEOUT) & 429 strictly deduct 0 credits — safe to retry
        if resp.status_code in RETRYABLE_STATUSES and attempt < max_retries:
            retry_after = resp.headers.get("Retry-After")
            wait_s = float(retry_after) if (retry_after and retry_after.isdigit()) else base_delay * (2 ** attempt)
            time.sleep(wait_s + random.uniform(0.15, 0.6))
            continue

        return {
            "ok": False,
            "status_code": resp.status_code,
            "credits_charged": 0,
            "detail": resp.text[:400],
        }
    return {"ok": False, "error": "exhausted_retries", "credits_charged": 0}


def dispatch_tool(http_client: httpx.Client, name: str, args: dict[str, Any]) -> dict[str, Any]:
    if name == "get_amazon_reviews":
        payload = {
            "asin": args["asin"],
            "country": args.get("country", "US"),
            "star_rating": args.get("star_rating", "critical"),
            "max_reviews": int(args.get("max_reviews", 40)),
            "verified_purchases_only": bool(args.get("verified_purchases_only", True)),
            "enable_deep_bypass": True,
            "mode": "summary",
        }
        return call_edgedata_with_retry(http_client, "POST", "/v1/amazon/reviews", json_body=payload)

    if name == "get_walmart_offers":
        item_id = str(args["item_id"]).strip()
        return call_edgedata_with_retry(
            http_client,
            "GET",
            f"/v1/walmart/items/{item_id}/offers",
            params={"mode": "summary"},
        )

    if name == "check_shopify_market":
        payload = {
            "store": args["store"],
            "handle": args["handle"],
            "country": str(args.get("country", "GB")).upper(),
            "language": str(args.get("language", "EN")).upper(),
            "mode": "summary",
        }
        return call_edgedata_with_retry(http_client, "POST", "/v1/shopify/products/market", json_body=payload)

    return {"ok": False, "error": f"unknown_tool:{name}"}


def run_research(user_prompt: str, max_turns: int = 6) -> str:
    llm = OpenAI()
    messages: list[dict[str, Any]] = [
        {
            "role": "system",
            "content": (
                "You are a senior e-commerce analyst. Call EdgeData tools to gather live Amazon reviews, "
                "Walmart Buy Box offers, and Shopify localized market prices before writing a concise brief."
            ),
        },
        {"role": "user", "content": user_prompt},
    ]

    with httpx.Client() as http_client:
        for _ in range(max_turns):
            completion = llm.chat.completions.create(
                model="gpt-4.1-mini",
                messages=messages,
                tools=OPENAI_TOOLS,
                tool_choice="auto",
            )
            msg = completion.choices[0].message
            messages.append(msg.model_dump(exclude_none=True))

            if not msg.tool_calls:
                return msg.content or ""

            for tc in msg.tool_calls:
                args = json.loads(tc.function.arguments or "{}")
                result = dispatch_tool(http_client, tc.function.name, args)
                messages.append(
                    {
                        "role": "tool",
                        "tool_call_id": tc.id,
                        "content": json.dumps(result, ensure_ascii=False),
                    }
                )
    return "Max tool turns reached."


if __name__ == "__main__":
    brief = run_research(
        "Compare critical verified reviews for Amazon ASIN B0BSHF7WHW, check Walmart item 5296511223 Buy Box offers, "
        "and check UK (GB) localized pricing for allbirds.com handle mens-wool-runners."
    )
    print(brief)

4. mode="summary" vs mode="raw" (~85% Token Savings)

In multi-turn Function Calling, every tool output stays inside your conversation history for all subsequent turns. Passing raw HTML-derived JSON blows up context windows and multiplies OpenAI/Anthropic input token spend. Setting mode="summary" projects only decision-grade fields server-side, trimming a full 3-platform research turn by ~85%.

Raw Payload (mode="raw") ~21,400 tokens / 3-tool turn

Full review HTML fragments, redundant CDN image arrays, nested storefront badges, and uncompacted variant metadata.

Summary Mode (mode="summary") ~3,180 tokens (~85% saved)

Projects rating distributions, concise excerpts, Buy Box price_stats, and top 10 localized Shopify SKUs.

Function Calling Tool & Endpoint mode="raw" Payload mode="summary" (Recommended) Token Savings
get_amazon_reviews
POST /v1/amazon/reviews (40 reviews)
~14,800 tokens (full review objects, media arrays, helpful metadata) ~2,050 tokens (rating histogram, verified ratio, concise excerpts) ~86% saved
get_walmart_offers
GET /v1/walmart/items/{id}/offers
~2,450 tokens (raw offer nodes & storefront badges) ~510 tokens (buy_box, price_stats, top WFS/3P offers) ~79% saved
check_shopify_market
POST /v1/shopify/products/market
~4,150 tokens (full media gallery, raw HTML descriptions, all option trees) ~620 tokens (localized currency, top 10 variant SKUs, prices & stock) ~85% saved
Total 3-Tool Research Turn ~21,400 input tokens ~3,180 input tokens ~85.1% saved

5. Provision Your Instant 100-Credit Free API Key

Generate a live X-API-Key right here (no credit card required) to test the OpenAI, Anthropic, TypeScript, and cURL tool loops immediately. When you scale to production, choose the $47 one-time 25,000 never-expiring credit pack, $49/mo Pro (15k), or $149/mo Scale (60k).