File size: 12,670 Bytes
fcf8a90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""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()
# Provider fallback: the PROVIDER_COUNT cheapest OpenRouter endpoints for the configured model,
# tried in order (cheapest first). If one is down, OpenRouter moves to the next one.
PROVIDER_COUNT = 3
PROVIDER_REFRESH_SECONDS = 1800
providers_state = {"list": [], "at": 0.0, "model": ""}
providers_lock = asyncio.Lock()


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 model_name():
    return os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash")


def fallback_providers():
    # Used only if OpenRouter's endpoint list can't be read (cheapest 3 as of the last update).
    raw = os.getenv("OPENROUTER_PROVIDERS", "open-inference/fp4,decart/fp4,morph/fp8")
    return [p.strip() for p in raw.split(",") if p.strip()][:PROVIDER_COUNT]


def blended_price(endpoint):
    # Chats send more prompt tokens than they get back, so weight input price (default 3:1).
    pricing = endpoint.get("pricing") or {}
    weight = float(os.getenv("PRICE_INPUT_WEIGHT", "3"))
    return (float(pricing.get("prompt", "inf")) * weight + float(pricing.get("completion", "inf"))) / (weight + 1)


async def cheapest_providers(client):
    """The cheapest working endpoints for the model, one per provider company, cached 30 min."""
    model = model_name()
    if providers_state["list"] and providers_state["model"] == model and time.monotonic() - providers_state["at"] < PROVIDER_REFRESH_SECONDS:
        return providers_state["list"]
    async with providers_lock:
        now = time.monotonic()
        if providers_state["list"] and providers_state["model"] == model and now - providers_state["at"] < PROVIDER_REFRESH_SECONDS:
            return providers_state["list"]
        try:
            response = await client.get("https://openrouter.ai/api/v1/models/" + model.split(":")[0] + "/endpoints", timeout=8)
            response.raise_for_status()
            endpoints = response.json()["data"]["endpoints"]
            allowed = {q.strip() for q in os.getenv("ALLOWED_QUANTIZATIONS", "").split(",") if q.strip()}
            usable = [e for e in endpoints if isinstance(e, dict) and e.get("tag")
                      and "response_format" in (e.get("supported_parameters") or [])
                      and (not allowed or e.get("quantization") in allowed)]
            healthy = [e for e in usable if e.get("status", 0) == 0]
            pool = sorted(healthy if len(healthy) >= PROVIDER_COUNT else usable, key=blended_price)
            chosen, seen = [], set()
            for endpoint in pool:
                company = endpoint.get("provider_name") or endpoint["tag"].split("/")[0]
                if company in seen:
                    continue
                seen.add(company)
                chosen.append(endpoint["tag"])
                if len(chosen) == PROVIDER_COUNT:
                    break
            if not chosen:
                raise ValueError("No usable providers")
            providers_state.update(list=chosen, at=now, model=model)
        except (httpx.HTTPError, ValueError, KeyError, TypeError):
            # Keep the last good list (or the built-in one) and try again in 2 minutes.
            if not providers_state["list"] or providers_state["model"] != model:
                providers_state.update(list=fallback_providers(), model=model)
            providers_state["at"] = now - PROVIDER_REFRESH_SECONDS + 120
        return providers_state["list"]


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")


@app.middleware("http")
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)


@app.get("/")
async def home():
    return {"service": "CharacterAI Roblox middleware", "health": "/health"}


@app.get("/health")
async def health():
    return {"ok": True, "ready": ready(), "version": "3.1.0", "model": model_name(), "providers": providers_state["list"]}


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))



@app.post("/chat", dependencies=[Depends(authorize)])
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": model_name(),
            "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:
                    # Cheapest first; OpenRouter falls through the list if a provider is down,
                    # and never goes to a provider outside it.
                    payload["provider"] = {"order": await cheapest_providers(client), "allow_fallbacks": False}
                    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)