import json import os import uuid from bottle import Bottle, request, response, run import torch from utils import init_env, get_model_config, get_small_model_config from llm_model import LlmModel from llm_trainer import TrainerTools, streaming_generate import traceback from search import get_search_api init_env() device = "cpu" if torch.cuda.is_available(): device = "cuda" elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): device = "mps" model_name = 'dpo.bin' if not os.path.exists(f'./{model_name}'): from huggingface_hub import snapshot_download snapshot_download( 'qibin0506/Cortex', allow_patterns=model_name, local_dir='./' ) model = LlmModel(get_model_config(long_context=True)).to(device=device) model.load_state_dict(torch.load(f'./{model_name}', weights_only=True)) model.eval() app = Bottle() with open('./static/index.html', 'r') as f: html = f.read() def fmt_msg(event, data): data = data.replace('\n', '
') return f"{json.dumps({'event': event, 'data':data})}\n\n" def generate_user_uuid() -> str: unique_id = uuid.uuid4() return unique_id.hex @app.get('/') def index(): visitor_count = 0 generate_count = 0 if os.path.exists('./visitor.txt'): with open('./visitor.txt', 'r') as f: visitor_count = int(f.readline()) if os.path.exists('./generator.txt'): with open('./generator.txt', 'r') as f: generate_count = int(f.readline()) with open('./visitor.txt', 'w') as f: f.write(f'{visitor_count + 1}') return html.replace('{{__VISITOR_COUNT__}}', f"{visitor_count}").replace('{{__GENERATE_COUNT__}}', f"{generate_count}") @app.hook('after_request') def enable_cors(): """Add CORS headers to all responses to allow cross-origin requests.""" response.set_header('Access-Control-Allow-Origin', '*') response.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') response.set_header('Access-Control-Allow-Headers', 'Content-Type') @app.route('/api/chat', method=['OPTIONS']) def options_handler(): """Handle CORS pre-flight requests.""" return @app.route('/api/chat', method=['POST']) def sse_chat(): """ Handles chat requests and returns a streaming response via SSE. """ response.content_type = 'text/event-stream' response.set_header('Cache-Control', 'no-cache') response.set_header('Connection', 'keep-alive') try: generate_count = 0 if os.path.exists('./generator.txt'): with open('./generator.txt', 'r') as f: generate_count = int(f.readline()) with open('./generator.txt', 'w') as f: f.write(f'{generate_count + 1}') payload = request.json chat_history = payload.get('history') thinking = payload.get('thinking') user_uuid = payload.get('uuid') temperature = payload.get('temperature') top_p = payload.get('top_p') think_budget_enable = thinking and payload.get('think_budget_enable') think_budget = payload.get('think_budget') deep_search = payload.get('deep_search') if not think_budget: think_budget_enable = False if deep_search: thinking = False think_budget_enable = False search_api = get_search_api() chat_history = chat_history[-1:] else: search_api = None # 仅保留两轮对话 chat_history = chat_history[-3:] if not chat_history: yield fmt_msg('error', 'Chat history cannot be empty') return except (json.JSONDecodeError, AttributeError): yield fmt_msg('error', 'Invalid JSON payload') return try: if search_api: chat_history = [{'role': 'system', 'content': '我需要根据用户的问题和搜索到的结果给出用户答案,回答的方式要简明扼要'}, *chat_history] else: chat_history = [{'role': 'system', 'content': ' '}, *chat_history] chat_template = TrainerTools().tokenizer.apply_chat_template(chat_history, tokenizer=False) print(f"generate for {chat_template}") chat_template = f'{chat_template}' if search_api: user_prompt = chat_history[-1]['content'].replace('/think', '').replace('/no think', '') search_result = search_api(user_prompt) if search_result: search_msg = f'根据用户的问题,我搜索到了如下内容:\n{search_result}' yield fmt_msg('thinking_chunk', search_msg) chat_template = f'{chat_template}{search_msg}' prompt_token = TrainerTools().tokenizer.encode(chat_template, unsqueeze=True) output_token_count = max(2048 - prompt_token.shape[-1], 0) if think_budget_enable: think_budget_content = '。考虑到用户的时间限制,我现在必须根据思考直接给出解决方案\n' think_budget_encoded = TrainerTools().tokenizer.encode(f'{think_budget_content}') think_budget = think_budget - len(think_budget_encoded) output_token_count = min(think_budget, output_token_count) generator = streaming_generate( model=model, prompt=prompt_token, max_position_embeddings=2048, max_new_tokens=output_token_count, temperature=temperature, k=None, p=top_p, device=device ) think_content = '' for chunk in generator: think_content += chunk if chunk == '': break yield fmt_msg('thinking_chunk', chunk) if '' not in think_content: think_content += f'{think_budget_content}' yield fmt_msg('thinking_chunk', think_budget_content) prompt_token = torch.concat([prompt_token, TrainerTools().tokenizer.encode(think_content, unsqueeze=True)], dim=-1) output_token_count = max(2048 - prompt_token.shape[-1], 0) generator = streaming_generate( model=model, prompt=prompt_token, max_position_embeddings=2048, max_new_tokens=output_token_count, temperature=temperature, k=None, p=top_p, device=device ) msg_type = None is_start = False for chunk in generator: if chunk == '\n' and is_start: continue is_start = False if chunk == '': break if chunk == '' or chunk == '': continue if chunk == '' or chunk == '': continue if chunk == '': msg_type = 'thinking_chunk' is_start = True continue elif chunk == '': msg_type = 'answer_chunk' is_start = True continue if msg_type: yield fmt_msg(msg_type, chunk) except Exception as e: traceback.print_exc() print(f"Error during model generation: {e}") yield fmt_msg('error', f'Internal server error: {e}') if __name__ == '__main__': # Use 'waitress' for a production-ready WSGI server on Windows/Linux try: from waitress import serve serve(app, host='0.0.0.0', port=7860) except ImportError: print("Waitress not found, falling back to Bottle's default server.") # Fallback for environments without waitress run(app, host='0.0.0.0', port=7860, server='paste') print("Bottle server started at http://0.0.0.0:7860/")