Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,51 @@
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
-
from
|
| 3 |
-
import
|
| 4 |
|
| 5 |
app = Flask(__name__)
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
with open(MODEL_PATH, "wb") as f:
|
| 17 |
-
f.write(r.content)
|
| 18 |
-
print("β
Model downloaded!")
|
| 19 |
|
| 20 |
-
print("
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
|
| 24 |
@app.route("/api/ask", methods=["POST"])
|
| 25 |
def ask():
|
| 26 |
data = request.get_json()
|
| 27 |
prompt = data.get("prompt", "")
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
temperature=0.7,
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
if __name__ == "__main__":
|
| 37 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
|
| 5 |
app = Flask(__name__)
|
| 6 |
|
| 7 |
+
# Load the Phi-3 model
|
| 8 |
+
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
| 9 |
+
print("π Loading model... this may take a minute.")
|
| 10 |
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
+
MODEL_NAME,
|
| 14 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 15 |
+
device_map="auto"
|
| 16 |
+
)
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
print("β
Model loaded successfully!")
|
| 19 |
+
|
| 20 |
+
@app.route("/")
|
| 21 |
+
def home():
|
| 22 |
+
return "<h2>π§ Phi-3-mini API is running!</h2><p>POST JSON to <code>/api/ask</code> with {'prompt': 'your question'}</p>"
|
| 23 |
|
| 24 |
@app.route("/api/ask", methods=["POST"])
|
| 25 |
def ask():
|
| 26 |
data = request.get_json()
|
| 27 |
prompt = data.get("prompt", "")
|
| 28 |
+
|
| 29 |
+
# System prompt to guide Phi-3 to act as a helpful assistant
|
| 30 |
+
full_prompt = f"<|system|>\nYou are Acla, a smart and friendly AI assistant. Be clear and concise.\n<|user|>\n{prompt}\n<|assistant|>"
|
| 31 |
+
|
| 32 |
+
inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
|
| 33 |
+
outputs = model.generate(
|
| 34 |
+
**inputs,
|
| 35 |
+
max_new_tokens=300,
|
| 36 |
temperature=0.7,
|
| 37 |
+
top_p=0.9,
|
| 38 |
+
do_sample=True
|
| 39 |
)
|
| 40 |
+
|
| 41 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 42 |
+
|
| 43 |
+
# Clean up: only return assistant's reply
|
| 44 |
+
if "<|assistant|>" in response:
|
| 45 |
+
response = response.split("<|assistant|>")[-1].strip()
|
| 46 |
+
|
| 47 |
+
return jsonify({"reply": response})
|
| 48 |
+
|
| 49 |
|
| 50 |
if __name__ == "__main__":
|
| 51 |
app.run(host="0.0.0.0", port=7860)
|