Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from huggingface_hub import InferenceClient
|
| 3 |
+
|
| 4 |
+
app = Flask(__name__)
|
| 5 |
+
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 6 |
+
|
| 7 |
+
# Chat response function
|
| 8 |
+
def generate_response(message, history, system_message, max_tokens, temperature, top_p):
|
| 9 |
+
messages = [{"role": "system", "content": system_message}]
|
| 10 |
+
|
| 11 |
+
for val in history:
|
| 12 |
+
if val[0]:
|
| 13 |
+
messages.append({"role": "user", "content": val[0]})
|
| 14 |
+
if val[1]:
|
| 15 |
+
messages.append({"role": "assistant", "content": val[1]})
|
| 16 |
+
|
| 17 |
+
messages.append({"role": "user", "content": message})
|
| 18 |
+
|
| 19 |
+
response = ""
|
| 20 |
+
for message in client.chat_completion(
|
| 21 |
+
messages,
|
| 22 |
+
max_tokens=max_tokens,
|
| 23 |
+
stream=True,
|
| 24 |
+
temperature=temperature,
|
| 25 |
+
top_p=top_p,
|
| 26 |
+
):
|
| 27 |
+
token = message.choices[0].delta.content
|
| 28 |
+
response += token
|
| 29 |
+
|
| 30 |
+
return response
|
| 31 |
+
|
| 32 |
+
@app.route("/api/chat", methods=["POST"])
|
| 33 |
+
def chat():
|
| 34 |
+
try:
|
| 35 |
+
data = request.json
|
| 36 |
+
message = data.get("message")
|
| 37 |
+
history = data.get("history", [])
|
| 38 |
+
system_message = data.get("system_message", "You are a friendly Chatbot.")
|
| 39 |
+
max_tokens = data.get("max_tokens", 512)
|
| 40 |
+
temperature = data.get("temperature", 0.7)
|
| 41 |
+
top_p = data.get("top_p", 0.95)
|
| 42 |
+
|
| 43 |
+
if not message:
|
| 44 |
+
return jsonify({"error": "Message is required"}), 400
|
| 45 |
+
|
| 46 |
+
response = generate_response(
|
| 47 |
+
message, history, system_message, max_tokens, temperature, top_p
|
| 48 |
+
)
|
| 49 |
+
return jsonify({"response": response})
|
| 50 |
+
|
| 51 |
+
except Exception as e:
|
| 52 |
+
return jsonify({"error": str(e)}), 500
|
| 53 |
+
|
| 54 |
+
@app.route("/", methods=["GET"])
|
| 55 |
+
def api_status():
|
| 56 |
+
return jsonify({"status": "API is active", "version": "1.0.0", "service": "Chatbot"})
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
app.run(host="0.0.0.0", port=5000, debug=True)
|