Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
import os
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
# Load environment variables from the .env file
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
# Get the Hugging Face token from the environment variables
|
| 10 |
+
hf_token = os.getenv("HUGGINGFACE_TOKEN")
|
| 11 |
+
|
| 12 |
+
# Initialize the InferenceClient with the model and token
|
| 13 |
+
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
|
| 14 |
+
|
| 15 |
+
# Create FastAPI app
|
| 16 |
+
app = FastAPI()
|
| 17 |
+
|
| 18 |
+
# Response generation function
|
| 19 |
+
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
|
| 20 |
+
messages = [{"role": "system", "content": system_message}]
|
| 21 |
+
|
| 22 |
+
# Add the conversation history to the message list
|
| 23 |
+
for val in history:
|
| 24 |
+
if val[0]:
|
| 25 |
+
messages.append({"role": "user", "content": val[0]})
|
| 26 |
+
if val[1]:
|
| 27 |
+
messages.append({"role": "assistant", "content": val[1]})
|
| 28 |
+
|
| 29 |
+
# Add the new user message to the message list
|
| 30 |
+
messages.append({"role": "user", "content": message})
|
| 31 |
+
|
| 32 |
+
response = ""
|
| 33 |
+
|
| 34 |
+
# Collect tokens from the model
|
| 35 |
+
for msg in client.chat_completion(
|
| 36 |
+
messages,
|
| 37 |
+
max_tokens=max_tokens,
|
| 38 |
+
stream=True,
|
| 39 |
+
temperature=temperature,
|
| 40 |
+
top_p=top_p,
|
| 41 |
+
):
|
| 42 |
+
token = msg.choices[0].delta.content
|
| 43 |
+
if token:
|
| 44 |
+
response += token
|
| 45 |
+
|
| 46 |
+
return response # Return the complete response directly
|
| 47 |
+
|
| 48 |
+
# Endpoint to access the API via FastAPI
|
| 49 |
+
@app.post("/generate-response/")
|
| 50 |
+
async def generate_response(request: Request):
|
| 51 |
+
body = await request.json()
|
| 52 |
+
message = body["message"]
|
| 53 |
+
history = body.get("history", [])
|
| 54 |
+
system_message = body.get("system_message", "You are a friendly Chatbot.")
|
| 55 |
+
max_tokens = body.get("max_tokens", 512)
|
| 56 |
+
temperature = body.get("temperature", 0.7)
|
| 57 |
+
top_p = body.get("top_p", 0.95)
|
| 58 |
+
|
| 59 |
+
# Call respond function and return the response
|
| 60 |
+
response = respond(message, history, system_message, max_tokens, temperature, top_p)
|
| 61 |
+
return {"response": response}
|