github-actions[bot]
Automated deployment from GitHub Actions: a9d5a91de63ad7224bafe6039fb2b7479388fbf4
0a8c81b Download main.py from VLTA-AI/dropshop: direct link, hf CLI and curl.
- Browser
- Download file 24 kB
-
https://huggingface.co/spaces/VLTA-AI/dropshop/resolve/main/main.py
- Command line
-
hf download hf://spaces/VLTA-AI/dropshop/main.py
-
curl -L -o main.py https://huggingface.co/spaces/VLTA-AI/dropshop/resolve/main/main.py
24 kB
| from dotenv import load_dotenv | |
| load_dotenv() | |
| import uvicorn | |
| import logging | |
| import traceback | |
| from contextlib import asynccontextmanager | |
| import asyncio | |
| import httpx | |
| import os | |
| from datetime import datetime | |
| import inngest | |
| import inngest.fast_api | |
| from fastapi import FastAPI, Request, BackgroundTasks, Form, Response | |
| from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor | |
| from pydantic import BaseModel, ValidationError | |
| # --------------------------------------------------------------------------- | |
| # Native Inngest Observability Middleware | |
| # --------------------------------------------------------------------------- | |
| # This replaces the previous "Monkey Patch" hack (inngest.fast_api._to_response). | |
| # Using the official Middleware API guarantees compatibility across SDK upgrades. | |
| # --------------------------------------------------------------------------- | |
| class InngestObservabilityMiddleware(inngest.Middleware): | |
| """ | |
| Enterprise-grade observability middleware for Inngest function lifecycle. | |
| Hooks: | |
| - before_execution: log function invocation with run_id and event name | |
| - after_execution: log completion or capture exceptions with full stack trace | |
| - before_response: hook for future APM metrics / OpenTelemetry span flushing | |
| """ | |
| def __init__(self, client: inngest.Inngest, raw_request: object) -> None: | |
| super().__init__(client, raw_request) | |
| self._logger = logging.getLogger("inngest.middleware") | |
| async def before_execution(self) -> None: | |
| pass # Available for pre-execution tracing if needed | |
| async def after_execution(self) -> None: | |
| pass # Available for post-execution span flushing | |
| async def before_response(self) -> None: | |
| pass # Available for metrics emission | |
| async def transform_output(self, result: object) -> None: | |
| """ | |
| Called after each function execution, with the raw CallResult. | |
| This is where we capture and log any error that occurred. | |
| """ | |
| if hasattr(result, "error") and result.error is not None: | |
| err = result.error | |
| self._logger.error( | |
| f"[InngestMiddleware] Function execution failed: " | |
| f"{type(err).__name__}: {err}", | |
| exc_info=err if isinstance(err, Exception) else None, | |
| ) | |
| async def lifespan(app: FastAPI): | |
| # Setup OpenTelemetry on startup | |
| from src.utils.telemetry import setup_telemetry | |
| setup_telemetry() | |
| # Initialize the database on startup | |
| from src.models.database import engine, SQLModel | |
| SQLModel.metadata.create_all(engine) | |
| logging.info("Database initialized.") | |
| # Startup: Register with Inngest Cloud | |
| space_host = os.getenv("SPACE_HOST") | |
| if not space_host: | |
| hf_url = os.getenv("HF_SPACE_URL", "") | |
| if "huggingface.co/spaces/" in hf_url: | |
| parts = hf_url.split("spaces/")[-1].split("/") | |
| if len(parts) == 2: | |
| space_host = f"{parts[0].lower()}-{parts[1].lower()}.hf.space" | |
| if space_host: | |
| async def register(): | |
| await asyncio.sleep(5) # Wait for Uvicorn to bind | |
| sync_url = f"https://{space_host}/api/inngest" | |
| async with httpx.AsyncClient() as client: | |
| try: | |
| res = await client.put(sync_url) | |
| logging.info(f"Inngest Auto-Sync triggered: {sync_url} -> {res.status_code}") | |
| except Exception as e: | |
| logging.error(f"Failed to auto-sync Inngest: {e}") | |
| asyncio.create_task(register()) | |
| yield | |
| app = FastAPI(title="VLTA-Dropshopping AI Engine", lifespan=lifespan) | |
| FastAPIInstrumentor.instrument_app(app) | |
| from fastapi.middleware.cors import CORSMiddleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Inngest Client β with native middleware registered | |
| # --------------------------------------------------------------------------- | |
| inngest_client = inngest.Inngest( | |
| app_id="vlta-dropshopping-engine", | |
| is_production=os.getenv("INNGEST_SIGNING_KEY") is not None, | |
| middleware=[InngestObservabilityMiddleware], | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Import event schemas (type-safe contracts) | |
| # --------------------------------------------------------------------------- | |
| from src.schemas.events import ( | |
| CheckoutCompletedEvent, | |
| SourcingStartedEvent, | |
| SourcingTriggerEvent, | |
| ContentGenerateEvent, | |
| ScraperTriggerEvent, | |
| GeminiScraperTriggerEvent, | |
| AutonomousDiscoveryEvent, | |
| ) | |
| from src.agents.selector_agent import process_sourcing_event | |
| # --------------------------------------------------------------------------- | |
| # Inngest Functions | |
| # --------------------------------------------------------------------------- | |
| async def sourcing_started(ctx: inngest.Context) -> dict: | |
| """ | |
| Triggered when the Next.js frontend pushes a new product lead. | |
| Passes execution to the Selector Agent. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = SourcingStartedEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[sourcing_started] Invalid event data: {e}") | |
| raise | |
| data = ctx.event.data | |
| result = await step.run( | |
| "run_selector_agent", | |
| lambda: process_sourcing_event(data) | |
| ) | |
| if result.get("Next_Agent_Suggestion") == "content-agent": | |
| artifacts = result["Generated_Artifacts"] | |
| def insert_to_db(): | |
| from sqlmodel import Session | |
| from src.models.database import engine | |
| from src.models.product_idea import ProductIdea, ProductStatus | |
| with Session(engine) as session: | |
| idea = ProductIdea( | |
| id=artifacts["id"], | |
| source_url=artifacts["source_url"], | |
| primary_image_url=artifacts.get("primary_image_url", ""), | |
| est_total_cost_cny=artifacts["est_total_cost_cny"], | |
| recommended_retail_price_usd=artifacts["recommended_retail_price_usd"], | |
| zone_1_shipping_usd=15.0, | |
| roi_score=result.get("ROI_Score", 0.0), | |
| status=ProductStatus.ANALYZED | |
| ) | |
| session.merge(idea) | |
| session.commit() | |
| await step.run("save_idea_to_db", insert_to_db) | |
| return result | |
| from src.agents.scraper_agent import run_scraper_agent, ScrapingCriteria | |
| async def scraper_trigger(ctx: inngest.Context) -> dict: | |
| """ | |
| Manually or automatically trigger the Apify Amazon Scraper. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = ScraperTriggerEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[scraper_trigger] Invalid event data: {e}") | |
| raise | |
| criteria = ScrapingCriteria( | |
| keyword=event.keyword, | |
| max_items=event.max_items, | |
| target_platform=event.target_platform, | |
| ) | |
| result_ideas = await step.run( | |
| "run_scraper_agent", | |
| lambda: [idea.model_dump() for idea in run_scraper_agent(criteria)] | |
| ) | |
| def insert_scraped_to_db(): | |
| from sqlmodel import Session | |
| from src.models.database import engine | |
| from src.models.product_idea import ProductIdea, ProductStatus | |
| with Session(engine) as session: | |
| for idea_dict in result_ideas: | |
| idea = ProductIdea( | |
| id=idea_dict["id"], | |
| source_url=idea_dict["source_url"], | |
| primary_image_url=idea_dict.get("primary_image_url", ""), | |
| est_total_cost_cny=idea_dict["price_cny"], | |
| recommended_retail_price_usd=idea_dict["retail_price_usd"], | |
| zone_1_shipping_usd=15.0, | |
| status=ProductStatus.SCRAPED | |
| ) | |
| session.merge(idea) | |
| session.commit() | |
| await step.run("save_scraped_to_db", insert_scraped_to_db) | |
| return {"status": "success", "ideas_scraped": len(result_ideas)} | |
| from src.agents.trend_discovery_agent import run_trend_discovery_agent | |
| async def autonomous_discovery_trigger(ctx: inngest.Context) -> dict: | |
| """ | |
| Trigger the Autonomous Trend Discovery Agent to generate niches, | |
| then automatically trigger the Gemini Scraper Agent for each niche. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = AutonomousDiscoveryEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[autonomous_discovery] Invalid event data: {e}") | |
| raise | |
| keywords = await step.run( | |
| "run_trend_discovery_agent", | |
| lambda: run_trend_discovery_agent(count=3) | |
| ) | |
| for i, kw in enumerate(keywords): | |
| await step.send_event( | |
| f"trigger_gemini_scraper_{i}", | |
| { | |
| "name": "dropshopping/scraper.gemini", | |
| "data": {"keyword": kw, "max_items": 5} | |
| } | |
| ) | |
| return {"status": "success", "keywords_discovered": keywords, "events_dispatched": len(keywords)} | |
| from src.agents.gemini_search_scraper import run_gemini_scraper_agent | |
| async def gemini_scraper_trigger(ctx: inngest.Context) -> dict: | |
| """ | |
| 100% Free Scraper using Gemini Search Grounding. | |
| Bypasses Apify by finding real products indexed by Google. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = GeminiScraperTriggerEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[gemini_scraper_trigger] Invalid event data: {e}") | |
| raise | |
| result_ideas = await step.run( | |
| "run_gemini_scraper_agent", | |
| lambda: run_gemini_scraper_agent(event.keyword, event.max_items) | |
| ) | |
| def insert_scraped_to_db(): | |
| from sqlmodel import Session | |
| from src.models.database import engine | |
| from src.models.product_idea import ProductIdea, ProductStatus | |
| with Session(engine) as session: | |
| for idea_dict in result_ideas: | |
| idea = ProductIdea( | |
| id=idea_dict["id"], | |
| source_url=idea_dict.get("source_url", ""), | |
| primary_image_url=idea_dict.get("primary_image_url", ""), | |
| est_total_cost_cny=idea_dict.get("price_cny", 0.0), | |
| recommended_retail_price_usd=idea_dict.get("retail_price_usd", 0.0), | |
| zone_1_shipping_usd=15.0, | |
| status=ProductStatus.SCRAPED | |
| ) | |
| session.merge(idea) | |
| session.commit() | |
| await step.run("save_gemini_scraped_to_db", insert_scraped_to_db) | |
| return {"status": "success", "ideas_scraped": len(result_ideas)} | |
| from src.agents.content_agent import generate_marketing_content | |
| from src.agents.fulfiller_agent import run_fulfiller_agent | |
| def process_fulfillment(event: CheckoutCompletedEvent): | |
| """ | |
| Core fulfillment logic: persists the order to DB (idempotent) then runs | |
| the Fulfiller Agent. Accepts a validated CheckoutCompletedEvent, not raw dict. | |
| """ | |
| from sqlmodel import Session, select | |
| from src.models.database import engine | |
| from src.models.customer_order import CustomerOrder, OrderStatus | |
| import json | |
| logger = logging.getLogger(__name__) | |
| with Session(engine) as session: | |
| order = session.exec( | |
| select(CustomerOrder).where(CustomerOrder.id == event.order_id) | |
| ).first() | |
| if not order: | |
| shipping_json = json.dumps(event.shipping_address.model_dump()) | |
| order = CustomerOrder( | |
| id=event.order_id, | |
| stripe_session_id=event.session_id, | |
| shopify_order_id=event.shopify_order_id, | |
| amount_usd=event.amount_usd, | |
| customer_email=event.customer_email, | |
| shipping_address=shipping_json, | |
| status=OrderStatus.RECEIVED, | |
| mapped_1688_variant_id=event.purchased_sku or "unknown_sku", | |
| quantity=event.quantity, | |
| ) | |
| session.add(order) | |
| session.commit() | |
| logger.info(f"[process_fulfillment] Order {event.order_id} persisted to DB.") | |
| else: | |
| logger.info(f"[process_fulfillment] Order {event.order_id} already exists β skipping insert (idempotent).") | |
| return run_fulfiller_agent(event.order_id) | |
| async def checkout_completed(ctx: inngest.Context) -> dict: | |
| """ | |
| Triggered when Vercel pushes a validated Shopify order event to Inngest Cloud. | |
| Contract: | |
| - Validates incoming data against CheckoutCompletedEvent (Pydantic). | |
| - Any missing/invalid field raises ValidationError HERE, not inside the DB layer. | |
| - Passes a typed event object (not raw dict) to process_fulfillment. | |
| """ | |
| step = ctx.step | |
| logger = logging.getLogger(__name__) | |
| # ββ Gateway: Contract Validation βββββββββββββββββββββββββββββββββββββββ | |
| # This is the single source of truth for what this function accepts. | |
| # A ValidationError here surfaces the exact missing field to Inngest Cloud | |
| # as a clear error message, rather than a cryptic silent 500. | |
| try: | |
| event = CheckoutCompletedEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logger.error( | |
| f"[checkout_completed] β Event data failed schema validation. " | |
| f"This is a publisher-side bug in route.ts or the test script.\n{e}" | |
| ) | |
| raise | |
| logger.info( | |
| f"[checkout_completed] β Schema validated. " | |
| f"order_id={event.order_id} | amount=${event.amount_usd} | email={event.customer_email}" | |
| ) | |
| def process_wrapper(): | |
| return process_fulfillment(event) | |
| result = await step.run("run_fulfiller_agent_active_verify", process_wrapper) | |
| return result | |
| async def content_generation_started(ctx: inngest.Context) -> dict: | |
| """ | |
| Triggered when the Selector Agent approves a product. | |
| Generates marketing content using Gemini LLM. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = ContentGenerateEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[content_generation_started] Invalid event data: {e}") | |
| raise | |
| async def run_content(): | |
| from sqlmodel import Session, select | |
| from src.models.database import engine | |
| from src.models.product_idea import ProductIdea, ProductStatus | |
| with Session(engine) as session: | |
| idea = session.exec( | |
| select(ProductIdea).where(ProductIdea.id == event.id) | |
| ).first() | |
| if not idea: | |
| raise Exception(f"ProductIdea {event.id} not found in DB.") | |
| result = await generate_marketing_content(idea) | |
| idea.status = ProductStatus.PUBLISHED | |
| idea.shopify_title = result.get("title") | |
| keywords = result.get("seo_keywords", []) | |
| idea.marketing_summary = ", ".join(keywords[:3]) if keywords else "Premium dropshipping product." | |
| idea.shopify_product_id = result.get("shopify_product_id") | |
| idea.shopify_product_url = result.get("shopify_product_url") | |
| session.add(idea) | |
| session.commit() | |
| return result | |
| result = await step.run("run_content_agent", run_content) | |
| return result | |
| from src.agents.sourcing_agent import run_sourcing_agent | |
| async def sourcing_trigger(ctx: inngest.Context) -> dict: | |
| """ | |
| Trigger the CJ Dropshipping Sourcing Agent for a batch of products. | |
| """ | |
| step = ctx.step | |
| # ββ Contract Validation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| event = SourcingTriggerEvent(**ctx.event.data) | |
| except ValidationError as e: | |
| logging.getLogger(__name__).error(f"[sourcing_trigger] Invalid event data: {e}") | |
| raise | |
| def source_items(): | |
| from src.models.product_idea import ProductStatus | |
| results = [] | |
| for pid in event.productIds: | |
| try: | |
| idea = run_sourcing_agent(pid) | |
| if idea and idea.status == ProductStatus.ANALYZED: | |
| results.append({ | |
| "id": idea.id, | |
| "source_url": idea.source_url, | |
| "est_total_cost_cny": idea.est_total_cost_cny, | |
| "recommended_retail_price_usd": idea.recommended_retail_price_usd | |
| }) | |
| except Exception as e: | |
| logging.getLogger(__name__).error(f"Sourcing agent failed for {pid}: {e}") | |
| return results | |
| approved_items = await step.run("run_sourcing_agents", source_items) | |
| for i, item in enumerate(approved_items): | |
| await step.send_event( | |
| f"trigger_content_{item['id']}", | |
| { | |
| "name": "dropshopping/content.generate", | |
| "data": { | |
| "id": item["id"], | |
| "source_url": item["source_url"], | |
| "sales_volume": 500, | |
| "est_total_cost_cny": item["est_total_cost_cny"], | |
| "recommended_retail_price_usd": item["recommended_retail_price_usd"], | |
| "status": "Selected" | |
| } | |
| } | |
| ) | |
| return { | |
| "status": "success", | |
| "sourced_count": len(event.productIds), | |
| "auto_approved_count": len(approved_items) | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Serve Inngest API endpoint | |
| # --------------------------------------------------------------------------- | |
| _space_host = os.getenv("SPACE_HOST") | |
| if not _space_host: | |
| _hf_url = os.getenv("HF_SPACE_URL", "") | |
| if "huggingface.co/spaces/" in _hf_url: | |
| _parts = _hf_url.split("spaces/")[-1].split("/") | |
| if len(_parts) == 2: | |
| _space_host = f"{_parts[0].lower()}-{_parts[1].lower()}.hf.space" | |
| serve_origin_url = f"https://{_space_host}" if _space_host else None | |
| inngest.fast_api.serve( | |
| app, | |
| inngest_client, | |
| [ | |
| sourcing_started, | |
| sourcing_trigger, | |
| content_generation_started, | |
| checkout_completed, | |
| scraper_trigger, | |
| autonomous_discovery_trigger, | |
| gemini_scraper_trigger, | |
| ], | |
| serve_origin=serve_origin_url, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # REST Endpoints | |
| # --------------------------------------------------------------------------- | |
| def health_check(): | |
| return {"status": "ok"} | |
| class InboundEmailRequest(BaseModel): | |
| subject: str | |
| body: str | |
| sender: str | |
| from src.agents.email_parsing_agent import EmailParsingAgent | |
| email_agent = EmailParsingAgent() | |
| def handle_inbound_email(req: InboundEmailRequest): | |
| """ | |
| Webhook to receive forwarded emails from suppliers. | |
| Passes the raw text to the EmailParsingAgent for intelligent tracking extraction. | |
| """ | |
| result = email_agent.parse_inbound_email(req.body) | |
| if result["is_shipping_notification"] and result["confidence_score"] > 90: | |
| return {"status": "success", "action": "fulfilled_on_shopify", "data": result} | |
| else: | |
| return {"status": "ignored_or_flagged", "reason": result["reason"]} | |
| class LocalDiscoverRequest(BaseModel): | |
| keyword: str = "trending products" | |
| max_items: int = 5 | |
| async def local_discover(req: LocalDiscoverRequest): | |
| """ | |
| Mode 3: Local Antigravity Agent β runs Gemini scraper SYNCHRONOUSLY. | |
| Bypasses Inngest entirely. Results written directly to DB and returned. | |
| """ | |
| from src.agents.gemini_search_scraper import run_gemini_scraper_agent | |
| from sqlmodel import Session | |
| from src.models.database import engine | |
| from src.models.product_idea import ProductIdea, ProductStatus | |
| ideas = run_gemini_scraper_agent(req.keyword, req.max_items) | |
| saved = [] | |
| with Session(engine) as session: | |
| for idea_dict in ideas: | |
| idea = ProductIdea( | |
| id=idea_dict["id"], | |
| source_url=idea_dict.get("source_url", ""), | |
| primary_image_url=idea_dict.get("primary_image_url", ""), | |
| est_total_cost_cny=idea_dict.get("price_cny", 0.0), | |
| recommended_retail_price_usd=idea_dict.get("retail_price_usd", 0.0), | |
| zone_1_shipping_usd=15.0, | |
| status=ProductStatus.SCRAPED | |
| ) | |
| session.merge(idea) | |
| saved.append({ | |
| "id": idea_dict["id"], | |
| "title": idea_dict.get("title", ""), | |
| "source_url": idea_dict.get("source_url", ""), | |
| "retail_price_usd": idea_dict.get("retail_price_usd", 0.0), | |
| "price_cny": idea_dict.get("price_cny", 0.0), | |
| "primary_image_url": idea_dict.get("primary_image_url", ""), | |
| }) | |
| session.commit() | |
| return {"status": "success", "ideas_scraped": len(saved), "ideas": saved} | |
| from src.agents.customer_bot_agent import CustomerBotAgent | |
| customer_bot = CustomerBotAgent() | |
| async def handle_whatsapp_webhook( | |
| Body: str = Form(...), | |
| From: str = Form(...), | |
| ): | |
| """ | |
| Twilio Webhook for incoming WhatsApp messages. | |
| Returns a TwiML XML response. | |
| """ | |
| import re | |
| email_match = re.search(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', Body) | |
| user_email = email_match.group(0).rstrip('.') if email_match else "" | |
| bot_response = customer_bot.process_message(Body, user_email) | |
| twiml_response = f"""<?xml version="1.0" encoding="UTF-8"?> | |
| <Response> | |
| <Message>{bot_response.reply_text}</Message> | |
| </Response>""" | |
| return Response(content=twiml_response, media_type="application/xml") | |