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):
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".
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).
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).
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.
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.
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.
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.
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.
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.
"""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)
"""Zero-framework Anthropic Claude tool_use loop with EdgeData HTTP 504 zero-credit retry."""
import json
import os
import random
import time
from typing import Any
import anthropic
import httpx
EDGEDATA_BASE = "https://api.upp3.com"
EDGEDATA_API_KEY = os.environ["EDGEDATA_API_KEY"]
RETRYABLE_STATUSES = {429, 504} # Strictly 0 credits charged on HTTP 504 / 429
ANTHROPIC_TOOLS: list[dict[str, Any]] = [
{
"name": "get_amazon_reviews",
"description": "Extract deduplicated Amazon verified reviews using mode=summary (~86% fewer tokens).",
"input_schema": {
"type": "object",
"properties": {
"asin": {"type": "string", "description": "10-character Amazon ASIN."},
"country": {"type": "string", "default": "US"},
"star_rating": {
"type": "string",
"enum": ["all_stars", "critical", "positive", "one_star", "two_star"],
"default": "critical",
},
"max_reviews": {"type": "integer", "default": 40},
},
"required": ["asin"],
},
},
{
"name": "get_walmart_offers",
"description": "Retrieve Walmart US Buy Box winner, WFS status, and competing offers in summary mode.",
"input_schema": {
"type": "object",
"properties": {
"item_id": {"type": "string", "description": "Walmart US numeric item ID."},
},
"required": ["item_id"],
},
},
{
"name": "check_shopify_market",
"description": "Check Shopify Markets localized pricing and variant availability for a target ISO country.",
"input_schema": {
"type": "object",
"properties": {
"store": {"type": "string", "description": "Shopify store domain (e.g. allbirds.com)."},
"handle": {"type": "string", "description": "Product handle (e.g. mens-wool-runners)."},
"country": {"type": "string", "default": "GB"},
"language": {"type": "string", "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]:
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 timeouts charge 0 credits on EdgeData — safe to retry with backoff
if resp.status_code in RETRYABLE_STATUSES and attempt < max_retries:
retry_after = resp.headers.get("Retry-After")
delay = float(retry_after) if (retry_after and retry_after.isdigit()) else base_delay * (2 ** attempt)
time.sleep(delay + 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 execute_tool(http_client: httpx.Client, tool_name: str, tool_input: dict[str, Any]) -> dict[str, Any]:
if tool_name == "get_amazon_reviews":
return call_edgedata_with_retry(
http_client,
"POST",
"/v1/amazon/reviews",
json_body={
"asin": tool_input["asin"],
"country": tool_input.get("country", "US"),
"star_rating": tool_input.get("star_rating", "critical"),
"max_reviews": int(tool_input.get("max_reviews", 40)),
"verified_purchases_only": True,
"enable_deep_bypass": True,
"mode": "summary",
},
)
if tool_name == "get_walmart_offers":
item_id = str(tool_input["item_id"]).strip()
return call_edgedata_with_retry(
http_client,
"GET",
f"/v1/walmart/items/{item_id}/offers",
params={"mode": "summary"},
)
if tool_name == "check_shopify_market":
return call_edgedata_with_retry(
http_client,
"POST",
"/v1/shopify/products/market",
json_body={
"store": tool_input["store"],
"handle": tool_input["handle"],
"country": str(tool_input.get("country", "GB")).upper(),
"language": str(tool_input.get("language", "EN")).upper(),
"mode": "summary",
},
)
return {"ok": False, "error": f"unknown_tool:{tool_name}"}
def run_claude_research(prompt: str, max_turns: int = 6) -> str:
client = anthropic.Anthropic()
messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
with httpx.Client() as http_client:
for _ in range(max_turns):
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
system="Use EdgeData tools in summary mode to produce a concise, evidence-backed retail research brief.",
tools=ANTHROPIC_TOOLS,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "\n".join(b.text for b in response.content if b.type == "text")
tool_results: list[dict[str, Any]] = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(http_client, block.name, dict(block.input))
tool_results.append(
{
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result, ensure_ascii=False),
}
)
messages.append({"role": "user", "content": tool_results})
return "Max tool turns reached."
if __name__ == "__main__":
print(
run_claude_research(
"Audit Amazon ASIN B0BSHF7WHW critical complaints, Walmart US item 5296511223 Buy Box offers, "
"and UK market pricing for allbirds.com product mens-wool-runners."
)
)
// npm install edgedata-sdk
import { EdgeDataClient } from "edgedata-sdk";
import {
getOpenAITools,
getAnthropicTools,
executeTool,
} from "edgedata-sdk/agents";
const EDGEDATA_API_KEY = process.env.EDGEDATA_API_KEY ?? "";
const OPENAI_API_KEY = process.env.OPENAI_API_KEY ?? "";
const edgeClient = new EdgeDataClient({ apiKey: EDGEDATA_API_KEY });
// 1) Auto-generate typed schemas for OpenAI OR Anthropic with 1 line
const openaiTools = getOpenAITools({ resources: ["amazon", "walmart", "shopify"] });
export const anthropicTools = getAnthropicTools({ resources: ["amazon", "walmart", "shopify"] });
// 2) Zero-credit retry helper: HTTP 504 (UPSTREAM_TIMEOUT) & 429 never deduct credits
async function executeWithZeroCreditRetry<T>(
fn: () => Promise<T>,
maxRetries = 3,
baseDelayMs = 1500
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
try {
return await fn();
} catch (err: unknown) {
const status = (err as { status?: number; statusCode?: number })?.status
?? (err as { statusCode?: number })?.statusCode;
const retryable = status === 504 || status === 429;
if (!retryable || attempt === maxRetries) throw err;
const jitter = Math.floor(Math.random() * 400);
await new Promise((r) => setTimeout(r, baseDelayMs * 2 ** attempt + jitter));
}
}
throw new Error("Retry budget exhausted");
}
// 3) Zero-framework native fetch loop against OpenAI Chat Completions
export async function runOpenAIResearch(prompt: string) {
const messages: Array<Record<string, unknown>> = [
{ role: "system", content: "Always keep mode='summary' and cite exact numbers from EdgeData tool outputs." },
{ role: "user", content: prompt },
];
for (let turn = 0; turn < 6; turn += 1) {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4.1-mini",
messages,
tools: openaiTools,
tool_choice: "auto",
}),
});
if (!res.ok) throw new Error(`OpenAI HTTP ${res.status}`);
const data = (await res.json()) as {
choices: Array<{
message: {
role: string;
content: string | null;
tool_calls?: Array<{ id: string; function: { name: string; arguments: string } }>;
};
}>;
};
const msg = data.choices[0].message;
messages.push(msg);
if (!msg.tool_calls?.length) {
return msg.content ?? "";
}
for (const tc of msg.tool_calls) {
const args = JSON.parse(tc.function.arguments || "{}") as Record<string, unknown>;
const toolOutput = await executeWithZeroCreditRetry(() =>
executeTool(edgeClient, tc.function.name, { ...args, mode: "summary" })
);
messages.push({
role: "tool",
tool_call_id: tc.id,
content: JSON.stringify(toolOutput),
});
}
}
return "Max tool turns reached.";
}
runOpenAIResearch(
"Check Amazon ASIN B0BSHF7WHW critical reviews, Walmart 5296511223 Buy Box offers, and allbirds.com mens-wool-runners GB market price."
).then(console.log);
# 1) Amazon critical verified reviews (mode="summary", ~86% token savings)
curl -sS -X POST "https://api.upp3.com/v1/amazon/reviews" \
-H "X-API-Key: $EDGEDATA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"asin": "B0BSHF7WHW",
"country": "US",
"star_rating": "critical",
"max_reviews": 40,
"verified_purchases_only": true,
"enable_deep_bypass": true,
"mode": "summary"
}'
# 2) Walmart US Buy Box & competing WFS/3P seller offers (mode="summary")
curl -sS "https://api.upp3.com/v1/walmart/items/5296511223/offers?mode=summary" \
-H "X-API-Key: $EDGEDATA_API_KEY"
# 3) Shopify Markets UK (GB) localized pricing & variant stock (mode="summary")
curl -sS -X POST "https://api.upp3.com/v1/shopify/products/market" \
-H "X-API-Key: $EDGEDATA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"store": "allbirds.com",
"handle": "mens-wool-runners",
"country": "GB",
"language": "EN",
"mode": "summary"
}'
{
"ok": true,
"source": "amazon",
"mode": "summary",
"credits_charged": 4,
"data": {
"asin": "B0BSHF7WHW",
"deep_bypass_used": true,
"total_reviews_analyzed": 40,
"average_rating": 1.6,
"rating_distribution": { "1": 23, "2": 17 },
"top_pain_themes": ["battery drain after firmware update", "earcup hinge crack", "multipoint bluetooth drop"],
"sample_reviews": [
{
"rating": 1,
"verified_purchase": true,
"title": "Right hinge snapped after 4 months",
"excerpt": "Sound quality is solid but plastic swivel cracked during normal commute..."
}
],
"estimated_tokens_saved_pct": 86.1
}
}
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%.
| Function Calling Tool & Endpoint | mode="raw" Payload |
mode="summary" (Recommended) |
Token Savings |
|---|---|---|---|
get_amazon_reviewsPOST /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_offersGET /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_marketPOST /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).