File size: 12,434 Bytes
e8a992b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""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"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
_ARG_PAIR_RE = re.compile(r"<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>", 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 <think>...</think>, <tool_call>...</tool_call>, 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"<think>(.*?)</think>", text, re.DOTALL)
    if m_th:
        reasoning = m_th.group(1).strip()
        text = text[m_th.end() :]
    elif "</think>" in text:
        before, after = text.split("</think>", 1)
        reasoning = before.replace("<think>", "").strip()
        text = after
    elif "<think>" in text:
        # Unclosed <think> — ran out of tokens inside thinking block
        reasoning = text.split("<think>", 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\n<arg_key>k</arg_key>\n<arg_value>v</arg_value>
            lines = body.split("<arg_key>", 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"</?think>", "", "".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 </think>, 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()