import os
import sys
import requests
BASE = "https://api.swarms.world"
HEADERS = {"x-api-key": os.environ["SWARMS_API_KEY"], "Content-Type": "application/json"}
# The nightly catalog job enriches every new SKU in the feed. Before it
# starts, check the credit balance in Swarms Cloud and stop early if the
# account cannot cover the batch, instead of failing halfway through.
credits = requests.get(f"{BASE}/v1/account/credits", headers=HEADERS, timeout=30).json()
print("credits:", credits)
new_rows = [
{"sku": "CW-2041-BLK", "vendor_title": "SAUCEPAN 20CM S/S INDUCTION BLK HNDL"},
{"sku": "CW-2042-BLK", "vendor_title": "SAUCEPAN 16CM S/S INDUCTION BLK HNDL"},
{"sku": "BK-1177-WHT", "vendor_title": "MIXING BOWL SET 3PC CERAMIC WHT"},
]
# A conservative budget per SKU, agreed with finance for this job.
BUDGET_PER_SKU_USD = 0.05
needed = BUDGET_PER_SKU_USD * len(new_rows)
balance = None
for key in ("credits", "credit", "balance"):
if isinstance(credits, dict) and isinstance(credits.get(key), (int, float)):
balance = float(credits[key])
break
if balance is not None and balance < needed:
print(f"stopping: {len(new_rows)} SKUs need about {needed:.2f} USD, balance is {balance:.2f}")
sys.exit(1)
def enrich_request(row: dict) -> dict:
return {
"name": f"Catalog Enrichment {row['sku']}",
"swarm_type": "AgentRearrange",
"rearrange_flow": "Intake -> Copywriter, Attributes -> Compliance -> Publisher",
"task": f"Enrich this supplier row into a complete listing: {row}",
"agents": [
{"agent_name": "Intake", "system_prompt": "Normalise the supplier row into clean JSON.", "model_name": "gemini-2.5-flash", "max_loops": 1},
{"agent_name": "Copywriter", "system_prompt": "Write a title under 80 characters and five bullets from the row only.", "model_name": "claude-sonnet-5-5", "max_loops": 1},
{"agent_name": "Attributes", "system_prompt": "Extract structured attributes as JSON; unknown values are null.", "model_name": "gpt-4.1-mini", "max_loops": 1},
{"agent_name": "Compliance", "system_prompt": "Flag banned claims, missing statements and invented specs per market.", "model_name": "gpt-5.4", "max_loops": 1},
{"agent_name": "Publisher", "system_prompt": "Assemble the final listing JSON per market.", "model_name": "claude-haiku-5-5", "max_loops": 1},
],
"max_loops": 1,
}
batch = [enrich_request(row) for row in new_rows]
resp = requests.post(f"{BASE}/v1/swarm/batch/completions", headers=HEADERS, json=batch, timeout=900)
resp.raise_for_status()
for row, result in zip(new_rows, resp.json()):
usage = result.get("usage", {})
print(row["sku"], "tokens:", usage.get("total_tokens"))
# Afterwards the run totals are in Swarms Cloud, or from the API:
print(requests.get(f"{BASE}/v1/metrics/summary", headers=HEADERS, timeout=30).json())