import os import subprocess import requests import random from fastapi import FastAPI, HTTPException from pydantic import BaseModel from huggingface_hub import InferenceClient # --- CONFIG --- app = FastAPI(title="APEX AI Sentinel") GO_LEDGER_URL = "http://localhost:8080" HF_TOKEN = os.environ.get("HF_TOKEN") # Setup AI Client (Using Mistral or similar free model) client = InferenceClient(model="mistralai/Mistral-7B-Instruct-v0.2", token=HF_TOKEN) # In-Memory Puzzle Storage (For now) active_puzzles = {} class MiningRequest(BaseModel): user_address: str solution_code: str puzzle_id: str class WalletRequest(BaseModel): user_address: str # --- ROUTES --- @app.get("/") def home(): return {"status": "APEX System Online", "role": "Sentinel AI"} @app.post("/get_puzzle") def get_puzzle(req: WalletRequest): # 1. AI Generates a Logic Puzzle difficulty = random.randint(1, 100) prompt = f"Generate a coding challenge (Python/Math) with difficulty {difficulty}/100. Output only the challenge text." # We use a fallback if AI is slow, otherwise call AI try: challenge_text = client.text_generation(prompt, max_new_tokens=150) except: challenge_text = "Calculate the 50th Fibonacci number." puzzle_id = f"puz_{random.randint(10000,99999)}" active_puzzles[puzzle_id] = challenge_text return { "puzzle_id": puzzle_id, "challenge": challenge_text, "difficulty": difficulty } @app.post("/submit_mine") def submit_mine(req: MiningRequest): # 1. Validate Puzzle ID if req.puzzle_id not in active_puzzles: raise HTTPException(status_code=400, detail="Invalid Puzzle ID") # 2. Run C++ Engine to verify 'work' (Simulated here using subprocess) # In a real scenario, we compile the user's code. # Here we check if their 'solution string' passes the C++ engine check. # Calling the C++ binary we compiled in Dockerfile process = subprocess.run( ["./apex_engine", req.puzzle_id, req.solution_code], capture_output=True, text=True ) if process.returncode == 0: # 3. SUCCESS! Tell Go Ledger to Mint Coin payload = {"address": req.user_address, "amount": 1.0} try: r = requests.post(f"{GO_LEDGER_URL}/mint", json=payload) return r.json() except: raise HTTPException(status_code=500, detail="Ledger Error") else: return {"status": "FAILED", "reason": "Solution Rejected by C++ Engine"} @app.post("/my_balance") def get_balance(req: WalletRequest): # Proxy request to Go Ledger r = requests.post(f"{GO_LEDGER_URL}/balance", json={"address": req.user_address}) return r.json()