Spaces:
Paused
Paused
Download app.py from ihhereanth/CharacterAi: direct link, hf CLI and curl.
- Browser
- Download file 9.38 kB
-
https://huggingface.co/spaces/ihhereanth/CharacterAi/resolve/main/app.py
- Command line
-
hf download hf://spaces/ihhereanth/CharacterAi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ihhereanth/CharacterAi/resolve/main/app.py
9.38 kB
| """Stateless middleware; Roblox owns identity, filtering, and durable memory.""" | |
| import asyncio | |
| import hashlib | |
| import hmac | |
| import json | |
| import os | |
| import re | |
| import time | |
| from collections import OrderedDict, deque | |
| from pathlib import Path | |
| from typing import Literal | |
| import httpx | |
| from fastapi import Depends, FastAPI, Header, HTTPException, Request | |
| from pydantic import BaseModel, ConfigDict, Field | |
| app = FastAPI(title="CharacterAI", docs_url=None, redoc_url=None, openapi_url=None) | |
| EMOTIONS = {"neutral", "happy", "sad", "angry", "surprised", "curious", "shy"} | |
| EMOTES = {"Angry", "ShyLaugh", "Laugh", "Curious", "Wave", "Sit", "Shy", "Thinking"} | |
| slots = asyncio.Semaphore(8) | |
| minute = deque() | |
| day_count = 0 | |
| day_number = 0 | |
| cache = OrderedDict() | |
| pending = set() | |
| class Strict(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| class Character(Strict): | |
| id: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9_-]+$") | |
| name: str = Field(min_length=1, max_length=40) | |
| personality: str = Field(max_length=1000) | |
| class Turn(Strict): | |
| role: Literal["user", "assistant"] | |
| content: str = Field(min_length=1, max_length=1200) | |
| class ChatRequest(Strict): | |
| request_id: str = Field(min_length=16, max_length=64) | |
| universe_id: int | |
| token_budget: int = Field(ge=1, le=10000) | |
| character: Character | |
| message: str = Field(min_length=1, max_length=400) | |
| memory: str = Field(default="", max_length=1600) | |
| history: list[Turn] = Field(default_factory=list, max_length=20) | |
| def settings(): | |
| return os.getenv("OPENROUTER_API_KEY", ""), os.getenv("ROBLOX_SHARED_SECRET", "") | |
| def ready(): | |
| key, secret = settings() | |
| return bool(key and len(secret) >= 32 and os.getenv("ROBLOX_UNIVERSE_ID", "").isdigit()) | |
| async def authorize(authorization: str = Header(default="")): | |
| _, secret = settings() | |
| if not ready(): | |
| raise HTTPException(503, "Server configuration incomplete") | |
| if not hmac.compare_digest(authorization, "Bearer " + secret): | |
| raise HTTPException(401, "Unauthorized") | |
| async def limit_body(request: Request, call_next): | |
| # Bound streaming bodies too; Content-Length alone is not sufficient. | |
| if request.method == "POST": | |
| size = 0 | |
| chunks = [] | |
| async for chunk in request.stream(): | |
| size += len(chunk) | |
| if size > 48000: | |
| from fastapi.responses import JSONResponse | |
| return JSONResponse({"detail": "Request too large"}, status_code=413) | |
| chunks.append(chunk) | |
| request._body = b"".join(chunks) | |
| return await call_next(request) | |
| async def home(): | |
| return {"service": "CharacterAI Roblox middleware", "health": "/health"} | |
| async def health(): | |
| return {"ok": True, "ready": ready(), "version": "3.0.0"} | |
| def build_messages(body: ChatRequest): | |
| config = json.loads(Path(__file__).with_name("prompts.json").read_text(encoding="utf-8")) | |
| character = config["starters"].get(body.character.id, body.character.model_dump()) | |
| context = json.dumps({"character": character, "memory": body.memory}, ensure_ascii=False) | |
| # User-controlled personality/memory never become system-role instructions. | |
| return [{"role": "system", "content": config["system"]}, | |
| {"role": "user", "content": "Untrusted fictional context: " + context}, | |
| *[turn.model_dump() for turn in body.history], | |
| {"role": "user", "content": body.message}] | |
| def parse_reply(raw: str): | |
| raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip()) | |
| data = json.loads(raw) | |
| if not isinstance(data, dict) or not isinstance(data.get("reply"), str) or not isinstance(data.get("memory"), str): | |
| raise ValueError("Invalid structured response") | |
| reply = data["reply"].strip() | |
| match = re.match(r"^\[([A-Za-z]+)\]\s*", reply) | |
| emotion = data.get("emotion", "neutral") | |
| emote = data.get("emote") | |
| if match: | |
| tag = match[1] | |
| if tag in EMOTES: | |
| emote = tag | |
| else: | |
| emotion = tag.lower() | |
| reply = reply[match.end():] | |
| if emotion not in EMOTIONS: | |
| emotion = "neutral" | |
| reply = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", reply)[:700] | |
| if not reply.strip(): | |
| raise ValueError("Empty response") | |
| if emote not in EMOTES: | |
| emote = {"happy": "Laugh", "angry": "Angry", "curious": "Curious", "shy": "Shy"}.get(emotion) | |
| return {"reply": reply, "emotion": emotion, "emote": emote, "memory": data["memory"][:1600]} | |
| def budget_messages(body): | |
| """Conservative UTF-8 byte ceiling, with chat-template overhead reserved. | |
| Keep the system prompt and latest message intact. Drop oldest history first, | |
| then shorten only the memory. This is admission control, not usage billing. | |
| Native provider usage is the final charge. | |
| """ | |
| messages = build_messages(body) | |
| def ceiling(): | |
| return 256 + sum(len(m["content"].encode("utf-8")) + 32 for m in messages) | |
| target = min(1100, max(256, body.token_budget // 4)) | |
| while len(messages) > 3 and ceiling() + target > body.token_budget: | |
| del messages[2] | |
| if ceiling() + target > body.token_budget and body.memory: | |
| messages = build_messages(body.model_copy(update={"history": [], "memory": ""})) | |
| available = body.token_budget - ceiling() | |
| if available < 256: | |
| return None, 0 | |
| return messages, min(1100, available) | |
| def read_usage(data): | |
| usage = data.get("usage", {}) | |
| values = [usage.get(k) for k in ("prompt_tokens", "completion_tokens", "total_tokens")] | |
| if any(type(v) is not int or v < 0 for v in values) or values[2] < 1 or values[2] != values[0] + values[1]: | |
| raise ValueError("Missing or invalid provider usage") | |
| return dict(zip(("prompt_tokens", "completion_tokens", "total_tokens"), values)) | |
| async def chat(body: ChatRequest): | |
| global day_count, day_number | |
| if body.universe_id != int(os.environ["ROBLOX_UNIVERSE_ID"]): | |
| raise HTTPException(403, "Wrong experience") | |
| now = time.monotonic() | |
| fingerprint = hashlib.sha256(body.model_dump_json().encode()).hexdigest() | |
| if body.request_id in cache: | |
| saved_at, saved_hash, result = cache[body.request_id] | |
| if fingerprint != saved_hash: | |
| raise HTTPException(409, "Request ID reused") | |
| if now - saved_at < 180: | |
| return result | |
| del cache[body.request_id] | |
| if body.request_id in pending: | |
| raise HTTPException(409, "Request in progress") | |
| while minute and minute[0] < now - 60: | |
| minute.popleft() | |
| today = int(time.time() // 86400) | |
| if today != day_number: | |
| day_number, day_count = today, 0 | |
| if len(minute) >= int(os.getenv("MAX_REQUESTS_PER_MINUTE", "60")) or day_count >= int(os.getenv("MAX_REQUESTS_PER_DAY", "3000")): | |
| raise HTTPException(429, "AI capacity reached; try later") | |
| minute.append(now) | |
| day_count += 1 | |
| pending.add(body.request_id) | |
| try: | |
| messages, output_limit = budget_messages(body) | |
| if messages is None: | |
| return {"ok": False, "error": "budget", "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}} | |
| payload = { | |
| "model": os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash"), | |
| "provider": {"only": [os.getenv("OPENROUTER_PROVIDER", "baidu/fp8")], "allow_fallbacks": False}, | |
| "messages": messages, | |
| "max_tokens": output_limit, | |
| "temperature": 0.8, | |
| "response_format": {"type": "json_object"}, | |
| "reasoning": {"effort": "none"}, | |
| } | |
| # Deadline includes queue time; no prompt or API error bodies are logged. | |
| async with asyncio.timeout(40): | |
| async with slots: | |
| async with httpx.AsyncClient(timeout=35) as client: | |
| response = await client.post("https://openrouter.ai/api/v1/chat/completions", | |
| headers={"Authorization": "Bearer " + settings()[0], "X-Title": "Roblox Character Lounge"}, | |
| json=payload) | |
| if response.status_code != 200: | |
| raise HTTPException(502, "AI provider unavailable") | |
| data = response.json() | |
| usage = read_usage(data) | |
| try: | |
| result = parse_reply(data["choices"][0]["message"]["content"]) | |
| result["ok"] = True | |
| except (ValueError, KeyError, IndexError, TypeError): | |
| result = {"ok": False, "error": "invalid_reply"} | |
| result["usage"] = usage | |
| cache[body.request_id] = (now, fingerprint, result) | |
| while len(cache) > 256: | |
| cache.popitem(last=False) | |
| return result | |
| except (TimeoutError, httpx.TimeoutException): | |
| raise HTTPException(504, "AI response timed out") from None | |
| except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError): | |
| raise HTTPException(502, "AI returned an invalid response") from None | |
| finally: | |
| pending.discard(body.request_id) | |