Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,14 @@
|
|
| 1 |
-
import spaces
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from langchain_community.vectorstores import FAISS
|
| 5 |
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline
|
| 6 |
-
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 7 |
from langchain_classic.chains import create_retrieval_chain
|
| 8 |
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
|
| 9 |
from langchain_core.prompts import PromptTemplate
|
| 10 |
|
| 11 |
-
# ==========================================
|
| 12 |
# 1. Load Vector Store
|
| 13 |
-
# ==========================================
|
| 14 |
-
print("Loading FAISS Vector Store...")
|
| 15 |
embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
|
| 16 |
-
|
| 17 |
vectorstore = FAISS.load_local(
|
| 18 |
"faiss_upf_index",
|
| 19 |
embeddings,
|
|
@@ -21,17 +16,19 @@ vectorstore = FAISS.load_local(
|
|
| 21 |
)
|
| 22 |
retriever = vectorstore.as_retriever()
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
# 2. Load Model & Tokenizer in 16-bit
|
| 26 |
-
# ==========================================
|
| 27 |
-
print("Loading Model...")
|
| 28 |
model_id = "anirudh248/llama3-upf-generator"
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
|
|
|
|
| 32 |
model = AutoModelForCausalLM.from_pretrained(
|
| 33 |
model_id,
|
| 34 |
-
|
|
|
|
| 35 |
)
|
| 36 |
model.generation_config.pad_token_id = tokenizer.eos_token_id
|
| 37 |
|
|
@@ -46,14 +43,9 @@ hf_pipeline = pipeline(
|
|
| 46 |
return_full_text=False,
|
| 47 |
clean_up_tokenization_spaces=False
|
| 48 |
)
|
| 49 |
-
|
| 50 |
llm = HuggingFacePipeline(pipeline=hf_pipeline)
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
# 3. Setup Dual Chains
|
| 54 |
-
# ==========================================
|
| 55 |
-
|
| 56 |
-
# CHAIN A: The UPF Code Generator
|
| 57 |
upf_prompt_template = """
|
| 58 |
You are an expert in Unified Power Format (UPF). Generate a precise and complete UPF code block based on the following power intent. Use the retrieved context as a reference. The code must be correct and adhere to UPF 3.0 standards.
|
| 59 |
|
|
@@ -69,11 +61,9 @@ upf_prompt = PromptTemplate.from_template(upf_prompt_template)
|
|
| 69 |
document_chain = create_stuff_documents_chain(llm, upf_prompt)
|
| 70 |
rag_chain = create_retrieval_chain(retriever, document_chain)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
User: {input}
|
| 76 |
-
Assistant:""")
|
| 77 |
|
| 78 |
def generate_upf_code(power_intent_description):
|
| 79 |
result = rag_chain.invoke({"input": power_intent_description})
|
|
@@ -82,33 +72,24 @@ def generate_upf_code(power_intent_description):
|
|
| 82 |
def generate_chat_response(user_message):
|
| 83 |
return llm.invoke(chat_prompt.format(input=user_message)).strip()
|
| 84 |
|
| 85 |
-
|
| 86 |
-
# ==========================================
|
| 87 |
-
# 4. Gradio UI & Routing Logic
|
| 88 |
-
# ==========================================
|
| 89 |
-
|
| 90 |
-
# Keywords that trigger the high-quality UPF generation path
|
| 91 |
UPF_KEYWORDS = [
|
| 92 |
"upf", "power", "domain", "isolation", "retention", "voltage",
|
| 93 |
"switch", "supply", "pst", "level shifter", "state", "intent",
|
| 94 |
"create_", "set_", "connect_"
|
| 95 |
]
|
| 96 |
|
| 97 |
-
@spaces.GPU(duration=120)
|
| 98 |
def user_interaction(user_message, history):
|
| 99 |
history = history or []
|
| 100 |
-
|
| 101 |
msg_lower = user_message.lower()
|
| 102 |
|
| 103 |
is_upf_request = any(kw in msg_lower for kw in UPF_KEYWORDS) or len(msg_lower.split()) > 12
|
| 104 |
|
| 105 |
if is_upf_request:
|
| 106 |
-
|
| 107 |
-
response = generate_upf_code(user_message)
|
| 108 |
if "```" not in response:
|
| 109 |
response = f"```tcl\n{response}\n```"
|
| 110 |
else:
|
| 111 |
-
# PATH B: Normal Conversation
|
| 112 |
response = generate_chat_response(user_message)
|
| 113 |
|
| 114 |
history.append({"role": "user", "content": user_message})
|
|
@@ -116,7 +97,7 @@ def user_interaction(user_message, history):
|
|
| 116 |
return history, ""
|
| 117 |
|
| 118 |
with gr.Blocks() as interface:
|
| 119 |
-
gr.Markdown("#
|
| 120 |
|
| 121 |
chatbot = gr.Chatbot(label="Chat History", elem_id="chatbot")
|
| 122 |
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
from langchain_community.vectorstores import FAISS
|
| 4 |
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline
|
| 5 |
+
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 6 |
from langchain_classic.chains import create_retrieval_chain
|
| 7 |
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
|
| 8 |
from langchain_core.prompts import PromptTemplate
|
| 9 |
|
|
|
|
| 10 |
# 1. Load Vector Store
|
|
|
|
|
|
|
| 11 |
embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
|
|
|
|
| 12 |
vectorstore = FAISS.load_local(
|
| 13 |
"faiss_upf_index",
|
| 14 |
embeddings,
|
|
|
|
| 16 |
)
|
| 17 |
retriever = vectorstore.as_retriever()
|
| 18 |
|
| 19 |
+
# 2. Load Model & Pipeline in 4-bit
|
|
|
|
|
|
|
|
|
|
| 20 |
model_id = "anirudh248/llama3-upf-generator"
|
| 21 |
|
| 22 |
+
bnb_config = BitsAndBytesConfig(
|
| 23 |
+
load_in_4bit=True,
|
| 24 |
+
bnb_4bit_compute_dtype=torch.float16
|
| 25 |
+
)
|
| 26 |
|
| 27 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 28 |
model = AutoModelForCausalLM.from_pretrained(
|
| 29 |
model_id,
|
| 30 |
+
quantization_config=bnb_config,
|
| 31 |
+
device_map="auto"
|
| 32 |
)
|
| 33 |
model.generation_config.pad_token_id = tokenizer.eos_token_id
|
| 34 |
|
|
|
|
| 43 |
return_full_text=False,
|
| 44 |
clean_up_tokenization_spaces=False
|
| 45 |
)
|
|
|
|
| 46 |
llm = HuggingFacePipeline(pipeline=hf_pipeline)
|
| 47 |
|
| 48 |
+
# 3. Setup RAG Chain & Chat Prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
upf_prompt_template = """
|
| 50 |
You are an expert in Unified Power Format (UPF). Generate a precise and complete UPF code block based on the following power intent. Use the retrieved context as a reference. The code must be correct and adhere to UPF 3.0 standards.
|
| 51 |
|
|
|
|
| 61 |
document_chain = create_stuff_documents_chain(llm, upf_prompt)
|
| 62 |
rag_chain = create_retrieval_chain(retriever, document_chain)
|
| 63 |
|
| 64 |
+
chat_prompt = PromptTemplate.from_template(
|
| 65 |
+
"You are a helpful AI assistant. Answer the user's message conversationally and concisely.\n\nUser: {input}\nAssistant:"
|
| 66 |
+
)
|
|
|
|
|
|
|
| 67 |
|
| 68 |
def generate_upf_code(power_intent_description):
|
| 69 |
result = rag_chain.invoke({"input": power_intent_description})
|
|
|
|
| 72 |
def generate_chat_response(user_message):
|
| 73 |
return llm.invoke(chat_prompt.format(input=user_message)).strip()
|
| 74 |
|
| 75 |
+
# 4. Routing Logic & Gradio Interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
UPF_KEYWORDS = [
|
| 77 |
"upf", "power", "domain", "isolation", "retention", "voltage",
|
| 78 |
"switch", "supply", "pst", "level shifter", "state", "intent",
|
| 79 |
"create_", "set_", "connect_"
|
| 80 |
]
|
| 81 |
|
|
|
|
| 82 |
def user_interaction(user_message, history):
|
| 83 |
history = history or []
|
|
|
|
| 84 |
msg_lower = user_message.lower()
|
| 85 |
|
| 86 |
is_upf_request = any(kw in msg_lower for kw in UPF_KEYWORDS) or len(msg_lower.split()) > 12
|
| 87 |
|
| 88 |
if is_upf_request:
|
| 89 |
+
response = generate_upf_code(user_message)
|
|
|
|
| 90 |
if "```" not in response:
|
| 91 |
response = f"```tcl\n{response}\n```"
|
| 92 |
else:
|
|
|
|
| 93 |
response = generate_chat_response(user_message)
|
| 94 |
|
| 95 |
history.append({"role": "user", "content": user_message})
|
|
|
|
| 97 |
return history, ""
|
| 98 |
|
| 99 |
with gr.Blocks() as interface:
|
| 100 |
+
gr.Markdown("# UPF Code Generator with Llama 3 & RAG")
|
| 101 |
|
| 102 |
chatbot = gr.Chatbot(label="Chat History", elem_id="chatbot")
|
| 103 |
|