Download app.py from bhanu2511/Minitrix: direct link, hf CLI and curl.
- Browser
- Download file 5.81 kB
-
https://huggingface.co/spaces/bhanu2511/Minitrix/resolve/main/app.py
- Command line
-
hf download hf://spaces/bhanu2511/Minitrix/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bhanu2511/Minitrix/resolve/main/app.py
5.81 kB
| # Setup: Install necessary libraries | |
| # The requirements.txt will handle this during deployment, but keeping for local testing | |
| # %pip install -q -U langchain langchain-community langchain-huggingface unstructured transformers accelerate bitsandbytes sentence-transformers faiss-cpu gradio | |
| import os | |
| import torch | |
| from langchain.chains import RetrievalQA | |
| from langchain_community.document_loaders import DirectoryLoader | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_huggingface import HuggingFacePipeline | |
| from langchain.text_splitter import CharacterTextSplitter | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig | |
| from huggingface_hub import notebook_login # Import notebook_login to get the token | |
| import gradio as gr # Import gradio | |
| # Create the knowledge base directory and a dummy file if they don't exist | |
| # This is just for demonstration purposes. Replace with your actual knowledge base. | |
| if not os.path.exists("./minitrix_knowledge_base"): | |
| os.makedirs("./minitrix_knowledge_base") | |
| with open("./minitrix_knowledge_base/example.txt", "w") as f: | |
| f.write("Minitrix SLMs are designed for efficiency and performance on smaller devices.\n") | |
| f.write("They differ from traditional LLMs in their size and focus on specific tasks.\n") | |
| f.write("FAISS is a library for efficient similarity search and clustering of dense vectors.") | |
| # Data Pipeline: Load and split documents | |
| print("Loading and splitting documents...") | |
| loader = DirectoryLoader("./minitrix_knowledge_base/", glob="**/*.txt", show_progress=True) | |
| documents = loader.load() | |
| text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) | |
| docs = text_splitter.split_documents(documents) | |
| print(f"Loaded {len(documents)} documents and split into {len(docs)} chunks.") | |
| # Vector Store: Create embeddings and build FAISS vector store | |
| print("Creating embeddings and building vector store...") | |
| embeddings_model_name = "sentence-transformers/all-MiniLM-L6-v2" | |
| embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name) | |
| vectorstore = FAISS.from_documents(docs, embeddings) | |
| print("Vector store created.") | |
| # Save the vector store | |
| vectorstore_save_path = "faiss_index_minitrix" | |
| vectorstore.save_local(vectorstore_save_path) | |
| print(f"Vector store saved to {vectorstore_save_path}") | |
| # Load the generator SLM | |
| model_id = "NousResearch/Llama-2-7b-chat-hf" # Changed model_id | |
| print(f"Loading the generator SLM: {model_id}...") | |
| # BitsAndBytesConfig for quantization (adjust as needed for your hardware) | |
| bnb_config = BitsAndBytesConfig( | |
| load_in_4bit=True, | |
| bnb_4bit_quant_type="nf4", | |
| bnb_4bit_compute_dtype=torch.bfloat16 | |
| ) | |
| # Get the authentication token from notebook_login (for local testing if needed, deployment handles auth differently) | |
| try: | |
| from huggingface_hub import get_token | |
| auth_token = get_token() | |
| except: | |
| auth_token = None | |
| print("Could not retrieve Hugging Face token. Ensure you have run `notebook_login()` and authenticated.") | |
| if auth_token is None: | |
| print("Hugging Face token is not available. Please run `notebook_login()` and authenticate.") | |
| else: | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_id, | |
| quantization_config=bnb_config, | |
| device_map="auto", | |
| trust_remote_code=True, | |
| token=auth_token # Pass the authentication token | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(model_id, token=auth_token) # Pass the authentication token | |
| print("SLM loaded successfully.") | |
| # Create the final RAG Chain | |
| pipe = pipeline( | |
| "text-generation", | |
| model=model, | |
| tokenizer=tokenizer, | |
| max_new_tokens=512, | |
| # use_cache=False # May not be needed for this model | |
| ) | |
| llm = HuggingFacePipeline(pipeline=pipe) | |
| print("Creating the RAG chain...") | |
| qa_chain = RetrievalQA.from_chain_type( | |
| llm=llm, | |
| chain_type="stuff", | |
| retriever=vectorstore.as_retriever() | |
| ) | |
| print("RAG chain created successfully.") | |
| # Define the Gradio response function | |
| def get_minitrix_response(question_string): | |
| """ | |
| This function takes the user's question as a string, formats it correctly | |
| for the RAG chain, and returns the final answer. | |
| """ | |
| # This is the prompt template we used to test the chain. | |
| system_message = "Answer the following question based only on the context provided. If the answer is not in the context, say 'I don't have that information.'" | |
| prompt_template = f"<s>[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n{question_string} [/INST]" | |
| # Create the dictionary that the chain expects as input | |
| input_dict = {"query": prompt_template} | |
| # Invoke the chain with the correctly formatted input | |
| result = qa_chain.invoke(input_dict) | |
| # Extract and process the text answer from the result dictionary | |
| raw_output = result['result'] | |
| # Llama-2 model output often starts after the [/INST] tag. | |
| if "[/INST]" in raw_output: | |
| answer_part = raw_output.split("[/INST]", 1)[1].strip() | |
| else: | |
| answer_part = raw_output.strip() | |
| return answer_part | |
| # Create the Gradio interface | |
| iface = gr.Interface( | |
| fn=get_minitrix_response, | |
| inputs=gr.Textbox(lines=2, placeholder="Ask a question about Minitrix..."), | |
| outputs="text", | |
| title="Minitrix AI Assistant", | |
| description="Your expert guide to Minitrix's custom SLM solutions.", | |
| flagging_mode="never" | |
| ) | |
| # To run locally uncomment the line below. | |
| # iface.launch(share=True) | |
| else: | |
| print("Model loading and RAG chain creation skipped because Hugging Face token is not available.") | |