Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
# Limit parallelism to fit 2 CPU cores
|
| 3 |
+
os.environ["OMP_NUM_THREADS"] = "2"
|
| 4 |
+
os.environ["MKL_NUM_THREADS"] = "2"
|
| 5 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI, HTTPException
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 11 |
+
# Load the Phi-1.5 Instruct model (1.3B) from Hugging Face
|
| 12 |
+
model_id = "rasyosef/Phi-1_5-Instruct-v0.1"
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 14 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 15 |
+
pipe = pipeline(
|
| 16 |
+
"text-generation",
|
| 17 |
+
model=model,
|
| 18 |
+
tokenizer=tokenizer
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
app = FastAPI()
|
| 22 |
+
|
| 23 |
+
@app.get("/chat")
|
| 24 |
+
def chat(query: str):
|
| 25 |
+
"""
|
| 26 |
+
REST API endpoint. Use: GET /chat?query=Your question
|
| 27 |
+
Returns a JSON {"response": "..."}.
|
| 28 |
+
"""
|
| 29 |
+
if not query:
|
| 30 |
+
raise HTTPException(status_code=400, detail="Query parameter 'query' is required.")
|
| 31 |
+
# Use the same prompt format expected by the model:
|
| 32 |
+
messages = [
|
| 33 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 34 |
+
{"role": "user", "content": query}
|
| 35 |
+
]
|
| 36 |
+
result = pipe(
|
| 37 |
+
messages,
|
| 38 |
+
max_new_tokens=100,
|
| 39 |
+
do_sample=False,
|
| 40 |
+
return_full_text=False
|
| 41 |
+
)
|
| 42 |
+
answer = result[0]["generated_text"].strip()
|
| 43 |
+
return {"response": answer}
|
| 44 |
+
|
| 45 |
+
# Define Gradio UI (optional)
|
| 46 |
+
def gradio_chat(input_text):
|
| 47 |
+
if not input_text:
|
| 48 |
+
return ""
|
| 49 |
+
messages = [
|
| 50 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 51 |
+
{"role": "user", "content": input_text}
|
| 52 |
+
]
|
| 53 |
+
result = pipe(messages, max_new_tokens=100, do_sample=False, return_full_text=False)
|
| 54 |
+
return result[0]["generated_text"].strip()
|
| 55 |
+
|
| 56 |
+
iface = gr.Interface(
|
| 57 |
+
fn=gradio_chat,
|
| 58 |
+
inputs=gr.Textbox(lines=2, placeholder="Type a message..."),
|
| 59 |
+
outputs="text",
|
| 60 |
+
title="Phi-1.5 Chatbot",
|
| 61 |
+
description="Enter a message and press **Submit** to get a response."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Mount Gradio at root so it does not conflict with /chat
|
| 65 |
+
app = gr.mount_gradio_app(app, iface, path="/")
|