| from flask import Flask, render_template, request, jsonify |
| import os |
| from huggingface_hub import hf_hub_download |
| from llama_cpp import Llama |
| import threading |
|
|
| app = Flask(__name__) |
|
|
| |
| llm = None |
|
|
| def initialize_model(): |
| global llm |
| try: |
| print("Initializing TinyLlama model...") |
| |
| |
| model_name = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" |
| model_file = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf" |
| |
| |
| print(f"Downloading model: {model_name}/{model_file}") |
| model_path = hf_hub_download(model_name, filename=model_file) |
| |
| print(f"Model downloaded to: {model_path}") |
| |
| |
| llm = Llama( |
| model_path=model_path, |
| n_ctx=16000, |
| n_threads=4, |
| n_gpu_layers=-1, |
| verbose=False |
| ) |
| |
| print("Model initialized successfully!") |
| |
| except Exception as e: |
| print(f"Error initializing model: {str(e)}") |
| raise |
|
|
| |
| model_init_thread = threading.Thread(target=initialize_model) |
| model_init_thread.start() |
|
|
| @app.route('/') |
| def index(): |
| |
| if llm is None: |
| return "Model is still loading, please wait...", 503 |
| return render_template('index.html') |
|
|
| @app.route('/health') |
| def health(): |
| status = 'healthy' if llm is not None else 'loading' |
| return {'status': status} |
|
|
| @app.route('/chat', methods=['POST']) |
| def chat(): |
| global llm |
| |
| |
| if llm is None: |
| if model_init_thread.is_alive(): |
| return jsonify({'error': 'Model is still loading, please wait...'}), 503 |
| else: |
| return jsonify({'error': 'Model failed to load'}), 500 |
| |
| try: |
| user_message = request.json.get('message', '') |
| |
| if not user_message: |
| return jsonify({'error': 'No message provided'}), 400 |
| |
| |
| response = llm.create_chat_completion( |
| messages=[ |
| {"role": "system", "content": "You are a helpful assistant."}, |
| {"role": "user", "content": user_message} |
| ], |
| max_tokens=100, |
| temperature=0.7, |
| stop=["</s>", "\n"] |
| ) |
| |
| |
| assistant_response = response["choices"][0]["message"]["content"] |
| |
| return jsonify({ |
| 'response': assistant_response.strip() |
| }) |
| |
| except Exception as e: |
| return jsonify({'error': str(e)}), 500 |
|
|
| if __name__ == '__main__': |
| app.run(host='0.0.0.0', port=8501, debug=True) |