Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Laad jouw eigen getrainde model in
|
| 9 |
+
model_path = "./SpaceStar-0.01-Final"
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(model_path).to("cpu")
|
| 12 |
+
|
| 13 |
+
class ChatRequest(BaseModel):
|
| 14 |
+
message: str
|
| 15 |
+
system_prompt: str = "Je bent SpaceStar 0.01, een geavanceerde AI-assistent die gespecialiseerd is in programmeren, wiskunde en communicatie in het Nederlands en Engels."
|
| 16 |
+
|
| 17 |
+
@app.post("/chat")
|
| 18 |
+
async def chat(request: ChatRequest):
|
| 19 |
+
# Formatteer het gesprek in de Qwen-stijl
|
| 20 |
+
messages = [
|
| 21 |
+
{"role": "system", "content": request.system_prompt},
|
| 22 |
+
{"role": "user", "content": request.message}
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 26 |
+
model_inputs = tokenizer([text], return_tensors="pt").to("cpu")
|
| 27 |
+
|
| 28 |
+
# Genereer het antwoord
|
| 29 |
+
generated_ids = model.generate(
|
| 30 |
+
**model_inputs,
|
| 31 |
+
max_new_tokens=256,
|
| 32 |
+
temperature=0.7,
|
| 33 |
+
top_p=0.9
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Filter de input-tokens weg zodat we alleen het antwoord overhouden
|
| 37 |
+
generated_ids = [
|
| 38 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 42 |
+
return {"response": response}
|
| 43 |
+
|
| 44 |
+
@app.get("/")
|
| 45 |
+
def home():
|
| 46 |
+
return {"status": "SpaceStar 0.01 is online and ready!"}
|