"""OpenAI-compatible HTTP server for WebBrain-LingLoop-8B-A1.3B CUDA runtime.""" from __future__ import annotations import argparse import json import os import re import threading import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any, Dict, List, Optional os.environ["HF_HUB_DISABLE_XET"] = "1" import torch from transformers import AutoTokenizer from .modeling_lingloop_cuda import LingLoopCache, LingLoopCudaModel _TOOL_CALL_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) _ARG_PAIR_RE = re.compile(r"(.*?)\s*(.*?)", re.DOTALL) def _normalize_messages_for_bailing(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Ensure tool_call.arguments are dicts (required by Bailing V3 chat_template.jinja).""" out = [] for m in messages: mc = dict(m) if mc.get("role") == "assistant" and isinstance(mc.get("tool_calls"), list): new_tcs = [] for tc in mc["tool_calls"]: tcc = dict(tc) fn = dict(tcc.get("function", {}) or {}) args = fn.get("arguments", {}) if isinstance(args, str): try: parsed = json.loads(args) if isinstance(parsed, dict): fn["arguments"] = parsed except Exception: fn["arguments"] = {"raw": args} tcc["function"] = fn new_tcs.append(tcc) mc["tool_calls"] = new_tcs out.append(mc) return out def _coerce_arg_val(v: str) -> Any: vs = v.strip() if vs in ("true", "True"): return True if vs in ("false", "False"): return False if vs in ("null", "None"): return None if (vs.startswith("{") and vs.endswith("}")) or (vs.startswith("[") and vs.endswith("]")): try: return json.loads(vs) except Exception: pass try: if "." in vs: return float(vs) return int(vs) except Exception: return vs def parse_bailing_output(raw_text: str) -> Dict[str, Any]: """Extract optional ..., ..., and clean content.""" text = raw_text for tok in ("<|role_end|>", "<|endoftext|>", "<|end_of_text|>"): if tok in text: text = text.split(tok, 1)[0] reasoning = "" m_th = re.search(r"(.*?)", text, re.DOTALL) if m_th: reasoning = m_th.group(1).strip() text = text[m_th.end() :] elif "" in text: before, after = text.split("", 1) reasoning = before.replace("", "").strip() text = after elif "" in text: # Unclosed — ran out of tokens inside thinking block reasoning = text.split("", 1)[1].strip() text = "" tool_calls = [] cleaned_chunks = [] last_idx = 0 for idx, m in enumerate(_TOOL_CALL_RE.finditer(text)): cleaned_chunks.append(text[last_idx : m.start()]) last_idx = m.end() body = m.group(1).strip() parsed_tc = None if body.startswith("{"): try: obj = json.loads(body) if isinstance(obj, dict) and "name" in obj: parsed_tc = { "id": f"call_{uuid.uuid4().hex[:8]}", "type": "function", "function": { "name": str(obj["name"]), "arguments": json.dumps(obj.get("arguments", {}), ensure_ascii=False), }, } except Exception: parsed_tc = None if parsed_tc is None: # Native Bailing XML format: function_name\nk\nv lines = body.split("", 1) fn_name = lines[0].strip().splitlines()[0].strip() if lines[0].strip() else "" args_dict: Dict[str, Any] = {} for km in _ARG_PAIR_RE.finditer(body): args_dict[km.group(1).strip()] = _coerce_arg_val(km.group(2)) if fn_name: parsed_tc = { "id": f"call_{uuid.uuid4().hex[:8]}", "type": "function", "function": { "name": fn_name, "arguments": json.dumps(args_dict, ensure_ascii=False), }, } if parsed_tc is not None: tool_calls.append(parsed_tc) cleaned_chunks.append(text[last_idx:]) content = re.sub(r"", "", "".join(cleaned_chunks)).strip() return { "content": content if (content or not tool_calls) else None, "reasoning_content": reasoning or None, "tool_calls": tool_calls or None, } class EngineState: def __init__(self, args: argparse.Namespace): self.lock = threading.Lock() self.meta_dir = args.meta_dir self.tok = AutoTokenizer.from_pretrained(args.meta_dir, trust_remote_code=True) self.model = LingLoopCudaModel.from_gguf( args.model_gguf, str(Path(args.meta_dir) / "config.json"), device=torch.device("cuda:0") ) self.cache = LingLoopCache(self.model.cfg, self.model.device, max_seq=8192) self.model_id = args.model_name self.adapter_path = args.adapter self.scale = args.scale self.tool_gated = args.tool_gated self.tool_scale = args.tool_scale if args.tool_gated else None if args.adapter: info = self.model.apply_wsp_adapter(args.adapter, scale=args.scale, tool_scale=self.tool_scale) print(f"[server] loaded adapter {args.adapter} scale={args.scale} info={info}") else: print(f"[server] loaded standalone model {args.model_gguf}") self.stop_ids = [self.model.cfg.eos_token_id] for st in ("<|role_end|>", "<|endoftext|>", "<|end_of_text|>"): tid = self.tok.convert_tokens_to_ids(st) if isinstance(tid, int) and tid >= 0 and tid not in self.stop_ids: self.stop_ids.append(tid) def make_handler(state: EngineState): class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, format: str, *args: Any) -> None: return def _send_json(self, code: int, payload: Dict[str, Any]) -> None: raw = json.dumps(payload, ensure_ascii=False).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(raw))) self.end_headers() self.wfile.write(raw) def do_GET(self) -> None: if self.path == "/health": self._send_json(200, {"status": "ok", "model": state.model_id, "scale": state.scale}) return if self.path == "/v1/models": self._send_json(200, {"object": "list", "data": [{"id": state.model_id, "object": "model"}]}) return self._send_json(404, {"error": "not found"}) def do_POST(self) -> None: length = int(self.headers.get("Content-Length", "0")) body = json.loads(self.rfile.read(length).decode("utf-8")) if length > 0 else {} if self.path == "/admin/set_adapter": with state.lock: adp = body.get("adapter") sc = float(body.get("scale", 1.0)) tg = bool(body.get("tool_gated", False)) tsc = float(body.get("tool_scale", sc)) if tg else None if not adp or sc == 0.0: state.model.clear_wsp_adapter() state.adapter_path = None state.scale = 0.0 info = {"cleared": True} else: info = state.model.apply_wsp_adapter(adp, scale=sc, tool_scale=tsc) state.adapter_path = adp state.scale = sc state.tool_gated = tg state.tool_scale = tsc self._send_json(200, {"ok": True, "scale": state.scale, "info": info}) return if self.path != "/v1/chat/completions": self._send_json(404, {"error": f"unsupported path {self.path}"}) return messages = _normalize_messages_for_bailing(body.get("messages", [])) tools = body.get("tools") temp = float(body.get("temperature", 0.0)) top_p = float(body.get("top_p", 1.0)) max_tokens = int(body.get("max_tokens", 1024)) ct_kwargs = body.get("chat_template_kwargs") or {} enable_thinking = ct_kwargs.get("enable_thinking", body.get("enable_thinking", False)) if enable_thinking is None: enable_thinking = False prompt_text = state.tok.apply_chat_template( messages, tools=tools if tools else None, tokenize=False, add_generation_prompt=True, enable_thinking=bool(enable_thinking), ) prompt_ids = state.tok.encode(prompt_text, add_special_tokens=False) t0 = time.perf_counter() with state.lock: gen_ids, tok_s = state.model.generate( prompt_ids, max_new_tokens=max_tokens, temperature=temp, top_p=top_p, stop_token_ids=state.stop_ids, active_tool_mode=bool(tools), cache=state.cache, ) elapsed = time.perf_counter() - t0 raw_out = state.tok.decode(gen_ids, skip_special_tokens=False) parsed = parse_bailing_output(raw_out) # In thinking mode, when generation was stopped at max_tokens without , keep raw text fallback if content empty msg: Dict[str, Any] = {"role": "assistant", "content": parsed["content"] or ""} if parsed["reasoning_content"] is not None: msg["reasoning_content"] = parsed["reasoning_content"] if parsed["tool_calls"] is not None: msg["tool_calls"] = parsed["tool_calls"] if parsed["content"] is None: msg["content"] = "" finish_reason = "tool_calls" if parsed["tool_calls"] else ("length" if len(gen_ids) >= max_tokens else "stop") resp = { "id": f"chatcmpl-{uuid.uuid4().hex[:12]}", "object": "chat.completion", "created": int(time.time()), "model": state.model_id, "choices": [{"index": 0, "message": msg, "finish_reason": finish_reason}], "usage": { "prompt_tokens": len(prompt_ids), "completion_tokens": len(gen_ids), "total_tokens": len(prompt_ids) + len(gen_ids), "completion_tok_s": round(tok_s, 2), "elapsed_s": round(elapsed, 3), }, } self._send_json(200, resp) return Handler def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model-gguf", required=True) ap.add_argument("--meta-dir", required=True) ap.add_argument("--model-name", default="WebBrain-LingLoop-8B-A1.3B") ap.add_argument("--adapter", default=None) ap.add_argument("--scale", type=float, default=1.0) ap.add_argument("--tool-gated", action="store_true") ap.add_argument("--tool-scale", type=float, default=1.0) ap.add_argument("--port", type=int, default=8145) ap.add_argument("--host", default="127.0.0.1") args = ap.parse_args() state = EngineState(args) srv = ThreadingHTTPServer((args.host, args.port), make_handler(state)) print(f"[server] listening on http://{args.host}:{args.port} (VRAM={torch.cuda.memory_allocated() / 1024**3:.3f} GiB)") srv.serve_forever() if __name__ == "__main__": main()