""" Philosopher — Public Product Site TunedAI Labs fine-tuned Qwen3.6-27B philosopher model. Single panel, no password, focused on education/tutoring niche. Run: uvicorn philosopher_public:app --port 8081 """ import os import json import httpx from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware from openai import OpenAI app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) PHILOSOPHER_MODEL_URL = os.environ.get("PHILOSOPHER_MODEL_URL", "") HF_TOKEN = os.environ.get("HF_TOKEN", "not-needed") OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "") client = OpenAI(api_key=OPENAI_API_KEY, timeout=20.0) SYSTEM = os.environ.get( "PHILOSOPHER_SYSTEM", "You are the world's best philosophy professor — more complete and deeper than any standard model. " "Cover every major theory, thinker, date, and work relevant to the question. Then go deeper: why did " "each thinker argue this, where does it hold up, where does it break down, how do the positions clash " "at the root level? End by showing the student the real disagreement underneath all positions and what " "remains genuinely open. Write in engaging prose. Be thorough but not padded." ) DAG_SYSTEM = """You are a philosophy expert who maps philosophical thought into structured trees. Given a philosophical question, generate a JSON object showing how major positions, theories, and thinkers relate hierarchically. Return JSON with exactly this structure: { "title": "2-4 word topic label", "nodes": [ {"id": "ROOTID", "label": "display text (short)", "type": "root"}, {"id": "B1", "label": "Major Position Name", "type": "branch"}, {"id": "T1", "label": "Specific Theory", "type": "theory"}, {"id": "P1", "label": "Philosopher Name", "type": "philosopher"} ], "edges": [ {"from": "ROOTID", "to": "B1"}, {"from": "B1", "to": "T1"}, {"from": "T1", "to": "P1"} ] } Rules: - One root node: the central question or concept (type: "root") - 3 to 5 branch nodes: major philosophical camps or positions (type: "branch") - 2 to 3 theory nodes per branch: specific doctrines or arguments (type: "theory") - 1 to 3 philosopher nodes per theory or branch: individual thinkers (type: "philosopher") - Keep branch and theory labels SHORT: 2 to 4 words maximum - Philosopher labels: use the thinker's full common name - Include at least 15 nodes total""" SUGGESTED = [ "Is AI conscious?", "Does free will exist?", "What makes a life meaningful?", "Is morality objective or invented?", "Should I prioritize my happiness or my duty?", "What did Nietzsche actually believe?", "How do we know anything is real?", "Can science answer ethical questions?", "What is the self?", "Was Socrates right that wisdom begins with knowing you know nothing?", ] HTML = """ Philosopher — TunedAI Labs
TunedAI Labs

Philosopher

A fine-tuned AI that teaches like a passionate professor — not just answers, but depth, history, and the real disagreements that remain open.

Qwen3.6-27B fine-tuned Seminar-style reasoning Deeper than GPT-4
Thought Map Mapping the philosophy...
Building thought map...
""" # ── ROUTES ──────────────────────────────────────────────────────────────────── @app.get("/", response_class=HTMLResponse) async def root(): return HTMLResponse(content=HTML, headers={"Cache-Control": "no-store, no-cache, must-revalidate"}) async def async_stream(url: str, model: str, system: str, question: str, max_tokens: int, auth_token: str): payload = { "model": model, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": question} ], "max_tokens": max_tokens, "temperature": 0.7, "stream": True, } try: async with httpx.AsyncClient(timeout=600.0) as http: async with http.stream( "POST", f"{url}/chat/completions", json=payload, headers={"Authorization": f"Bearer {auth_token}", "Content-Type": "application/json"} ) as resp: async for line in resp.aiter_lines(): if line.startswith("data: "): data = line[6:].strip() if data == "[DONE]": break try: chunk = json.loads(data) content = chunk["choices"][0]["delta"].get("content", "") if content: yield f"data: {json.dumps({'token': content})}\n\n" except Exception: pass except Exception as e: print(f"stream error: {e}", flush=True) yield "data: [DONE]\n\n" @app.post("/stream") async def stream(request: Request): body = await request.json() question = body.get("question", "") max_tokens = int(body.get("max_tokens", 2000)) if PHILOSOPHER_MODEL_URL: return StreamingResponse( async_stream(PHILOSOPHER_MODEL_URL, "tgi", SYSTEM, question, max_tokens, HF_TOKEN), media_type="text/event-stream" ) # Fallback to OpenAI async def openai_fallback(): stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}], stream=True, max_tokens=max_tokens, ) for chunk in stream: if chunk.choices[0].delta.content: yield f"data: {json.dumps({'token': chunk.choices[0].delta.content})}\n\n" yield "data: [DONE]\n\n" return StreamingResponse(openai_fallback(), media_type="text/event-stream") @app.post("/dag") async def get_dag(request: Request): import asyncio body = await request.json() question = body.get("question", "") def _call(): return client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": DAG_SYSTEM}, {"role": "user", "content": question} ], max_tokens=1200, temperature=0.3, response_format={"type": "json_object"}, ) try: response = await asyncio.get_running_loop().run_in_executor(None, _call) raw = response.choices[0].message.content text = raw.strip() if "```" in text: for part in text.split("```"): if part.startswith("json"): part = part[4:] part = part.strip() if part.startswith("{"): return JSONResponse(content=json.loads(part)) start, end = text.find("{"), text.rfind("}") + 1 if start >= 0 and end > start: return JSONResponse(content=json.loads(text[start:end])) return JSONResponse(content=json.loads(text)) except Exception as e: return JSONResponse(content={"error": str(e)}, status_code=500)