File size: 15,551 Bytes
6071ec5 | 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 309 310 311 312 313 314 315 316 | """Local web chat for Slayer1B packages (config.json + tokenizer.json + model.safetensors) on the local GPU, built to show
tool calling: the model's raw output streams token by token, every <tool_call> is parsed, executed and its result fed back
(call -> result -> next step), and the page shows each step.
Models: every folder with those three files under release/ or models/ (next to this directory); one model on the GPU at a time.
Tools: the demo tools of tools_suite.py (weather/time/search use a small fixed table; calculator and currency compute).
python chat_server.py [--port 8780] [--model <folder name>]
"""
import argparse
import gc
import json
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import torch
from tokenizers import Tokenizer
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(ROOT))
import slayer_model # noqa: E402
import tools_suite # noqa: E402
from chatfmt import Fmt, parse_calls # noqa: E402
LOCK = threading.Lock()
M = {"name": None}
BLOCK = 4096
WEB = {"name": "web_search", "description": "Search the web. Returns the top results: title, url and a short snippet (e.g. Wikipedia, GitHub, LinkedIn, news pages).",
"parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Search phrase"}}, "required": ["query"]}}
OPEN = {"name": "open_page", "description": "Open a web page by its url and return its title and the beginning of its text.",
"parameters": {"type": "object", "properties": {"url": {"type": "string", "description": "Full http(s) address"}}, "required": ["url"]}}
TOOLS = {**{n: tools_suite.TOOLS[n] for n in tools_suite.TOOLS}, "web_search": WEB, "open_page": OPEN}
TOOL_NAMES = ["web_search", "open_page", "get_weather", "get_time", "calculator", "convert_currency", "search", "send_email"]
DEFAULT_OFF = ["search", "send_email"]
# Honest identification, robots.txt respected for every page fetch, one request per second per host.
# Web search goes through a search API made for programmatic/agent use (key from the environment), not by scraping
# a search engine's HTML pages.
UA = "SlayerLocalChat/0.1 (local research assistant; respects robots.txt)"
ROBOTS, LAST = {}, {}
def allowed(url):
import urllib.parse
import urllib.request
p = urllib.parse.urlparse(url)
base = f"{p.scheme}://{p.netloc}"
if base not in ROBOTS:
try:
from protego import Protego
r = urllib.request.urlopen(urllib.request.Request(base + "/robots.txt", headers={"User-Agent": UA}), timeout=8)
ROBOTS[base] = Protego.parse(r.read(500_000).decode("utf-8", "replace"))
except Exception as e:
code = getattr(e, "code", None)
ROBOTS[base] = "allow" if code in (404, 410) else "deny" # no robots.txt = allowed; unreachable = do not fetch
r = ROBOTS[base]
return r == "allow" or (r != "deny" and r.can_fetch(url, UA))
def _get(url, timeout=10, check_robots=True):
import urllib.parse
import urllib.request
if check_robots and not allowed(url):
raise PermissionError("blocked by robots.txt")
host = urllib.parse.urlparse(url).netloc
wait = LAST.get(host, 0) + 1.0 - time.time()
if wait > 0:
time.sleep(wait)
LAST[host] = time.time()
r = urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "pl,en;q=0.8"}), timeout=timeout)
return r.read(600_000).decode(r.headers.get_content_charset() or "utf-8", "replace"), r.geturl()
def web_search(args):
"""Search API (Brave Search with BRAVE_API_KEY, or Tavily with TAVILY_API_KEY): top 5 as {title, url, domain, snippet}."""
import os
import urllib.parse
import urllib.request
q = str(args.get("query") or "").strip()
if not q:
return {"error": "empty query"}
try:
if os.environ.get("BRAVE_API_KEY"):
req = urllib.request.Request("https://api.search.brave.com/res/v1/web/search?" + urllib.parse.urlencode({"q": q, "count": 5}),
headers={"Accept": "application/json", "X-Subscription-Token": os.environ["BRAVE_API_KEY"], "User-Agent": UA})
res = json.load(urllib.request.urlopen(req, timeout=12)).get("web", {}).get("results", [])
items = [(r.get("title", ""), r.get("url", ""), r.get("description", "")) for r in res]
elif os.environ.get("TAVILY_API_KEY"):
body = json.dumps({"query": q, "max_results": 5}).encode()
req = urllib.request.Request("https://api.tavily.com/search", data=body, headers={"Content-Type": "application/json", "User-Agent": UA,
"Authorization": "Bearer " + os.environ["TAVILY_API_KEY"]})
res = json.load(urllib.request.urlopen(req, timeout=15)).get("results", [])
items = [(r.get("title", ""), r.get("url", ""), r.get("content", "")) for r in res]
else:
return {"error": "web search is not configured: set BRAVE_API_KEY or TAVILY_API_KEY before starting the chat server"}
except Exception as e:
return {"error": f"search API error: {type(e).__name__}: {e}"[:200]}
import re
clean = lambda x: " ".join(re.sub(r"<.*?>", "", x or "").split())
out = [{"title": clean(t)[:120], "url": u, "domain": urllib.parse.urlparse(u).netloc.replace("www.", ""), "snippet": clean(s)[:220]} for t, u, s in items[:5]]
return {"query": q, "results": out} if out else {"query": q, "results": [], "note": "no results"}
def open_page(args):
"""Fetch a page and return title, meta description and the first ~1500 characters of visible text."""
import html as H
import re
u = str(args.get("url") or "").strip()
if not re.match(r"https?://", u):
return {"error": "url must start with http:// or https://"}
# site adapter: a Hugging Face user/organization page keeps its members and repos in embedded JSON, not in page text;
# the public API gives them cleanly (what a person sees on the page, in a form a small model can read)
m = re.match(r"https?://(?:www\.)?huggingface\.co/([A-Za-z0-9_.-]+)/?$", u)
if m and m.group(1) not in ("models", "datasets", "spaces", "docs", "blog", "papers", "pricing", "login", "join"):
name = m.group(1)
try:
mem = json.loads(_get(f"https://huggingface.co/api/organizations/{name}/members", timeout=10)[0])
mods = json.loads(_get(f"https://huggingface.co/api/models?author={name}&limit=8&sort=lastModified", timeout=10)[0])
dss = json.loads(_get(f"https://huggingface.co/api/datasets?author={name}&limit=5&sort=lastModified", timeout=10)[0])
return {"url": u, "title": f"{name} on Hugging Face (organization)",
"members": [f"{x.get('fullname') or x['user']} (@{x['user']})" for x in mem],
"latest_models": [x["id"] for x in mods], "latest_datasets": [x["id"] for x in dss],
"text": f"Members of {name}: " + ", ".join(x.get("fullname") or x["user"] for x in mem)}
except Exception:
pass # not an organization (or API down): fall back to the page
try:
t, final = _get(u, timeout=12)
except Exception as e:
return {"error": f"{type(e).__name__}: {e}"[:200], "url": u}
title = re.search(r"<title[^>]*>(.*?)</title>", t, re.S | re.I)
desc = re.search(r'<meta[^>]+(?:name|property)="(?:og:)?description"[^>]+content="([^"]*)"', t, re.I)
body = re.sub(r"(?is)<(script|style|noscript|svg|header|footer|nav)[^>]*>.*?</\1>", " ", t)
body = " ".join(H.unescape(re.sub(r"(?s)<[^>]+>", " ", body)).split())
return {"url": final, "title": " ".join(H.unescape(title.group(1)).split())[:150] if title else "",
"description": H.unescape(desc.group(1))[:300] if desc else "", "text": body[:1500]}
def execute(name, args):
if name == "web_search":
return web_search(args)
if name == "open_page":
return open_page(args)
return tools_suite.execute(name, args)
def models():
out = {}
for base in (ROOT / "release", ROOT / "models"):
if base.is_dir():
for d in sorted(base.iterdir()):
if all((d / f).exists() for f in ("model.safetensors", "config.json", "tokenizer.json")):
out[d.name] = d
return out
def ensure(name):
if M["name"] == name:
return
path = models()[name]
M.pop("model", None)
gc.collect()
torch.cuda.empty_cache()
M["model"] = slayer_model.Slayer(str(path), device="cuda", dtype=torch.bfloat16)
M["fmt"] = Fmt(Tokenizer.from_file(str(path / "tokenizer.json")))
M["name"] = name
print("loaded", name, flush=True)
def sample(lg, out, temperature, top_p, rep, gen):
if rep != 1.0 and out:
idx = torch.tensor(sorted(set(out)), device=lg.device)
v = lg[idx]
lg = lg.clone()
lg[idx] = torch.where(v > 0, v / rep, v * rep)
if temperature <= 0:
return int(lg.argmax())
p = torch.softmax(lg / temperature, -1)
if top_p < 1.0:
sp, si = torch.sort(p, descending=True)
keep = sp.cumsum(0) - sp <= top_p
p = torch.zeros_like(p).scatter(0, si[keep], sp[keep])
p = p / p.sum()
return int(torch.multinomial(p, 1, generator=gen))
@torch.inference_mode()
def stream_generate(ids, s, emit):
"""Generate one assistant turn, emitting text deltas; returns (text, n_tokens)."""
m, f = M["model"], M["fmt"]
stop = {f.ime, f.bos, f.ims}
cache, out, shown = [], [], ""
lg = m.krok(torch.tensor([ids[-(BLOCK - 1):]], device="cuda"), cache)[0]
gen = torch.Generator(device="cuda").manual_seed(int(s.get("seed", 0)))
for _ in range(int(s.get("max_new", 400))):
t = sample(lg, out, float(s.get("temperature", 0.3)), float(s.get("top_p", 0.9)), float(s.get("rep", 1.1)), gen)
if t in stop or len(ids) + len(out) >= BLOCK - 1:
break
out.append(t)
text = f.tok.decode(out, skip_special_tokens=False)
if not text.endswith("�") and len(text) > len(shown):
emit({"t": "tok", "text": text[len(shown):]})
shown = text
lg = m.krok(torch.tensor([[t]], device="cuda"), cache)[0]
text = f.tok.decode(out, skip_special_tokens=False)
if len(text) > len(shown):
emit({"t": "tok", "text": text[len(shown):]})
return text.strip(), len(out)
def run_chat(req, emit):
s = req.get("settings", {})
f = M["fmt"]
names = [n for n in (s.get("tools") or []) if n in TOOLS]
tools = [TOOLS[n] for n in names] or None
sys_parts = []
if (s.get("user_name") or "").strip():
n = s["user_name"].strip()
sys_parts.append(f"Użytkownik ma na imię {n}. Zwracaj się do niego po imieniu. / The user's name is {n}; address them by name.")
if (s.get("system") or "").strip():
sys_parts.append(s["system"].strip())
msgs = ([{"role": "system", "content": "\n".join(sys_parts)}] if sys_parts else []) + req["messages"]
new_msgs = []
for step in range(5):
ids = f.prompt_ids(msgs + new_msgs, tools)
emit({"t": "step", "step": step, "prompt_tokens": len(ids)})
t0 = time.time()
text, n = stream_generate(ids, s, emit)
emit({"t": "gen_end", "tokens": n, "ms": int((time.time() - t0) * 1000)})
calls, errs = parse_calls(text) if tools else ([], [])
for e in errs:
emit({"t": "parse_error", "msg": e})
if not calls:
new_msgs.append({"role": "assistant", "content": text})
emit({"t": "done", "new_messages": new_msgs, "context_tokens": len(ids) + n})
return
new_msgs.append({"role": "assistant", "content": "", "tool_calls": [{"name": c["name"], "arguments": json.dumps(c["arguments"], ensure_ascii=False)} for c in calls]})
for c in calls:
emit({"t": "call", "name": c["name"], "arguments": c["arguments"]})
t1 = time.time()
res = execute(c["name"], c["arguments"]) if c["name"] in names else {"error": f"tool not available: {c['name']}"}
emit({"t": "result", "name": c["name"], "result": res, "ms": int((time.time() - t1) * 1000)})
new_msgs.append({"role": "tool", "content": json.dumps(res, ensure_ascii=False)})
new_msgs.append({"role": "assistant", "content": "(zatrzymano po 5 krokach narzędzi)"})
emit({"t": "done", "new_messages": new_msgs, "context_tokens": 0})
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.0"
def log_message(self, *a):
pass
def _send(self, code, body, ctype="application/json; charset=utf-8"):
b = body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
if self.path in ("/", "/index.html"):
self._send(200, (HERE / "index.html").read_text(encoding="utf-8"), "text/html; charset=utf-8")
elif self.path == "/info":
self._send(200, json.dumps({"models": list(models()), "loaded": M["name"], "block": BLOCK,
"tools": [TOOLS[n] for n in TOOL_NAMES], "default_off": DEFAULT_OFF}, ensure_ascii=False))
else:
self._send(404, "{}")
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])) or b"{}")
if self.path != "/chat":
return self._send(404, "{}")
self.send_response(200)
self.send_header("Content-Type", "application/x-ndjson; charset=utf-8")
self.send_header("Cache-Control", "no-cache")
self.end_headers()
def emit(ev):
self.wfile.write((json.dumps(ev, ensure_ascii=False) + "\n").encode("utf-8"))
self.wfile.flush()
try:
with LOCK:
if req.get("model") and req["model"] != M["name"]:
emit({"t": "loading", "model": req["model"]})
ensure(req.get("model") or M["name"])
emit({"t": "model", "model": M["name"]})
run_chat(req, emit)
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as e:
try:
emit({"t": "error", "msg": f"{type(e).__name__}: {e}"})
except Exception:
pass
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8780)
ap.add_argument("--model", default=None)
a = ap.parse_args()
ms = models()
if not ms:
sys.exit("no model folders under release/ or models/")
ensure(a.model if a.model in ms else next(iter(ms)))
print(f"Slayer chat on http://localhost:{a.port} models: {', '.join(ms)}", flush=True)
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
if __name__ == "__main__":
main()
|