Update main.py
Browse files
main.py
CHANGED
|
@@ -1,20 +1,43 @@
|
|
| 1 |
from fastapi import FastAPI, Header, HTTPException
|
| 2 |
-
from transformers import
|
| 3 |
from pydantic import BaseModel
|
|
|
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
API_KEY = "bazi2281488133767695242"
|
| 13 |
|
| 14 |
-
@app.post("/
|
| 15 |
-
def
|
| 16 |
if x_api_key != API_KEY:
|
| 17 |
raise HTTPException(status_code=403, detail="Go away")
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Header, HTTPException
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
from pydantic import BaseModel
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
import torch
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
model_id = "google/gemma-2b-it"
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu", torch_dtype=torch.float32)
|
| 12 |
|
| 13 |
+
class Message(BaseModel):
|
| 14 |
+
role: str # "user" или "model"
|
| 15 |
+
content: str
|
| 16 |
+
|
| 17 |
+
class ChatRequest(BaseModel):
|
| 18 |
+
messages: List[Message]
|
| 19 |
+
max_tokens: Optional[int] = 128000
|
| 20 |
+
temperature: Optional[float] = 0.7
|
| 21 |
|
| 22 |
API_KEY = "bazi2281488133767695242"
|
| 23 |
|
| 24 |
+
@app.post("/chat")
|
| 25 |
+
def chat(request: ChatRequest, x_api_key: str = Header(None)):
|
| 26 |
if x_api_key != API_KEY:
|
| 27 |
raise HTTPException(status_code=403, detail="Go away")
|
| 28 |
|
| 29 |
+
input_ids = tokenizer.apply_chat_template([m.dict() for m in request.messages],
|
| 30 |
+
return_tensors="pt"
|
| 31 |
+
).to("cpu")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
outputs = model.generate(
|
| 35 |
+
input_ids,
|
| 36 |
+
max_new_tokens=request.max_tokens,
|
| 37 |
+
temperature=request.temperature,
|
| 38 |
+
do_sample=True
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
|
| 42 |
+
|
| 43 |
+
return {"response": response}
|