Create main.py
Browse files- app/main.py +42 -0
app/main.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from app.models import ChatRequest, ChatResponse
|
| 5 |
+
|
| 6 |
+
app = FastAPI(title="AI Chat Service (Hugging Face Space)")
|
| 7 |
+
|
| 8 |
+
# Hugging Face API ayarları
|
| 9 |
+
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 10 |
+
MODEL_URL = os.getenv("MODEL_URL", "https://api-inference.huggingface.co/models/meta-llama/Llama-3-8B-Instruct")
|
| 11 |
+
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def query_huggingface(prompt: str):
|
| 15 |
+
"""Hugging Face modeline prompt gönderir ve cevabı döner."""
|
| 16 |
+
response = requests.post(MODEL_URL, headers=HEADERS, json={"inputs": prompt})
|
| 17 |
+
response.raise_for_status()
|
| 18 |
+
data = response.json()
|
| 19 |
+
|
| 20 |
+
if isinstance(data, list) and "generated_text" in data[0]:
|
| 21 |
+
return data[0]["generated_text"]
|
| 22 |
+
elif isinstance(data, dict) and "generated_text" in data:
|
| 23 |
+
return data["generated_text"]
|
| 24 |
+
else:
|
| 25 |
+
return str(data)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@app.get("/")
|
| 29 |
+
def home():
|
| 30 |
+
return {"message": "AI Chat Service is running 🚀"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 34 |
+
def chat(request: ChatRequest):
|
| 35 |
+
"""Sohbet endpoint'i"""
|
| 36 |
+
prompt = ""
|
| 37 |
+
for role, msg in request.history:
|
| 38 |
+
prompt += f"{role}: {msg}\n"
|
| 39 |
+
prompt += f"User: {request.message}\nAssistant:"
|
| 40 |
+
|
| 41 |
+
model_output = query_huggingface(prompt)
|
| 42 |
+
return ChatResponse(response=model_output)
|