CrewAI · 3 Serial Agents ~82% Multiplied Token Savings Walmart · Shopify · Trustpilot 0-PII 15 min build

Build a CrewAI 3-Agent Competitor Intelligence Crew for Retail Pricing, Stock & Brand Risk

In multi-agent crews, raw scraper JSON doesn’t just bloat one prompt—it gets passed downstream and re-tokenized at every handoff. This production CrewAI sequential workflow chains a Marketplace Merchandising Scout (Walmart & Shopify), a Brand Reputation Researcher (Trustpilot 0-PII), and an Executive Strategy Writer on EdgeData’s mode="summary" endpoints to cut cumulative crew token burn by ~82%.

3 Crew Agents
Merchandising Scout → Reputation Researcher → Strategy Writer
~82% Less
Cumulative tokens across agent-to-agent handoffs via mode="summary"
7 Live Endpoints
Walmart item/offers, Shopify inventory/markets, Trustpilot 3-call audit
0 Personal PII
Trustpilot reviewer PII stripped by default (GDPR-safe crew logs)

1. Three-Agent Sequential CrewAI Architecture

Splitting competitive intelligence into specialized CrewAI agents keeps tool schemas focused and eliminates hallucinated cross-domain metrics. Each upstream agent calls verified EdgeData REST endpoints with mode="summary" and passes compact JSON into the final strategy writer via Task(context=[...]):

AGENT 1 · SCOUT

Marketplace Merchandising Scout

Audits retail pricing, Buy Box control, WFS vs 3P sellers, and DTC SKU stock via GET /v1/walmart/items/{item_id}?enrich=true&mode=summary, GET /v1/walmart/items/{item_id}/offers?mode=summary, POST /v1/shopify/products/inventory, and POST /v1/shopify/products/market.

AGENT 2 · RESEARCHER

Brand Reputation Researcher

Audits brand trust and verified customer pain points via POST /v1/trustpilot/companies/by-domain, POST /v1/trustpilot/companies/transparency, and POST /v1/trustpilot/reviews (stars: [1, 2], only_verified: true, mode: "summary", GDPR 0-PII).

AGENT 3 · WRITER

Executive Strategy Writer

Consumes both upstream compact summary briefs (zero external scraping tools needed) and outputs a structured Markdown Competitive Battlecard with pricing spreads, stockout windows, and 1–2 star counter-messaging angles.

GDPR 0-PII Guarantee Across Crew Logs & Traces

Agent 2’s Trustpilot calls enforce include_personal_data=false by default. Reviewer names, emails, avatars, and profile URLs are completely removed before payloads reach CrewAI memory, LLM providers, or observability traces—keeping your competitive battlecards strictly B2B-compliant.

2. Complete Runnable CrewAI Code (BaseTool + httpx, SDK, cURL & Hosted MCP)

Tab 1 is copy-paste runnable today using standard crewai, pydantic, and httpx (zero extra EdgeData package needed). Tab 2 shows the clean EdgeDataClient typed SDK equivalent, while Tabs 3 & 4 give you standalone cURL checks and the Hosted MCP prompt.

Quickstart Install (Tab 1 — Runnable Immediately)

Run pip install crewai httpx pydantic, export EDGEDATA_API_KEY and OPENAI_API_KEY, and execute python competitor_intel_crew.py.

competitor_intel_crew.py — 3-Agent Sequential CrewAI Pipeline
import json
import os
import time
from typing import Any, Type
import httpx
from crewai import Agent, Crew, Process, Task
from crewai.tools import BaseTool
from pydantic import BaseModel, Field

API_BASE = "https://api.upp3.com"
API_KEY = os.environ["EDGEDATA_API_KEY"]
RETRYABLE = {429, 502, 503, 504}


def call_edgedata(
    method: str,
    path: str,
    *,
    params: dict[str, Any] | None = None,
    payload: dict[str, Any] | None = None,
    max_attempts: int = 3,
) -> str:
    """Execute EdgeData REST call with 504 zero-charge exponential backoff."""
    headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
    for attempt in range(1, max_attempts + 1):
        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 and attempt < max_attempts:
            time.sleep(1.5 * attempt)
            continue
        resp.raise_for_status()
        return json.dumps(resp.json().get("data", {}))
    raise RuntimeError(f"EdgeData call exhausted retries: {method} {path}")


# --- Agent 1 Tools: Walmart US + Shopify Markets & Inventory ---

class WalmartItemInput(BaseModel):
    item_id: str = Field(..., description="Numeric Walmart US item ID, e.g. 5296511223")


class WalmartMerchandisingTool(BaseTool):
    name: str = "walmart_item_and_offers"
    description: str = "Fetch Walmart US enriched item snapshot plus Buy Box & WFS competing offers in summary mode."
    args_schema: Type[BaseModel] = WalmartItemInput

    def _run(self, item_id: str) -> str:
        item = json.loads(
            call_edgedata("GET", f"/v1/walmart/items/{item_id}", params={"enrich": "true", "mode": "summary"})
        )
        offers = json.loads(
            call_edgedata("GET", f"/v1/walmart/items/{item_id}/offers", params={"mode": "summary"})
        )
        return json.dumps({"walmart_item": item, "walmart_offers": offers})


