Spaces:
Paused
Paused
File size: 2,075 Bytes
31c0a7e 980db68 31c0a7e a83fb54 31c0a7e 738c854 31c0a7e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
from flask import Flask, request, jsonify
from huggingface_hub import InferenceClient
# Initialize Flask app and Hugging Face client
app = Flask(__name__)
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Helper function to generate a response from the AI model
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 = ""
# Streaming response from the Hugging Face model
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("/", methods=["POST","GET"])
def home():
return "Hi!"
# API endpoint to handle requests
@app.route("/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)
# Validate inputs
if not isinstance(history, list) or not all(isinstance(pair, list) for pair in history):
return jsonify({"error": "Invalid history format. It should be a list of [message, response] pairs."}), 400
# Generate AI response
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
if __name__ == "__main__":
app.run(debug=True)
|