"""Standalone single-file /v1beta/decisions logprob server for Hugging Face quickstarts. Translates multimodal Decisions API requests (choice, noul, score) into max_tokens=1 top_logprobs calls against OpenAI-compatible vLLM or llama.cpp servers with temperature calibration and shared-prefix caching. """ from __future__ import annotations import argparse import asyncio import base64 import io import json import math import os import string from pathlib import Path from typing import Any, Literal import httpx import uvicorn from fastapi import FastAPI, HTTPException from PIL import Image from pydantic import BaseModel, Field SYSTEM_PROMPT_CHOICE = ( "You are a precise decision engine. Evaluate the input against the criteria " "and output ONLY the single option letter. Do not explain." ) SYSTEM_PROMPT_NOUL = ( "You are a precise decision engine. Evaluate whether the statement is true " "for the input. Output ONLY Yes or No." ) SYSTEM_PROMPT_SCORE = ( "You are a precise decision engine. Rate the input using the ordered rubric " "and output ONLY the single integer score." ) SYSTEM_PROMPT_BUNDLED = ( "You are a precise decision engine. Follow the task instructions exactly and " "output ONLY the single requested decision token (letter, Yes/No, or digit)." ) OPTION_LETTERS = string.ascii_uppercase FLOOR_LOGPROB = -20.0 INKLING_CONTROL_TOKENS = frozenset( { "<|message_model|>", "<|content_text|>", "<|content_thinking|>", "<|end_message|>", "<|content_model_end_sampling|>", } ) class InputBlock(BaseModel): """Single multimodal input block (text or base64-encoded image).""" type: Literal["text", "image"] text: str | None = None data: str | None = None mime_type: str | None = None class QuestionSpec(BaseModel): """Single decision inquiry specification.""" type: Literal["choice", "noul", "score"] instructions: str criteria: dict[str, str] | list[str] | None = None class DecisionRequest(BaseModel): """Incoming /v1beta/decisions request payload.""" model: str | None = None input: list[InputBlock] questions: dict[str, QuestionSpec] class DecisionUsagePayload(BaseModel): """Token usage summary returned in the Decisions API response.""" total_input_tokens: int = 0 total_output_tokens: int = 0 total_tokens: int = 0 class DecisionApiResponse(BaseModel): """Calibrated /v1beta/decisions response payload.""" model: str answers: dict[str, dict[str, Any]] = Field(default_factory=dict) usage: DecisionUsagePayload = Field(default_factory=DecisionUsagePayload) def default_chat_template_kwargs(model_name: str) -> dict[str, Any]: """Return model-appropriate chat_template_kwargs to suppress multi-token thinking.""" if "inkling" in model_name.lower(): return {"reasoning_effort": "none"} return {"enable_thinking": False} class CalibrationConfig(BaseModel): """Post-hoc temperature scaling and optional prior bias parameters.""" temperature_choice: float = 1.0 temperature_noul: float = 1.0 temperature_score: float = 1.0 noul_yes_bias: float = 0.0 choice_prior_biases: dict[str, float] = Field(default_factory=dict) @classmethod def from_json(cls, path: Path | None) -> CalibrationConfig: """Load calibration parameters from JSON file if it exists.""" if path is None or not path.exists(): return cls() with open(path, encoding="utf-8") as handle: data = json.load(handle) return cls.model_validate(data) def logsumexp(values: list[float]) -> float: """Compute numerically stable log-sum-exp.""" if not values: return FLOOR_LOGPROB peak = max(values) return peak + math.log(sum(math.exp(val - peak) for val in values)) def softmax_dict(logits: dict[str, float], temperature: float = 1.0) -> dict[str, float]: """Compute temperature-scaled softmax over a mapping of label -> logit.""" if not logits: return {} temp = max(temperature, 1e-4) scaled = {k: v / temp for k, v in logits.items()} max_val = max(scaled.values()) exps = {k: math.exp(v - max_val) for k, v in scaled.items()} total = sum(exps.values()) if total <= 0.0: uniform = 1.0 / len(logits) return {k: round(uniform, 6) for k in logits} return {k: round(v / total, 6) for k, v in exps.items()} def _compact_image_b64(b64_data: str, mime: str, max_side: int | None) -> tuple[str, str]: """Downscale oversized images to compact JPEG to cut vision prefill latency.""" if max_side is None or max_side <= 0: return b64_data, mime try: raw = base64.b64decode(b64_data) with Image.open(io.BytesIO(raw)) as img: if max(img.size) <= max_side and mime == "image/jpeg": return b64_data, mime rgb = img.convert("RGB") rgb.thumbnail((max_side, max_side), Image.Resampling.LANCZOS) buf = io.BytesIO() rgb.save(buf, format="JPEG", quality=88) return base64.b64encode(buf.getvalue()).decode("utf-8"), "image/jpeg" except Exception: return b64_data, mime def build_shared_user_prefix( input_blocks: list[InputBlock], max_image_side: int | None = 1024, ) -> list[dict[str, Any]]: """Build OpenAI-compatible multimodal content parts ordered for prefix cache hits.""" parts: list[dict[str, Any]] = [] for block in input_blocks: if block.type == "image" and block.data: mime = block.mime_type or "image/jpeg" compact_b64, compact_mime = _compact_image_b64(block.data, mime, max_image_side) parts.append( { "type": "image_url", "image_url": {"url": f"data:{compact_mime};base64,{compact_b64}"}, } ) elif block.type == "text" and block.text: parts.append({"type": "text", "text": block.text}) return parts def format_question_prompt(spec: QuestionSpec) -> tuple[str, dict[str, str]]: """Format a QuestionSpec into a single-token prompt suffix and token->label map.""" if spec.type == "noul": prompt = ( f"\n\nPredicate: {spec.instructions}\n\nRespond with a single word: Yes or No.\nAnswer:" ) return prompt, {"Yes": "Yes", "No": "No"} if spec.type == "choice": if not isinstance(spec.criteria, dict) or not spec.criteria: raise ValueError("choice question requires non-empty dict criteria") if len(spec.criteria) > len(OPTION_LETTERS): raise ValueError( f"choice question has {len(spec.criteria)} options; max single-token is 26" ) token_to_key: dict[str, str] = {} option_lines: list[str] = [] for idx, (key, desc) in enumerate(spec.criteria.items()): letter = OPTION_LETTERS[idx] token_to_key[letter] = key option_lines.append(f"{letter}: {desc}") last_letter = OPTION_LETTERS[len(spec.criteria) - 1] options_block = "\n".join(option_lines) prompt = ( f"\n\nTask: {spec.instructions}\n\n" f"Options:\n{options_block}\n\n" f"Answer (single letter A-{last_letter}):" ) return prompt, token_to_key if spec.type == "score": if not isinstance(spec.criteria, list) or not spec.criteria: raise ValueError("score question requires non-empty list criteria") if len(spec.criteria) > 10: raise ValueError("score question supports at most 10 ordered levels (0-9)") token_to_key = {} rubric_lines: list[str] = [] for idx, label in enumerate(spec.criteria): digit = str(idx) token_to_key[digit] = label rubric_lines.append(f"{digit}: {label}") max_digit = len(spec.criteria) - 1 rubric_block = "\n".join(rubric_lines) prompt = ( f"\n\nTask: {spec.instructions}\n\n" f"Rubric:\n{rubric_block}\n\n" f"Answer (single digit 0-{max_digit}):" ) return prompt, token_to_key raise ValueError(f"Unsupported question type: {spec.type}") def extract_top_logprobs(response_json: dict[str, Any]) -> dict[str, float]: """Extract decision-token {token_str: logprob} map from an OpenAI completion response.""" choices = response_json.get("choices") or [] if not choices: return {} choice0 = choices[0] logprobs_obj = choice0.get("logprobs") or {} content_items = logprobs_obj.get("content") or [] if content_items: target_item = content_items[0] for item in content_items: emitted = (item.get("token") or "").strip() if emitted not in INKLING_CONTROL_TOKENS: target_item = item break top_items = target_item.get("top_logprobs") or [] result: dict[str, float] = {} for item in top_items: tok = item.get("token") lp = item.get("logprob") if isinstance(tok, str) and isinstance(lp, (int, float)): if tok not in result or lp > result[tok]: result[tok] = float(lp) if result: return result msg = choice0.get("message") or {} text = (msg.get("content") or "").strip() if text: return {text: 0.0} return {} def aggregate_candidate_logits( raw_logprobs: dict[str, float], candidates: list[str], case_insensitive: bool = True, ) -> dict[str, float]: """Aggregate token logprobs across whitespace/case variants for each candidate token.""" min_seen = min(raw_logprobs.values()) - 2.0 if raw_logprobs else FLOOR_LOGPROB default_lp = max(FLOOR_LOGPROB, min_seen) grouped: dict[str, list[float]] = {c: [] for c in candidates} lookup = {c.lower() if case_insensitive else c: c for c in candidates} for tok, lp in raw_logprobs.items(): cleaned = tok.strip() if not cleaned: continue key = cleaned.lower() if case_insensitive else cleaned if key in lookup: grouped[lookup[key]].append(lp) return {c: (logsumexp(lps) if lps else default_lp) for c, lps in grouped.items()} class DecisionsLogprobEngine: """Evaluates Decisions API requests via single-token logprobs on vLLM or llama.cpp.""" def __init__( self, vllm_base_url: str = "http://localhost:8100", default_model: str = "system-1.5-v2", calibration: CalibrationConfig | None = None, top_logprobs: int = 20, timeout: float = 60.0, max_image_side: int | None = 1024, chat_template_kwargs: dict[str, Any] | None = None, max_tokens: int = 1, http_client: httpx.AsyncClient | None = None, ) -> None: self.vllm_base_url = vllm_base_url.rstrip("/") self.default_model = default_model self.calibration = calibration or CalibrationConfig() self.top_logprobs = top_logprobs self.timeout = timeout self.max_image_side = max_image_side self.chat_template_kwargs = ( dict(chat_template_kwargs) if chat_template_kwargs is not None else None ) self.max_tokens = max(1, max_tokens) self._external_client = http_client self._pooled_client: httpx.AsyncClient | None = None def _get_client(self) -> httpx.AsyncClient: """Return an injected client or a persistent keep-alive HTTP client.""" if self._external_client is not None: return self._external_client if self._pooled_client is None or self._pooled_client.is_closed: limits = httpx.Limits(max_connections=64, max_keepalive_connections=32) self._pooled_client = httpx.AsyncClient(timeout=self.timeout, limits=limits) return self._pooled_client def _resolve_model(self, requested_model: str | None) -> str: """Resolve requested model ID, falling back to configured default_model.""" if not requested_model: return self.default_model return requested_model def _score_question_from_logprobs( self, spec: QuestionSpec, token_to_key: dict[str, str], raw_logprobs: dict[str, float], ) -> dict[str, Any]: """Convert raw top_logprobs into a calibrated Decisions API answer payload.""" candidates = list(token_to_key.keys()) if spec.type == "noul": logits = aggregate_candidate_logits(raw_logprobs, ["Yes", "No"], case_insensitive=True) logits["Yes"] -= self.calibration.noul_yes_bias probs = softmax_dict(logits, temperature=self.calibration.temperature_noul) p_yes = probs["Yes"] return { "type": "noul", "noul": p_yes, "confidence": round(max(p_yes, 1.0 - p_yes), 6), } if spec.type == "choice": logits = aggregate_candidate_logits(raw_logprobs, candidates, case_insensitive=False) lower_logits = aggregate_candidate_logits( raw_logprobs, candidates, case_insensitive=True ) for cand in candidates: if logits[cand] <= FLOOR_LOGPROB + 1e-6 and lower_logits[cand] > logits[cand]: logits[cand] = lower_logits[cand] logits[cand] -= self.calibration.choice_prior_biases.get(cand, 0.0) letter_probs = softmax_dict(logits, temperature=self.calibration.temperature_choice) named_probs = {token_to_key[letter]: prob for letter, prob in letter_probs.items()} best_key = max(named_probs, key=lambda k: named_probs[k]) return { "type": "choice", "choice": best_key, "probabilities": named_probs, "confidence": named_probs[best_key], } if spec.type == "score": logits = aggregate_candidate_logits(raw_logprobs, candidates, case_insensitive=False) digit_probs = softmax_dict(logits, temperature=self.calibration.temperature_score) expected_score = sum(int(d) * p for d, p in digit_probs.items()) confidence = max(digit_probs.values()) if digit_probs else 0.0 return { "type": "score", "score": round(expected_score, 4), "confidence": round(confidence, 6), "probabilities": digit_probs, "legend": token_to_key, } raise ValueError(f"Unsupported question type: {spec.type}") async def _query_single_question( self, client: httpx.AsyncClient, model: str, system_prompt: str, shared_prefix: list[dict[str, Any]], spec: QuestionSpec, ) -> tuple[dict[str, Any], int, int]: """Execute one max_tokens=1 logprobs chat completion against backend server.""" q_suffix, token_to_key = format_question_prompt(spec) user_content = [*shared_prefix, {"type": "text", "text": q_suffix}] template_kwargs = ( self.chat_template_kwargs if self.chat_template_kwargs is not None else default_chat_template_kwargs(model) ) payload: dict[str, Any] = { "model": model, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}, ], "max_tokens": self.max_tokens, "temperature": 0.0, "logprobs": True, "top_logprobs": self.top_logprobs, "chat_template_kwargs": template_kwargs, } if "reasoning_effort" in template_kwargs: payload["reasoning_effort"] = template_kwargs["reasoning_effort"] resp = await client.post( f"{self.vllm_base_url}/v1/chat/completions", json=payload, ) resp.raise_for_status() data = resp.json() raw_logprobs = extract_top_logprobs(data) answer = self._score_question_from_logprobs(spec, token_to_key, raw_logprobs) usage = data.get("usage") or {} prompt_tokens = int(usage.get("prompt_tokens", 0)) completion_tokens = int(usage.get("completion_tokens", 0)) return answer, prompt_tokens, completion_tokens async def evaluate(self, request: DecisionRequest) -> DecisionApiResponse: """Evaluate all bundled questions with prefix-cache-aware concurrent dispatch.""" model = self._resolve_model(request.model) shared_prefix = build_shared_user_prefix(request.input, max_image_side=self.max_image_side) items = list(request.questions.items()) if not items: return DecisionApiResponse(model=model, answers={}, usage=DecisionUsagePayload()) if len(items) == 1: q_type = items[0][1].type system_prompt = { "choice": SYSTEM_PROMPT_CHOICE, "noul": SYSTEM_PROMPT_NOUL, "score": SYSTEM_PROMPT_SCORE, }[q_type] else: system_prompt = SYSTEM_PROMPT_BUNDLED client = self._get_client() answers: dict[str, dict[str, Any]] = {} total_in = 0 total_out = 0 first_name, first_spec = items[0] first_ans, in_tok, out_tok = await self._query_single_question( client, model, system_prompt, shared_prefix, first_spec ) answers[first_name] = first_ans total_in += in_tok total_out += out_tok if len(items) > 1: rest_tasks = [ self._query_single_question(client, model, system_prompt, shared_prefix, spec) for _, spec in items[1:] ] rest_results = await asyncio.gather(*rest_tasks) for (q_name, _), (ans, q_in, q_out) in zip(items[1:], rest_results, strict=True): answers[q_name] = ans total_in += q_in total_out += q_out return DecisionApiResponse( model=model, answers=answers, usage=DecisionUsagePayload( total_input_tokens=total_in, total_output_tokens=total_out, total_tokens=total_in + total_out, ), ) async def check_health(self) -> dict[str, Any]: """Check upstream inference backend readiness and list available models.""" client = self._get_client() resp = await client.get(f"{self.vllm_base_url}/v1/models", timeout=5.0) resp.raise_for_status() models_data = resp.json().get("data", []) model_ids = [m.get("id") for m in models_data if isinstance(m, dict)] return { "status": "ok", "backend_url": self.vllm_base_url, "default_model": self.default_model, "available_models": model_ids, "calibration": self.calibration.model_dump(), } def _parse_optional_json_dict(raw: str | None) -> dict[str, Any] | None: """Parse an optional JSON object string from env var or CLI flag.""" if not raw or not raw.strip(): return None parsed = json.loads(raw) if not isinstance(parsed, dict): raise ValueError("Expected a JSON object for chat_template_kwargs") return parsed def create_app(engine: DecisionsLogprobEngine | None = None) -> FastAPI: """Build the FastAPI /v1beta/decisions application.""" if engine is None: backend_url = os.environ.get("VLLM_BASE_URL", "http://localhost:8100") default_model = os.environ.get("DECISIONS_MODEL", "system-1.5-v2") cal_path_raw = os.environ.get("DECISIONS_CALIBRATION_PATH") calibration = CalibrationConfig.from_json( Path(cal_path_raw) if cal_path_raw and cal_path_raw.strip() else None ) chat_kwargs = _parse_optional_json_dict(os.environ.get("DECISIONS_CHAT_TEMPLATE_KWARGS")) max_tokens = int(os.environ.get("DECISIONS_MAX_TOKENS", "1")) max_image_side_raw = os.environ.get("DECISIONS_MAX_IMAGE_SIDE") max_image_side = ( int(max_image_side_raw) if max_image_side_raw and max_image_side_raw.strip() else 1024 ) engine = DecisionsLogprobEngine( vllm_base_url=backend_url, default_model=default_model, calibration=calibration, chat_template_kwargs=chat_kwargs, max_tokens=max_tokens, max_image_side=max_image_side, ) application = FastAPI( title="Decisions Logprob Server", description="Self-hosted /v1beta/decisions API backed by single-token logprobs.", version="0.2.0", ) application.state.engine = engine @application.get("/health") async def health() -> dict[str, Any]: try: return await application.state.engine.check_health() except httpx.HTTPError as exc: raise HTTPException( status_code=503, detail=f"Upstream inference server unavailable: {exc}", ) from exc @application.post("/v1beta/decisions", response_model=DecisionApiResponse) async def evaluate_decisions(request: DecisionRequest) -> DecisionApiResponse: try: return await application.state.engine.evaluate(request) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except httpx.HTTPStatusError as exc: raise HTTPException( status_code=exc.response.status_code, detail=f"Upstream backend error: {exc.response.text[:300]}", ) from exc except httpx.HTTPError as exc: raise HTTPException( status_code=502, detail=f"Upstream backend unreachable: {exc}", ) from exc return application app = create_app() def main() -> None: """CLI entrypoint for launching the standalone /v1beta/decisions server.""" parser = argparse.ArgumentParser( description="Run the standalone /v1beta/decisions FastAPI logprob server.", ) parser.add_argument("--host", default="0.0.0.0") parser.add_argument("--port", type=int, default=8101) parser.add_argument("--vllm-url", default="http://localhost:8100") parser.add_argument("--model", default="system-1.5-v2") parser.add_argument("--calibration", type=Path, default=None) parser.add_argument("--chat-template-kwargs", default=None) parser.add_argument("--max-tokens", type=int, default=1) parser.add_argument("--max-image-side", type=int, default=None) args = parser.parse_args() cal_raw = ( str(args.calibration) if args.calibration else os.environ.get("DECISIONS_CALIBRATION_PATH") ) cal_path = Path(cal_raw) if cal_raw and cal_raw.strip() else None calibration = CalibrationConfig.from_json(cal_path) chat_kwargs = _parse_optional_json_dict( args.chat_template_kwargs or os.environ.get("DECISIONS_CHAT_TEMPLATE_KWARGS") ) max_img_raw = ( args.max_image_side if args.max_image_side is not None else os.environ.get("DECISIONS_MAX_IMAGE_SIDE") ) max_image_side = int(max_img_raw) if max_img_raw else 1024 engine = DecisionsLogprobEngine( vllm_base_url=args.vllm_url, default_model=args.model, calibration=calibration, chat_template_kwargs=chat_kwargs, max_tokens=args.max_tokens, max_image_side=max_image_side, ) uvicorn.run(create_app(engine), host=args.host, port=args.port) if __name__ == "__main__": main()