Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Set your Hugging Face API token
|
| 9 |
+
huggingface_token = os.environ.get("huggingface_token")
|
| 10 |
+
|
| 11 |
+
# Load the model
|
| 12 |
+
generator = pipeline("text-generation", model="EleutherAI/gpt-neo-2.7B")
|
| 13 |
+
|
| 14 |
+
conversation_history = []
|
| 15 |
+
|
| 16 |
+
@app.post("/chat")
|
| 17 |
+
async def chat(message: dict):
|
| 18 |
+
global conversation_history
|
| 19 |
+
# Extract user message
|
| 20 |
+
user_message = message["message"]
|
| 21 |
+
conversation_history.append({"role": "user", "content": user_message})
|
| 22 |
+
|
| 23 |
+
messages = [msg["content"] for msg in conversation_history]
|
| 24 |
+
|
| 25 |
+
# Add a system message to instruct the model
|
| 26 |
+
messages.insert(0, "You are a story writer. Whatever the prompt, you always write a short story of 30 words.")
|
| 27 |
+
|
| 28 |
+
# Generate response using Hugging Face model
|
| 29 |
+
reply = generator(messages, max_length=30, do_sample=False)[0]["generated_text"]
|
| 30 |
+
|
| 31 |
+
conversation_history.append({"role": "assistant", "content": reply})
|
| 32 |
+
|
| 33 |
+
return reply
|