1. Why Cross-Marketplace LangChain Agents Need mode="summary"
A real e-commerce pricing or merchandising question almost never lives on a single storefront. Product teams routinely ask an agent to check why an Amazon ASIN is bleeding 1–2 star reviews, whether a Walmart US Buy Box seller is undercutting MAP via WFS or 3P fulfillment, and how a competing DTC Shopify store prices the same category in US vs. EU/UK markets.
In standard ReAct or OpenAI/Anthropic tool-calling loops, every tool observation is appended to message history and re-tokenized on every subsequent reasoning step. Four raw marketplace scrapes easily inject 21,000+ tokens in a single question—and by turn 5 of a multi-SKU audit, naive agents slam into 128k context limits or burn $0.50+ in redundant input tokens. EdgeData’s mode="summary" projects only decision-ready fields directly at the edge:
POST /v1/amazon/reviews
Pulls verified critical feedback (asin, country: "US", star_rating: "critical", mode: "summary") with defect themes and anonymized excerpts—strictly GDPR-safe by default.
GET /v1/walmart/items/{item_id}
Calls ?enrich=true&mode=summary to fetch live Walmart US title, price, availability, seller identity, and bundled AI review pros/cons in one compact call.
GET /v1/walmart/items/{item_id}/offers
Calls ?mode=summary to isolate buy_box, price_stats (min/max/avg), shipping fees, and WFS vs 3P seller fulfillment shifts.
POST /v1/shopify/products/market
Queries localized DTC pricing, currency parity, and variant availability across Shopify Markets (store, handle, country, language, mode: "summary").
EdgeData validates every POST body with strict schemas (extra="forbid"). For POST /v1/amazon/reviews, pass country (e.g. "US") and star_rating (valid enum: all_stars, five_star–one_star, positive, critical) alongside mode: "summary". Every snippet below is verified against the live OpenAPI contract.
2. Production LangChain Agent Code (Zero-Dep httpx + EdgeDataToolkit + TS & cURL)
Pick the integration style that matches your stack. Tab 1 runs immediately with standard langchain-core, langchain-openai, and httpx—no custom runtime required once you grab your free key below. Tab 2 shows the one-line EdgeDataToolkit binding for teams using the typed edgedata Python SDK (sync EdgeDataClient & async AsyncEdgeDataClient).
Run pip install langchain langchain-openai httpx, export EDGEDATA_API_KEY and OPENAI_API_KEY, and execute python langchain_market_agent.py.
import json
import os
import time
from typing import Any
import httpx
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
API_BASE = "https://api.upp3.com"
API_KEY = os.environ["EDGEDATA_API_KEY"]
RETRYABLE_STATUS = {429, 502, 503, 504}
def edgedata_request(
method: str,
path: str,
*,
params: dict[str, Any] | None = None,
payload: dict[str, Any] | None = None,
max_attempts: int = 3,
) -> dict[str, Any]:
"""Call EdgeData REST API with exponential backoff on 504 (0 credits charged on 504)."""
headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
last_error: Exception | None = None
for attempt in range(1, max_attempts + 1):
try:
with httpx.Client(base_url=API_BASE, headers=headers, timeout=45.0) as client:
resp = client.request(method, path, params=params, json=payload)
if resp.status_code in RETRYABLE_STATUS and attempt < max_attempts:
time.sleep(1.5 * attempt)
continue
resp.raise_for_status()
return resp.json().get("data", {})
except (httpx.TimeoutException, httpx.HTTPStatusError) as exc:
last_error = exc
if attempt < max_attempts:
time.sleep(1.5 * attempt)
continue
raise
raise RuntimeError(f"EdgeData request failed: {last_error}")
@tool
def amazon_critical_reviews(asin: str, country: str = "US", max_reviews: int = 30) -> str:
"""Fetch verified Amazon critical (1-3 star) reviews in token-efficient summary mode."""
data = edgedata_request(
"POST",
"/v1/amazon/reviews",
payload={
"asin": asin,
"country": country,
"star_rating": "critical",
"verified_purchases_only": True,
"max_reviews": max_reviews,
"mode": "summary",
},
)
return json.dumps(data)
@tool
def walmart_item_snapshot(item_id: str) -> str:
"""Fetch enriched Walmart US product detail, price, seller, and AI pros/cons."""
data = edgedata_request(
"GET",
f"/v1/walmart/items/{item_id}",
params={"enrich": "true", "mode": "summary"},
)
return json.dumps(data)
@tool
def walmart_buybox_offers(item_id: str) -> str:
"""Fetch Walmart US Buy Box winner, competing offers, price stats, and WFS status."""
data = edgedata_request(
"GET",
f"/v1/walmart/items/{item_id}/offers",
params={"mode": "summary"},
)
return json.dumps(data)
@tool
def shopify_market_pricing(
store: str,
handle: str,
country: str = "US",
language: str = "EN",
) -> str:
"""Fetch localized Shopify Markets pricing, currency, and availability for a DTC product."""
data = edgedata_request(
"POST",
"/v1/shopify/products/market",
payload={
"store": store,
"handle": handle,
"country": country,
"language": language,
"mode": "summary",
},
)
return json.dumps(data)
def run_market_agent(user_prompt: str) -> str:
tools = [
amazon_critical_reviews,
walmart_item_snapshot,
walmart_buybox_offers,
shopify_market_pricing,
]
tool_map = {t.name: t for t in tools}
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).bind_tools(tools)
messages: list[Any] = [
SystemMessage(
content=(
"You are an e-commerce market intelligence analyst. "
"Always call live EdgeData tools (already configured with mode='summary') "
"and synthesize concrete pricing, WFS Buy Box, and product-defect actions."
)
),
HumanMessage(content=user_prompt),
]
for _ in range(6):
ai_msg = llm.invoke(messages)
messages.append(ai_msg)
if not ai_msg.tool_calls:
return str(ai_msg.content)
for call in ai_msg.tool_calls:
result = tool_map[call["name"]].invoke(call["args"])
messages.append(ToolMessage(content=result, tool_call_id=call["id"]))
return "Reached tool-calling turn limit before final synthesis."
if __name__ == "__main__":
brief = run_market_agent(
"Compare three signals for our Q4 launch brief: "
"1) Amazon ASIN B0BSHF7WHW critical reviews in US, "
"2) Walmart US item 5296511223 enriched detail and Buy Box/WFS offers, "
"3) Shopify store allbirds.com handle mens-wool-runners in US (EN) vs DE (DE). "
"Return a Markdown table with pricing gaps, Buy Box risk, and top 3 defect fixes."
)
print(brief)
import asyncio
import os
from edgedata import AsyncEdgeDataClient, EdgeDataClient
from edgedata.agents import EdgeDataToolkit
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_openai import ChatOpenAI
API_KEY = os.environ["EDGEDATA_API_KEY"]
# 1) Sync LangChain binding via EdgeDataToolkit (Amazon + Walmart + Shopify)
client = EdgeDataClient(api_key=API_KEY)
toolkit = EdgeDataToolkit(
client,
resources=["amazon", "walmart", "shopify"],
)
lc_tools = toolkit.langchain_tools()
tool_map = {t.name: t for t in lc_tools}
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).bind_tools(lc_tools)
messages = [
HumanMessage(
content=(
"Use mode='summary' across Amazon ASIN B0BSHF7WHW critical reviews, "
"Walmart US item 5296511223 Buy Box offers, and Shopify allbirds.com "
"handle mens-wool-runners (US vs GB) to produce a merchandising memo."
)
)
]
for _ in range(6):
response = llm.invoke(messages)
messages.append(response)
if not response.tool_calls:
print(response.content)
break
for call in response.tool_calls:
output = tool_map[call["name"]].invoke(call["args"])
messages.append(ToolMessage(content=str(output), tool_call_id=call["id"]))
client.close()
# 2) Async fan-out with AsyncEdgeDataClient for low-latency LangGraph nodes
async def prefetch_commerce_context() -> dict:
async with AsyncEdgeDataClient(api_key=API_KEY) as aclient:
amz_reviews, wm_item, wm_offers, shp_us = await asyncio.gather(
aclient.amazon.reviews(
asin="B0BSHF7WHW",
country="US",
star_rating="critical",
mode="summary",
),
aclient.walmart.get_item("5296511223", enrich=True, mode="summary"),
aclient.walmart.get_offers("5296511223", mode="summary"),
aclient.shopify.product_market(
store="allbirds.com",
handle="mens-wool-runners",
country="US",
language="EN",
mode="summary",
),
)
return {
"amazon_reviews": amz_reviews,
"walmart_item": wm_item,
"walmart_offers": wm_offers,
"shopify_market": shp_us,
}
const API_BASE = "https://api.upp3.com";
const API_KEY = process.env.EDGEDATA_API_KEY ?? "";
async function edgeFetch<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
...init,
headers: {
"X-API-Key": API_KEY,
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
if (!res.ok) throw new Error(`EdgeData ${path} HTTP ${res.status}`);
const body = (await res.json()) as { data: T };
return body.data;
}
export async function gatherAgentSignals() {
const [amazonCritical, walmartItem, walmartOffers, shopifyUS] = await Promise.all([
edgeFetch("/v1/amazon/reviews", {
method: "POST",
body: JSON.stringify({
asin: "B0BSHF7WHW",
country: "US",
star_rating: "critical",
verified_purchases_only: true,
max_reviews: 30,
mode: "summary",
}),
}),
edgeFetch("/v1/walmart/items/5296511223?enrich=true&mode=summary"),
edgeFetch("/v1/walmart/items/5296511223/offers?mode=summary"),
edgeFetch("/v1/shopify/products/market", {
method: "POST",
body: JSON.stringify({
store: "allbirds.com",
handle: "mens-wool-runners",
country: "US",
language: "EN",
mode: "summary",
}),
}),
]);
return { amazonCritical, walmartItem, walmartOffers, shopifyUS };
}
gatherAgentSignals().then((res) => console.log(JSON.stringify(res, null, 2)));
# 1) Amazon US critical reviews (verified purchases, mode="summary")
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","verified_purchases_only":true,"max_reviews":30,"mode":"summary"}'
# 2) Walmart US enriched product snapshot
curl -sS "https://api.upp3.com/v1/walmart/items/5296511223?enrich=true&mode=summary" \
-H "X-API-Key: $EDGEDATA_API_KEY"
# 3) Walmart US Buy Box & competing WFS/3P seller offers
curl -sS "https://api.upp3.com/v1/walmart/items/5296511223/offers?mode=summary" \
-H "X-API-Key: $EDGEDATA_API_KEY"
# 4) Shopify Markets localized pricing (US vs DE)
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":"DE","language":"DE","mode":"summary"}'
3. mode="summary" vs mode="raw" (~85% LLM Token Savings)
In a LangChain ReAct or tool-calling loop, tool responses don’t just get billed once—they stay inside the conversation buffer across every subsequent tool call and final synthesis turn. Switching all four tools to mode="summary" slashes payload volume by ~85%, keeping a full 3-marketplace competitive sweep comfortably under 3,300 tokens instead of blowing through 21,500+ raw tokens (or overflowing a 128k window during batch catalog sweeps).
| LangChain Tool / REST Endpoint | mode="raw" Input Tokens |
mode="summary" Input Tokens |
Measured Savings | ReAct 5-SKU Sweep Impact |
|---|---|---|---|---|
POST /v1/amazon/reviews30 verified critical reviews |
~10,800 tokens | ~1,520 tokens | ~86% saved | Fits 5 ASINs in ~7.6k vs ~54k tokens |
GET /v1/walmart/items/{id}?enrich=true |
~4,350 tokens | ~690 tokens | ~84% saved | Drops BTF HTML bloat, keeps AI pros/cons |
GET /v1/walmart/items/{id}/offers |
~2,900 tokens | ~480 tokens | ~83% saved | Keeps buy_box, WFS flag & price_stats |
POST /v1/shopify/products/market |
~3,500 tokens | ~520 tokens | ~85% saved | Strips image CDNs, keeps localized price/stock |
| Total per 1-SKU Cross-Market Run | ~21,550 tokens | ~3,210 tokens | ~85.1% saved | Prevents 128k context overflow |
4. Prototype First in Claude / Cursor via Hosted MCP (Zero Boilerplate)
Want to validate your cross-marketplace prompt logic before writing a single line of LangChain Python? Connect Claude Desktop, Cursor, or Windsurf directly to EdgeData’s Hosted Streamable HTTP MCP gateway (https://mcp.upp3.com/mcp). All 50 native MCP tools default to mode="summary".
{
"mcpServers": {
"edgedata": {
"url": "https://mcp.upp3.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_EDGEDATA_API_KEY"
}
}
}
}
Run a cross-marketplace competitive research audit using EdgeData MCP tools (keep mode="summary" on every call): 1. Call amazon_get_reviews(asin="B0BSHF7WHW", country="US", star_rating="critical", verified_purchases_only=true, max_reviews=30, mode="summary"). 2. Call walmart_get_item(item_id="5296511223", enrich=true, mode="summary") and walmart_get_offers(item_id="5296511223", mode="summary"). 3. Call shopify_get_product_market(store="allbirds.com", handle="mens-wool-runners", country="US", language="EN", mode="summary") and again for country="DE", language="DE". Deliver an executive Markdown table covering: - Top 3 recurring Amazon critical-review defect themes we can solve in packaging or PDP copy - Walmart US Buy Box winner, landed price, WFS vs 3P status, and price spread across competing offers - Shopify Markets US vs DE localized pricing parity and DTC positioning recommendations.
5. Production Troubleshooting, 504 Zero-Charge Retries & Credit Sizing
Real-time retail upstreams occasionally spike in latency during flash sales or bot-defense rotations. Keep your LangChain agent resilient with four battle-tested guardrails:
Handling HTTP 504 Upstream Timeouts (0 Credits Charged)
If an upstream marketplace stalls beyond gateway timeout, EdgeData returns HTTP 504 and charges 0 credits. Wrap your LangChain tool transport with a 2–3 attempt exponential backoff (1.5s → 3.0s) and a 45s client timeout as shown in edgedata_request() above.
Avoiding HTTP 422 Schema Validation Errors
All POST routes enforce extra="forbid". Verify that /v1/amazon/reviews sends country (not domain) and star_rating (not stars), while Shopify market requests provide either url or both store and handle.
Controlling Tool-Calling Turn Loops
Always cap your LangChain agent loop (e.g., max_iterations=6) and instruct the system prompt to fetch Walmart detail and offers once per item ID rather than polling repeatedly.
GDPR & Privacy Boundaries by Default
Amazon review endpoints default to include_gdpr_sensitive=false, removing personal reviewer identifiers before payloads enter your LLM prompt history or LangSmith traces.
Transparent Direct Credit Pricing (Zero Hidden Markup)
100 credits/mo — instant key, no credit card required.
25,000 credits — one-time purchase, never expires.
15,000 credits/mo for scheduled agents & daily monitors.
60,000 credits/mo for high-concurrency agent fleets.
6. Claim Your Free API Key & Run the LangChain Agent
Provision your free 100 credits/mo EdgeData key right here in seconds—no credit card required—then paste it into EDGEDATA_API_KEY and run langchain_market_agent.py.