deNikk's picture
added hk_Token
cec729c verified
Raw History Blame Contribute Delete
1.96 kB
import os
from fastapi import FastAPI
from pydantic import BaseModel
from huggingface_hub import InferenceClient
import uvicorn
app = FastAPI()
# ✅ CHANGE: Get API token from Hugging Face Spaces secret instead of .env
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise ValueError("Hugging Face API token (HF_TOKEN) is missing!")
# ✅ CHANGE: Pass the token to InferenceClient
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1", token=HF_TOKEN)
class Item(BaseModel):
prompt: str
history: list
system_prompt: str
temperature: float = 0.0
max_new_tokens: int = 1048
top_p: float = 0.15
repetition_penalty: float = 1.0
def format_prompt(message, history):
prompt = "<s>"
for user_prompt, bot_response in history:
prompt += f"[INST] {user_prompt} [/INST] {bot_response}</s> "
prompt += f"[INST] {message} [/INST]"
return prompt
def generate(item: Item):
temperature = max(float(item.temperature), 1e-2)
top_p = float(item.top_p)
generate_kwargs = {
"temperature": temperature,
"max_new_tokens": item.max_new_tokens,
"top_p": top_p,
"repetition_penalty": item.repetition_penalty,
"do_sample": True,
"seed": 42,
}
formatted_prompt = format_prompt(f"{item.system_prompt}, {item.prompt}", item.history)
# ✅ CHANGE: Use token authentication for API call
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
output = "".join(response.token.text for response in stream)
return output
@app.post("/generate/")
async def generate_text(item: Item):
return {"response": generate(item)}
# ✅ ADDING TEST API ENDPOINT
@app.get("/test/")
async def test_api():
return {"message": "API is working!"}
# ✅ ADDING MAIN CHECK FOR LOCAL TESTING
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)