Spaces:
Build error
Build error
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
+
from fastapi.responses import StreamingResponse
|
5 |
+
|
6 |
+
app = FastAPI()
|
7 |
+
|
8 |
+
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
9 |
+
|
10 |
+
class Item(BaseModel):
|
11 |
+
prompt: str
|
12 |
+
history: list
|
13 |
+
system_prompt: str
|
14 |
+
temperature: float = 0.0
|
15 |
+
max_new_tokens: int = 1048
|
16 |
+
top_p: float = 0.15
|
17 |
+
repetition_penalty: float = 1.0
|
18 |
+
|
19 |
+
def format_prompt(message, history):
|
20 |
+
prompt = "<s>"
|
21 |
+
for user_prompt, bot_response in history:
|
22 |
+
prompt += f"[INST] {user_prompt} [/INST]"
|
23 |
+
prompt += f" {bot_response}</s> "
|
24 |
+
prompt += f"[INST] {message} [/INST]"
|
25 |
+
return prompt
|
26 |
+
|
27 |
+
async def generate_stream(item: Item):
|
28 |
+
try:
|
29 |
+
temperature = max(float(item.temperature), 1e-2)
|
30 |
+
top_p = float(item.top_p)
|
31 |
+
|
32 |
+
generate_kwargs = dict(
|
33 |
+
temperature=temperature,
|
34 |
+
max_new_tokens=item.max_new_tokens,
|
35 |
+
top_p=top_p,
|
36 |
+
repetition_penalty=item.repetition_penalty,
|
37 |
+
do_sample=True,
|
38 |
+
seed=42,
|
39 |
+
)
|
40 |
+
|
41 |
+
formatted_prompt = format_prompt(f"{item.system_prompt}, {item.prompt}", item.history)
|
42 |
+
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
|
43 |
+
|
44 |
+
for response in stream:
|
45 |
+
yield response.token.text
|
46 |
+
except Exception as e:
|
47 |
+
print(f"Error in generate_stream: {e}")
|
48 |
+
finally:
|
49 |
+
if 'stream' in locals():
|
50 |
+
stream.close()
|
51 |
+
|
52 |
+
@app.post("/generate/")
|
53 |
+
async def generate_text(item: Item):
|
54 |
+
try:
|
55 |
+
return StreamingResponse(generate_stream(item), media_type="text/plain")
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Error in generate_text: {e}")
|
58 |
+
return {"error": str(e)}
|