| from flask import Flask, request, jsonify |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import torch |
|
|
| |
| |
| |
| model_name = "Qwen/Qwen2.5-0.5B-Instruct" |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) |
|
|
| |
| model = AutoModelForCausalLM.from_pretrained( |
| model_name, |
| device_map="auto", |
| dtype=torch.float32 |
| ) |
|
|
| |
| if torch.__version__.startswith("2"): |
| model = torch.compile(model) |
|
|
| |
| |
| |
| SYSTEM_PROMPT = "You are a friendly AI assistant that gives helpful and polite answers." |
|
|
| |
| |
| |
| def chat(user_prompt: str): |
| messages = [ |
| {"role": "system", "content": SYSTEM_PROMPT}, |
| {"role": "user", "content": user_prompt} |
| ] |
|
|
| |
| text = tokenizer.apply_chat_template( |
| messages, |
| tokenize=False, |
| add_generation_prompt=True |
| ) |
|
|
| |
| inputs = tokenizer([text], return_tensors="pt").to(model.device) |
|
|
| |
| outputs = model.generate( |
| **inputs, |
| max_new_tokens=128, |
| do_sample=False, |
| num_beams=1 |
| ) |
|
|
| |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) |
| return response |
|
|
| |
| |
| |
| app = Flask(__name__) |
|
|
| @app.route("/chat", methods=["GET"]) |
| def chat_route(): |
| user_message = request.args.get("message") |
|
|
| if not user_message: |
| return jsonify({"error": "No message provided"}), 400 |
|
|
| try: |
| response = chat(user_message) |
| return jsonify({"response": response}) |
| except Exception as e: |
| return jsonify({"error": str(e)}), 500 |
|
|
| |
| |
| |
| if __name__ == "__main__": |
| app.run(host="0.0.0.0", port=7860) |