Spaces:
Running on Zero
Running on Zero
Plan switching, resubscribe, honest cancel flow, token-based limits with model weights
cf67874 verified Download spark_server.py from mohith2309/mai-api: direct link, hf CLI and curl.
- Browser
- Download file 6.16 kB
-
https://huggingface.co/spaces/mohith2309/mai-api/resolve/main/spark_server.py
- Command line
-
hf download hf://spaces/mohith2309/mai-api/spark_server.py
-
curl -L -o spark_server.py https://huggingface.co/spaces/mohith2309/mai-api/resolve/main/spark_server.py
6.16 kB
| """Spark chat server for the m.ai Hugging Face Space (research preview). | |
| Same contract as the m.ai app's /api/chat: POST {"messages": [...], "max_tokens": n} -> Server-Sent Events | |
| `data: {"t": "..."}` ... `data: {"done": true, "tokens": n, "prompt_tokens": m}`. Only the m.ai API inside the same container calls it | |
| (it binds to 127.0.0.1), and the API has already checked sign-in, plan and usage limits. | |
| Decoding matches the app: the checkpoint's own system prompt, greedy, repetition penalty 1.1, at most 128 tokens. | |
| """ | |
| import json | |
| import os | |
| import threading | |
| import time | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| import torch | |
| from alus import encode_chat, decode, get_tokenizer, load_checkpoint | |
| HOST, PORT = os.environ.get('SPARK_HOST', '127.0.0.1'), int(os.environ.get('SPARK_PORT', '8800')) | |
| torch.set_num_threads(int(os.environ.get('SPARK_THREADS', '2'))) | |
| state = {'model': None, 'system': None, 'context': 512, 'error': None, 'version': None} | |
| busy = threading.Lock() | |
| enc = get_tokenizer() | |
| def checkpoint_path(): | |
| if os.environ.get('SPARK_CHECKPOINT'): # local test | |
| return os.environ['SPARK_CHECKPOINT'] | |
| from huggingface_hub import hf_hub_download # private model repo, read with the Space's HF_TOKEN secret | |
| return hf_hub_download(os.environ.get('SPARK_REPO', 'mohith2309/spark'), os.environ.get('SPARK_FILE', 'spark.pt'), | |
| token=os.environ.get('HF_TOKEN') or None) | |
| def load(): | |
| try: | |
| t0 = time.time() | |
| model, ck = load_checkpoint(checkpoint_path()) | |
| if ck.get('stage') != 'sft' or not ck.get('chat_system'): | |
| raise ValueError('checkpoint is not a chat model') | |
| state.update(model=model, system=ck['chat_system'], version=ck.get('version'), | |
| context=min(1024, int(ck.get('run', {}).get('sequence', 512)))) | |
| print(json.dumps({'event': 'spark_loaded', 'seconds': round(time.time() - t0, 1), 'version': state['version']}), flush=True) | |
| except Exception as e: # the API keeps running and tells users Spark is offline | |
| state['error'] = f'{type(e).__name__}: {e}' | |
| print(json.dumps({'event': 'spark_failed', 'error': state['error']}), flush=True) | |
| def build_prompt(messages): | |
| """Same as m.ai's prompting.build_prompt: system + conversation, dropping whole old turns to fit.""" | |
| limit = state['context'] - 64 | |
| msgs = [{'role': 'system', 'content': state['system']}] + [dict(m) for m in messages] | |
| while True: | |
| ids, _ = encode_chat(enc, msgs) | |
| if len(ids) <= limit: | |
| return ids | |
| if len(msgs) <= 2: | |
| raise ValueError('That message is too long for Spark. Try a shorter one.') | |
| msgs.pop(1) | |
| if len(msgs) > 2 and msgs[1]['role'] == 'assistant': | |
| msgs.pop(1) | |
| class Handler(BaseHTTPRequestHandler): | |
| def log_message(self, *args): # no request logs: they could contain prompts | |
| pass | |
| def reply(self, code, data): | |
| body = json.dumps(data).encode() | |
| self.send_response(code) | |
| self.send_header('Content-Type', 'application/json') | |
| self.send_header('Content-Length', str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| def do_GET(self): | |
| if self.path == '/health': | |
| return self.reply(200 if state['model'] else 503, | |
| {'ready': bool(state['model']), 'version': state['version'], 'error': state['error']}) | |
| self.reply(404, {'error': 'Not found'}) | |
| def do_POST(self): | |
| if self.path != '/api/chat': | |
| return self.reply(404, {'error': 'Not found'}) | |
| if not state['model']: | |
| return self.reply(503, {'error': 'Spark is starting. Try again in a minute.'}) | |
| try: | |
| size = int(self.headers.get('Content-Length') or 0) | |
| if size > 65536: | |
| raise ValueError('Request too large') | |
| body = json.loads(self.rfile.read(size) or b'{}') | |
| messages = body.get('messages') | |
| if not isinstance(messages, list) or not messages or any( | |
| not isinstance(m, dict) or m.get('role') not in ('user', 'assistant') or not isinstance(m.get('content'), str) | |
| for m in messages) or messages[-1]['role'] != 'user': | |
| raise ValueError('Provide text messages ending with the user') | |
| max_tokens = max(1, min(128, int(body.get('max_tokens', 128)))) | |
| ids = build_prompt(messages) | |
| except (ValueError, TypeError) as e: | |
| return self.reply(400, {'error': str(e)}) | |
| if not busy.acquire(blocking=False): | |
| return self.reply(429, {'error': 'Spark is answering someone else. Try again in a moment.'}) | |
| try: | |
| self.send_response(200) | |
| self.send_header('Content-Type', 'text/event-stream') | |
| self.send_header('Cache-Control', 'no-cache') | |
| self.end_headers() | |
| out, sent = [], '' | |
| for tok in state['model'].generate(ids, max_tokens, temperature=0): | |
| out.append(tok) | |
| text = decode(enc, out) | |
| if not text.endswith('�') and len(text) > len(sent): | |
| self.wfile.write(('data: ' + json.dumps({'t': text[len(sent):]}) + '\n\n').encode()) | |
| self.wfile.flush() | |
| sent = text | |
| # prompt_tokens + tokens: what the m.ai API charges against the plan's token limits | |
| self.wfile.write(('data: ' + json.dumps({'done': True, 'tokens': len(out), 'prompt_tokens': len(ids)}) + '\n\n').encode()) | |
| except (BrokenPipeError, ConnectionResetError): | |
| pass | |
| except Exception as e: | |
| try: | |
| self.wfile.write(('data: ' + json.dumps({'error': type(e).__name__}) + '\n\n').encode()) | |
| except OSError: | |
| pass | |
| finally: | |
| busy.release() | |
| if __name__ == '__main__': | |
| threading.Thread(target=load, daemon=True).start() | |
| print(json.dumps({'event': 'spark_listening', 'host': HOST, 'port': PORT}), flush=True) | |
| ThreadingHTTPServer((HOST, PORT), Handler).serve_forever() | |