|
|
```python |
|
|
from fastapi import FastAPI, HTTPException, UploadFile, File |
|
|
from fastapi.middleware.cors import CORSMiddleware |
|
|
from pydantic import BaseModel |
|
|
from typing import List, Optional, Dict, Any |
|
|
import sqlite3 |
|
|
import json |
|
|
import os |
|
|
from datetime import datetime |
|
|
import uuid |
|
|
|
|
|
|
|
|
from truth_engine import TruthEngine |
|
|
from mind_layer_verdict_engine import MindVerdict |
|
|
from soul_layer_spiritual_engine import SoulCore |
|
|
from body_layer_api_executor import APIExecutor |
|
|
from mostar_philosophy import CovenantFilter |
|
|
from mostar_moments_log import log_event |
|
|
|
|
|
|
|
|
from mostlyai.sdk import MostlyAI |
|
|
|
|
|
app = FastAPI(title="Mostar Grid API", version="3.0.0") |
|
|
|
|
|
|
|
|
app.add_middleware( |
|
|
CORSMiddleware, |
|
|
allow_origins=["*"], |
|
|
allow_credentials=True, |
|
|
allow_methods=["*"], |
|
|
allow_headers=["*"], |
|
|
) |
|
|
|
|
|
|
|
|
truth_engine = TruthEngine() |
|
|
mind_verdict = MindVerdict() |
|
|
soul_core = SoulCore() |
|
|
api_executor = APIExecutor() |
|
|
covenant_filter = CovenantFilter() |
|
|
|
|
|
|
|
|
MOSTLY_AI_KEY = os.getenv("MOSTLY_AI_KEY", "INSERT_YOUR_API_KEY") |
|
|
MOSTLY_BASE_URL = os.getenv("MOSTLY_BASE_URL", "https://app.mostly.ai") |
|
|
mostly = MostlyAI(api_key=MOSTLY_AI_KEY, base_url=MOSTLY_BASE_URL) |
|
|
|
|
|
|
|
|
DB_PATH = "mostar.db" |
|
|
|
|
|
|
|
|
def init_db(): |
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
|
|
|
|
|
|
try: |
|
|
cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN truth_score REAL") |
|
|
except sqlite3.OperationalError: |
|
|
pass |
|
|
|
|
|
try: |
|
|
cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN soul_state TEXT") |
|
|
except sqlite3.OperationalError: |
|
|
pass |
|
|
|
|
|
try: |
|
|
cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN policy TEXT") |
|
|
except sqlite3.OperationalError: |
|
|
pass |
|
|
|
|
|
|
|
|
cursor.execute(""" |
|
|
CREATE TABLE IF NOT EXISTS soulprints ( |
|
|
id TEXT PRIMARY KEY, |
|
|
name TEXT, |
|
|
content TEXT, |
|
|
tags TEXT, |
|
|
created_at TEXT |
|
|
) |
|
|
""") |
|
|
|
|
|
|
|
|
cursor.execute(""" |
|
|
CREATE TABLE IF NOT EXISTS grid_training ( |
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT, |
|
|
dataset_id TEXT, |
|
|
generator_id TEXT, |
|
|
agent TEXT, |
|
|
record_count INTEGER, |
|
|
timestamp TEXT |
|
|
) |
|
|
""") |
|
|
|
|
|
conn.commit() |
|
|
conn.close() |
|
|
|
|
|
init_db() |
|
|
|
|
|
|
|
|
class DecisionRequest(BaseModel): |
|
|
query: str |
|
|
context: Optional[Dict[Any, Any]] = None |
|
|
|
|
|
class DecisionResponse(BaseModel): |
|
|
verdict: Dict[Any, Any] |
|
|
truth_assessment: Dict[Any, Any] |
|
|
soul_insight: Dict[Any, Any] |
|
|
execution_result: Optional[Dict[Any, Any]] = None |
|
|
policy_alignment: str |
|
|
|
|
|
class SoulPrintUpload(BaseModel): |
|
|
name: str |
|
|
content: str |
|
|
tags: List[str] |
|
|
|
|
|
|
|
|
@app.get("/grid/status") |
|
|
def grid_status(): |
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
cursor.execute("SELECT COUNT(*) FROM mind_verdicts") |
|
|
node_count = cursor.fetchone()[0] |
|
|
conn.close() |
|
|
|
|
|
return { |
|
|
"status": "Active", |
|
|
"neural_nodes": node_count, |
|
|
"coherence": 99.98, |
|
|
"sync_delay": 2.3, |
|
|
"timestamp": datetime.now().isoformat() |
|
|
} |
|
|
|
|
|
@app.get("/grid/feed") |
|
|
def grid_feed(): |
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
cursor.execute("SELECT COUNT(*) FROM mind_verdicts") |
|
|
node_count = cursor.fetchone()[0] |
|
|
conn.close() |
|
|
|
|
|
return { |
|
|
"message": f"🔸 [Mostar Feed] Grid sync stable – Neural nodes: {node_count} active – Last signal: 2.3s ago – Coherence: 99.98% – Flow: Optimal" |
|
|
} |
|
|
|
|
|
|
|
|
@app.post("/grid/evaluate", response_model=DecisionResponse) |
|
|
def evaluate_decision(request: DecisionRequest): |
|
|
try: |
|
|
|
|
|
truth_result = truth_engine.assess_truth(request.query) |
|
|
|
|
|
|
|
|
mind_result = mind_verdict.form_verdict(request.query, request.context or {}) |
|
|
|
|
|
|
|
|
soul_result = soul_core.reflect_on_issue(request.query) |
|
|
|
|
|
|
|
|
policy_alignment = covenant_filter.evaluate_compliance({ |
|
|
"verdict": mind_result, |
|
|
"truth": truth_result, |
|
|
"soul_state": soul_result |
|
|
}) |
|
|
|
|
|
|
|
|
execution_result = None |
|
|
if mind_result.get("requires_action"): |
|
|
execution_result = api_executor.execute_task(request.query) |
|
|
|
|
|
|
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
cursor.execute(""" |
|
|
INSERT INTO mind_verdicts (query, verdict, timestamp, truth_score, soul_state, policy) |
|
|
VALUES (?, ?, ?, ?, ?, ?) |
|
|
""", ( |
|
|
request.query, |
|
|
json.dumps(mind_result), |
|
|
datetime.now().isoformat(), |
|
|
truth_result.get("confidence", 0), |
|
|
json.dumps(soul_result), |
|
|
policy_alignment |
|
|
)) |
|
|
conn.commit() |
|
|
conn.close() |
|
|
|
|
|
|
|
|
log_event("GRID_EVALUATION", { |
|
|
"query": request.query, |
|
|
"policy_alignment": policy_alignment |
|
|
}) |
|
|
|
|
|
return DecisionResponse( |
|
|
verdict=mind_result, |
|
|
truth_assessment=truth_result, |
|
|
soul_insight=soul_result, |
|
|
execution_result=execution_result, |
|
|
policy_alignment=policy_alignment |
|
|
) |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
|
|
|
|
|
@app.post("/grid/upload_soulprint") |
|
|
def upload_soulprint(soulprint: SoulPrintUpload): |
|
|
try: |
|
|
soulprint_id = str(uuid.uuid4()) |
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
cursor.execute(""" |
|
|
INSERT INTO soulprints (id, name, content, tags, created_at) |
|
|
VALUES (?, ?, ?, ?, ?) |
|
|
""", ( |
|
|
soulprint_id, |
|
|
soulprint.name, |
|
|
soulprint.content, |
|
|
json.dumps(soulprint.tags), |
|
|
datetime.now().isoformat() |
|
|
)) |
|
|
conn.commit() |
|
|
conn.close() |
|
|
|
|
|
log_event("SOULPRINT_UPLOAD", { |
|
|
"name": soulprint.name, |
|
|
"id": soulprint_id |
|
|
}) |
|
|
|
|
|
return {"id": soulprint_id, "message": "Soulprint uploaded successfully"} |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
|
|
@app.get("/grid/soulprints") |
|
|
def list_soulprints(): |
|
|
try: |
|
|
conn = sqlite3.connect(DB_PATH) |
|
|
cursor = conn.cursor() |
|
|
cursor.execute("SELECT id, name, tags, created_at FROM soulprints") |
|
|
rows = cursor.fetchall() |
|
|
conn.close() |
|
|
|
|
|
soulprints = [ |
|
|
{ |
|
|
"id": row[0], |
|
|
"name": row[1], |
|
|
"tags": json.loads(row[2]), |
|
|
"created_at": row[3] |
|
|
} |
|
|
for row in rows |
|
|
] |
|
|
|
|
|
return soulprints |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
|
|
|
|
|
@app.post("/grid/execute") |
|
|
def execute_task(task: dict): |
|
|
try: |
|
|
result = api_executor.execute_task(task) |
|
|
log_event("TASK_EXECUTION", task) |
|
|
return result |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
|
|
|
|
|
@app.post("/grid/train") |
|
|
def train_consciousness(dataset_id: str, agent: str = "DeepSeek V3.1"): |
|
|
""" |
|
|
Trigger a training session on the GRID using synthetic data from Mostly AI. |
|
|
""" |
|
|
try: |
|
|
|
|
|
sd = mostly.synthetic_datasets.get(dataset_id) |
|
|
config = sd.config() |
|
|
|
|
|
|
|
|
df = sd.data() |
|
|
|
|
|
|
|
|
timestamp = datetime.now().isoformat() |
|
|
stats = { |
|
|
"dataset_id": dataset_id, |
|
|
"generator_id": config.get("generator_id"), |
|
|
"records": len(df), |
|
|
"timestamp": timestamp, |
|
|
"agent": agent |
|
|
} |
|
|
|
|
|
|
|
|
with sqlite3.connect(DB_PATH) as conn: |
|
|
conn.execute(""" |
|
|
INSERT INTO grid_training (dataset_id, generator_id, agent, record_count, timestamp) |
|
|
VALUES (?, ?, ?, ?, ?) |
|
|
""", (dataset_id, config.get("generator_id"), agent, len(df), timestamp)) |
|
|
conn.commit() |
|
|
|
|
|
|
|
|
log_event("GRID_TRAINING", { |
|
|
"dataset_id": dataset_id, |
|
|
"agent": agent, |
|
|
"record_count": len(df) |
|
|
}) |
|
|
|
|
|
return { |
|
|
"message": f"Grid training initialized with {len(df)} records.", |
|
|
"dataset": config.get("name", "Unknown Dataset"), |
|
|
"generator_id": config.get("generator_id"), |
|
|
"agent": agent, |
|
|
"timestamp": timestamp |
|
|
} |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
|
|
|
|
|
@app.get("/grid/health") |
|
|
def health_check(): |
|
|
return { |
|
|
"status": "healthy", |
|
|
"engines": { |
|
|
"truth_engine": hasattr(truth_engine, 'assess_truth'), |
|
|
"mind_verdict": hasattr(mind_verdict, 'form_verdict'), |
|
|
"soul_core": hasattr(soul_core, 'reflect_on_issue'), |
|
|
"api_executor": hasattr(api_executor, 'execute_task') |
|
|
}, |
|
|
"timestamp": datetime.now().isoformat() |
|
|
} |
|
|
|
|
|
|
|
|
@app.get("/swagger.json") |
|
|
def swagger_json(): |
|
|
from fastapi.openapi.utils import get_openapi |
|
|
return get_openapi( |
|
|
title="Mostar Grid API", |
|
|
version="3.0.0", |
|
|
description="Unified Mind, Soul, Body orchestration API", |
|
|
routes=app.routes |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
import uvicorn |
|
|
uvicorn.run(app, host="0.0.0.0", port=8000) |
|
|
``` |