Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
+
|
5 |
+
app = FastAPI()
|
6 |
+
|
7 |
+
client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
|
8 |
+
|
9 |
+
class PromptRequest(BaseModel):
|
10 |
+
prompt: str
|
11 |
+
history: list
|
12 |
+
|
13 |
+
def format_prompt(message, history):
|
14 |
+
system_prompt = "You are Mistral, a gentle and a useful AI assistant. My input is "
|
15 |
+
prompt = "<s>"
|
16 |
+
prompt += f"[INST] {system_prompt} [/INST]"
|
17 |
+
for user_prompt, bot_response in history:
|
18 |
+
prompt += f"[INST] {user_prompt} [/INST]"
|
19 |
+
prompt += f" {bot_response}</s> "
|
20 |
+
prompt += f"[INST] {message} [/INST]"
|
21 |
+
return prompt
|
22 |
+
|
23 |
+
def generate(prompt, history):
|
24 |
+
formatted_prompt = format_prompt(prompt, history)
|
25 |
+
|
26 |
+
stream = client.text_generation(formatted_prompt, stream=True, details=True, return_full_text=False)
|
27 |
+
output = ""
|
28 |
+
for response in stream:
|
29 |
+
output += response.token.text
|
30 |
+
yield output
|
31 |
+
|
32 |
+
@app.post("/generate/")
|
33 |
+
async def generate_response(request: PromptRequest):
|
34 |
+
try:
|
35 |
+
responses = []
|
36 |
+
async for response in generate(request.prompt, request.history):
|
37 |
+
responses.append(response)
|
38 |
+
return {"responses": responses}
|
39 |
+
except Exception as e:
|
40 |
+
raise HTTPException(status_code=500, detail=str(e))
|