class ShopifySkuInput(BaseModel):
    store: str = Field(..., description="Public Shopify store domain, e.g. allbirds.com")
    handle: str = Field(..., description="Shopify product handle, e.g. mens-wool-runners")
    country: str = Field(default="US", description="2-letter ISO market country code")
    language: str = Field(default="EN", description="2-letter ISO language code")


class ShopifyInventoryMarketTool(BaseTool):
    name: str = "shopify_inventory_and_market"
    description: str = "Fetch real-time Shopify variant inventory and localized Shopify Markets pricing in summary mode."
    args_schema: Type[BaseModel] = ShopifySkuInput

    def _run(self, store: str, handle: str, country: str = "US", language: str = "EN") -> str:
        inventory = json.loads(
            call_edgedata(
                "POST",
                "/v1/shopify/products/inventory",
                payload={"store": store, "handle": handle, "country": country, "mode": "summary"},
            )
        )
        market = json.loads(
            call_edgedata(
                "POST",
                "/v1/shopify/products/market",
                payload={
                    "store": store,
                    "handle": handle,
                    "country": country,
                    "language": language,
                    "mode": "summary",
                },
            )
        )
        return json.dumps({"shopify_inventory": inventory, "shopify_market": market})


# --- Agent 2 Tool: Trustpilot 0-PII Brand Reputation ---

class TrustpilotDomainInput(BaseModel):
    domain: str = Field(..., description="Competitor public domain, e.g. allbirds.com")


class TrustpilotReputationTool(BaseTool):
    name: str = "trustpilot_0pii_reputation"
    description: str = "Fetch Trustpilot TrustScore, transparency flagging stats, and verified 1-2 star 0-PII reviews."
    args_schema: Type[BaseModel] = TrustpilotDomainInput

    def _run(self, domain: str) -> str:
        company = json.loads(
            call_edgedata("POST", "/v1/trustpilot/companies/by-domain", payload={"domain": domain, "mode": "summary"})
        )
        transparency = json.loads(
            call_edgedata("POST", "/v1/trustpilot/companies/transparency", payload={"domain": domain, "mode": "summary"})
        )
        reviews = json.loads(
            call_edgedata(
                "POST",
                "/v1/trustpilot/reviews",
                payload={
                    "domain": domain,
                    "stars": [1, 2],
                    "only_verified": True,
                    "language": "en",
                    "page": 1,
                    "mode": "summary",
                },
            )
        )
        return json.dumps({"company": company, "transparency": transparency, "critical_reviews": reviews})


# --- 3-Agent Sequential Crew Definition ---

merch_scout = Agent(
    role="Marketplace Merchandising Scout",
    goal="Capture exact Walmart Buy Box/WFS pricing and Shopify DTC inventory & regional pricing gaps.",
    backstory="Senior retail pricing analyst focused on MAP parity, WFS fulfillment, and SKU stockouts.",
    tools=[WalmartMerchandisingTool(), ShopifyInventoryMarketTool()],
    verbose=True,
)

reputation_researcher = Agent(
    role="Brand Reputation Researcher",
    goal="Audit Trustpilot TrustScore, transparency flagging ratios, and verified 1-2 star complaint themes (0-PII).",
    backstory="GDPR-conscious voice-of-customer researcher specializing in customer churn and product defects.",
    tools=[TrustpilotReputationTool()],
    verbose=True,
)

strategy_writer = Agent(
    role="Executive Strategy Writer",
    goal="Synthesize merchandising and reputation telemetry into an actionable Markdown competitive battlecard.",
    backstory="VP-level GTM strategist who writes crisp, evidence-backed executive briefs with zero fluff.",
    verbose=True,
)

task_merch = Task(
    description=(
        "Inspect Walmart US item_id '5296511223' (item detail + Buy Box/WFS offers) and "
        "Shopify store 'allbirds.com' handle 'mens-wool-runners' (inventory + US and DE market pricing). "
        "Return structured JSON findings covering price spread, WFS availability, and out-of-stock variants."
    ),
    expected_output="Compact JSON summary of Walmart Buy Box/WFS status and Shopify inventory & US/DE pricing.",
    agent=merch_scout,
)

task_reputation = Task(
    description=(
        "Audit Trustpilot reputation for domain 'allbirds.com': baseline TrustScore, transparency flagging stats, "
        "and verified 1-2 star English complaints (0-PII). Cluster the top 3 recurring customer pain points."
    ),
    expected_output="Compact JSON summary of TrustScore, flagging ratio, and top 3 verified 1-2 star themes.",
    agent=reputation_researcher,
)

