journal / app.py
srbmihaicode's picture
Revert "test"
31c0a7e
raw
history blame
2.07 kB
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("/chat", methods=["POST"])
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)