gilangf3000's picture
Create app.py
f778ef0 verified
from flask import Flask, request, jsonify
from huggingface_hub import InferenceClient
app = Flask(__name__)
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Chat response function
def generate_response(message, history, system_message, max_tokens, temperature, top_p):
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
response = ""
for message in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = message.choices[0].delta.content
response += token
return response
@app.route("/api/chat", methods=["POST"])
def chat():
try:
data = request.json
message = data.get("message")
history = data.get("history", [])
system_message = data.get("system_message", "You are a friendly Chatbot.")
max_tokens = data.get("max_tokens", 512)
temperature = data.get("temperature", 0.7)
top_p = data.get("top_p", 0.95)
if not message:
return jsonify({"error": "Message is required"}), 400
response = generate_response(
message, history, system_message, max_tokens, temperature, top_p
)
return jsonify({"response": response})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/", methods=["GET"])
def api_status():
return jsonify({"status": "API is active", "version": "1.0.0", "service": "Chatbot"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)