ifixkart-backend/swarm/agents/customer.py

326 lines
12 KiB
Python

"""
One simulated customer = one identity + one authenticated HTTP session + one
real journey through the IfixKart API.
The agent does not insert rows directly. It registers a session through the
normal login endpoint, browses the public catalog, adds real cart items, checks
out, pays through the simulation-only gateway and verifies the resulting order.
"""
from __future__ import annotations
import asyncio
import random
import time
from dataclasses import asdict, dataclass, field
from typing import Any, Optional
import httpx
from swarm.agents.personas import Persona
class JourneyError(RuntimeError):
pass
@dataclass
class JourneyResult:
agent_index: int
email: str
persona_id: str
outcome: str
order_id: Optional[str] = None
order_no: Optional[str] = None
amount: float = 0.0
steps: list[str] = field(default_factory=list)
error: str = ""
duration_ms: int = 0
status_code: int = 0
def to_dict(self) -> dict[str, Any]:
return asdict(self)
class CustomerAgent:
def __init__(
self,
*,
client: httpx.AsyncClient,
agent_index: int,
account: dict[str, Any],
persona: Persona,
rng: random.Random,
think_time_scale: float = 0.05,
request_timeout: float = 45.0,
metrics=None,
) -> None:
self.client = client
self.index = agent_index
self.account = account
self.persona = persona
self.rng = rng
self.think_scale = think_time_scale
self.request_timeout = request_timeout
self.metrics = metrics
self.token: Optional[str] = None
self.steps: list[str] = []
self.products: list[dict[str, Any]] = []
# ---------- low-level helpers ----------
async def _think(self, low: float, high: float) -> None:
delay = self.rng.uniform(low, high) * self.think_scale
if delay > 0:
await asyncio.sleep(delay)
async def _request(
self,
method: str,
path: str,
*,
expected: tuple[int, ...] = (200,),
**kwargs,
) -> httpx.Response:
headers = kwargs.pop("headers", {})
headers.setdefault("user-agent", f"IfixKartSwarm/{self.persona.device}")
if self.token:
headers.setdefault("authorization", f"Bearer {self.token}")
started = time.perf_counter()
try:
response = await self.client.request(
method,
path,
headers=headers,
timeout=self.request_timeout,
**kwargs,
)
except Exception as exc:
if self.metrics:
await self.metrics.record_request(path, 0, time.perf_counter() - started, error=type(exc).__name__)
raise JourneyError(f"{method} {path} failed: {type(exc).__name__}: {exc}") from exc
elapsed = time.perf_counter() - started
if self.metrics:
await self.metrics.record_request(path, response.status_code, elapsed)
if response.status_code not in expected:
text = response.text[:500].replace("\n", " ")
raise JourneyError(f"{method} {path} -> {response.status_code}: {text}")
return response
# ---------- journey steps ----------
async def _login(self) -> None:
response = await self._request(
"POST",
"/api/v1/customer/auth/login",
expected=(200,),
json={"email": self.account["email"], "password": self.account["password"]},
)
self.token = response.json()["access_token"]
self.steps.append("login")
async def _get_address(self) -> str:
response = await self._request("GET", "/api/v1/customer/profile/addresses", expected=(200,))
addresses = response.json()
if addresses:
self.steps.append("load_address")
return addresses[0]["address_id"]
payload = {
"address_type": "SHIPPING",
"full_name": f"{self.account['first_name']} {self.account['last_name']}",
"phone": f"9{self.rng.randint(100000000, 999999999)}"[:10],
"street_address": f"{self.rng.randint(1, 200)}, {self.rng.choice(['MG Road', 'Anna Nagar', 'Banjara Hills', 'Park Street'])}",
"city": self.persona.city,
"state": self.persona.state,
"pincode": self.persona.pincode,
"is_default": True,
}
response = await self._request("POST", "/api/v1/customer/profile/addresses", expected=(200,), json=payload)
self.steps.append("create_address")
return response.json()["address_id"]
async def _catalog(self) -> None:
page = 1
products: list[dict[str, Any]] = []
while True:
response = await self._request(
"GET",
"/api/v1/catalog/products",
expected=(200,),
params={"page": page, "limit": 100},
)
body = response.json()
batch = body.get("products") or []
products.extend(batch)
if not batch or len(products) >= int(body.get("total") or 0) or page >= 3:
break
page += 1
self.products = [p for p in products if p.get("first_variant_id")]
if not self.products:
raise JourneyError("catalog returned no purchasable variants")
self.steps.append(f"catalog:{len(self.products)}")
def _choose_products(self) -> list[dict[str, Any]]:
def score(product: dict[str, Any]) -> tuple[float, float]:
name = (product.get("name") or "").lower()
price = float(product.get("price") or 0)
affinity = 0.0
for keyword in self.persona.preferred_keywords:
if keyword in name:
affinity += 2.0
if price <= self.persona.budget_max:
affinity += 1.0
else:
affinity -= 2.0
return (affinity, self.rng.random())
ranked = sorted(self.products, key=score, reverse=True)
in_budget = [p for p in ranked if float(p.get("price") or 0) <= self.persona.budget_max]
chosen = in_budget or sorted(self.products, key=lambda p: float(p.get("price") or 0))
return chosen[: max(4, self.persona.browse_depth + 2)]
async def _browse(self) -> bool:
candidates = self._choose_products()
depth = min(self.persona.browse_depth, len(candidates))
for product in candidates[:depth]:
slug = product.get("slug")
if not slug:
continue
try:
await self._request("GET", f"/api/v1/catalog/products/detail/{slug}", expected=(200,))
except JourneyError:
# A detail page 404 should not kill the whole journey.
pass
await self._think(1.0, 4.0)
self.steps.append(f"browse:{depth}")
return self.rng.random() < self.persona.conversion_prob
async def _add_to_cart(self, candidates: list[dict[str, Any]]) -> float:
added = 0
total_qty = 0
desired = 1
if self.rng.random() < 0.25:
desired = 2
for product in candidates:
if added >= 2:
break
qty = self.persona.quantity_pref if added == 0 else 1
if desired == 1:
qty = 1
try:
response = await self._request(
"POST",
"/api/v1/cart/items",
expected=(200,),
json={"variant_id": product["first_variant_id"], "qty": qty},
)
added += 1
total_qty += qty
self.steps.append(f"cart_add:{product.get('slug', '')[:40]}:{qty}")
await self._think(1.0, 3.0)
if response.json().get("total_amount") is not None:
continue
except JourneyError:
continue
if added == 0:
raise JourneyError("could not add any item to cart")
self.steps.append(f"cart_items:{total_qty}")
return total_qty
async def run(self) -> JourneyResult:
started = time.perf_counter()
result = JourneyResult(
agent_index=self.index,
email=self.account["email"],
persona_id=self.persona.persona_id,
outcome="ERROR",
)
try:
await self._login()
await self._think(0.5, 2.0)
address_id = await self._get_address()
await self._think(0.5, 2.0)
await self._catalog()
await self._think(1.0, 3.0)
candidates = self._choose_products()
wants_to_buy = await self._browse()
if not wants_to_buy:
result.outcome = "BROWSE_ABANDON"
result.steps = self.steps
result.duration_ms = int((time.perf_counter() - started) * 1000)
return result
await self._add_to_cart(candidates)
await self._think(1.0, 4.0)
if self.rng.random() < self.persona.cart_abandon_prob:
result.outcome = "CART_ABANDON"
result.steps = self.steps
result.duration_ms = int((time.perf_counter() - started) * 1000)
return result
checkout = await self._request(
"POST",
"/api/v1/checkout/create",
expected=(200,),
json={"address_id": address_id, "payment_method": "RAZORPAY"},
)
order = checkout.json()
result.order_id = order.get("order_id")
result.order_no = order.get("order_no")
result.amount = float(order.get("final_amount") or 0)
self.steps.append("checkout")
await self._think(1.0, 4.0)
if self.rng.random() < self.persona.payment_fail_prob:
try:
await self._request(
"POST",
"/api/v1/payment/cancel",
expected=(200,),
json={"order_id": result.order_id, "reason": "Simulated payment failure/abandonment"},
)
except JourneyError:
pass
result.outcome = "PAYMENT_FAILED"
result.steps = self.steps
result.duration_ms = int((time.perf_counter() - started) * 1000)
return result
paid = await self._request(
"POST",
"/api/v1/payment/simulate",
expected=(200,),
json={"order_id": result.order_id, "note": "IfixKart swarm simulated payment"},
)
self.steps.append("payment_simulated")
body = paid.json()
if body.get("status") != "SUCCESS":
raise JourneyError(f"simulated payment did not succeed: {body}")
verified = await self._request(
"GET",
f"/api/v1/orders/{result.order_id}",
expected=(200,),
)
final = verified.json()
result.outcome = "ORDER_CONFIRMED"
result.amount = float(final.get("final_amount") or result.amount)
self.steps.append("order_verified")
return result
except JourneyError as exc:
result.outcome = "ERROR"
result.error = str(exc)
result.status_code = 0
except Exception as exc: # defensive: never let one agent kill the fleet
result.outcome = "ERROR"
result.error = f"{type(exc).__name__}: {exc}"
finally:
result.steps = self.steps
result.duration_ms = int((time.perf_counter() - started) * 1000)
return result