task_battlecard = Task(
    description=(
        "Combine the upstream Marketplace Merchandising Scout and Brand Reputation Researcher findings into "
        "a board-ready Markdown Competitor Battlecard with: (1) Pricing & Buy Box Table, "
        "(2) Variant Stockout Opportunities, (3) Verified 1-2 Star Counter-Positioning Angles, and "
        "(4) 30-Day GTM Action Plan. Confirm zero reviewer PII is included."
    ),
    expected_output="Executive Markdown Competitive Battlecard with pricing, stock, and 0-PII VoC attack angles.",
    agent=strategy_writer,
    context=[task_merch, task_reputation],
)

crew = Crew(
    agents=[merch_scout, reputation_researcher, strategy_writer],
    tasks=[task_merch, task_reputation, task_battlecard],
    process=Process.sequential,
    verbose=True,
)

if __name__ == "__main__":
    battlecard = crew.kickoff()
    print(battlecard)

3. mode="summary" (~82% Token Savings — Multiplied Across Crew Handoffs!)

In a single-agent script, verbose JSON hurts once. In a sequential CrewAI pipeline, every token emitted by Agent 1 and Agent 2 is billed during their own tool loops and then re-injected as context into Agent 3 (plus any manager/reflection passes). That means mode="summary" delivers a 2×–3× compounding token reduction across the full crew execution:

Raw Mode Across 3-Agent Handoff ~41,200 cumulative tokens

7 raw payloads (~22.9k tokens) ingested by Agents 1–2, then echoed into Agent 3’s context window (~18.3k carry-over).

Summary Mode Across 3-Agent Handoff ~7,380 cumulative tokens (~82.1% saved)

Compact JSON (~4.1k tokens) across all 7 calls plus clean structured handoff (~3.3k) into the Executive Strategy Writer.

Crew Stage & EdgeData Endpoints mode="raw" Tokens mode="summary" Tokens Stage Savings Handoff Multiplier Effect
Agent 1: Walmart
/items/{id}?enrich=true + /offers
~7,250 tokens ~1,170 tokens ~84% saved Preserves buy_box, WFS & price_stats
Agent 1: Shopify
/products/inventory + /products/market
~8,250 tokens ~1,450 tokens ~82% saved Drops media CDN bloat, keeps variant stock
Agent 2: Trustpilot (0-PII)
/by-domain + /transparency + /reviews
~7,400 tokens ~1,480 tokens ~80% saved Strips all reviewer PII + verbose UI nodes
Agent 3: Strategy Writer Context Carry-Over
Ingests context=[task_merch, task_reputation]
~18,300 tokens ~3,280 tokens ~82% saved Savings multiply on every downstream pass
Total Sequential Crew Run (3 Agents) ~41,200 tokens ~7,380 tokens ~82.1% saved 5.5× lower LLM cost & faster latency

Sample Agent 3 Output (Executive Battlecard Excerpt)

Markdown — Executive Strategy Writer Battlecard Output
## Competitor Intelligence Battlecard (Zero-PII Verified)

### 1. Pricing, Buy Box & Stockout Matrix
| Channel | Target Signal | Live Snapshot | Strategic Opening |
| --- | --- | --- | --- |
| Walmart US (`5296511223`) | Buy Box & WFS | $24.98 (WFS) vs $26.40 3P floor | Monitor 3P seller stockouts; hold MAP above $24.98 |
| Shopify DTC (`allbirds.com`) | US vs DE Markets | Localized EUR pricing delta + 2 OOS sizes | Conquest OOS size keywords with fast-ship ad copy |
| Trustpilot (0-PII) | TrustScore & Flags | Verified 1-2 star delivery/sizing friction | Highlight 30-day free exchanges on PDP hero |

### 2. Verified 1-2 Star Counter-Positioning Angles (0 Reviewer PII)
- **Shipping & Exchange Speed**: Verified negative reviews cluster around slow return processing; promote instant prepaid return labels.
- **Fit Consistency**: Address sizing variance directly with an interactive fit guide above the fold.

4. Production Guardrails, 504 Zero-Charge Retries & Credit Pricing

Zero-Charge HTTP 504 Backoff

CrewAI tasks fail noisy if a single upstream request times out. The call_edgedata() wrapper automatically retries 429/502/503/504 with linear backoff, and EdgeData deducts 0 credits on upstream 504 timeouts.

Strict 0-PII Enterprise Compliance

Trustpilot review calls strip personal reviewer consumer fields by default, so your CrewAI memory files, Slack digests, and S3 battlecard archives remain GDPR-safe out of the box.

Direct Credit Pricing (Transparent, Zero Markup)

$0/mo
Free Sandbox

100 credits/mo — instant key, no credit card required.

$47
Non-Expiring Credit Pack

25,000 credits — one-time purchase, never expires.

$49/mo
Pro Plan

15,000 credits/mo for weekly competitor battlecards.

$149/mo
Scale Plan

60,000 credits/mo for multi-brand agency crews.

5. Get Your Instant Free API Key & Launch the Crew

Generate a free 100 credits/mo EdgeData API key in seconds—no credit card required—export EDGEDATA_API_KEY, and run your 3-agent CrewAI pipeline immediately.