HsuHH commited on
Commit
84dab87
·
verified ·
1 Parent(s): 6559e08

LLM-RAG-HW-0001

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ chroma_db/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
`requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ chromadb
3
+ langchain
4
+ langchain-community
5
+ langchain-huggingface
6
+ sentence-transformers
app.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from rag import get_rag_response
4
+
5
+ # --- Gradio Chat Wrapper ---
6
+ def chat_function(message, history):
7
+ """
8
+ Gradio passes the user's new 'message' and the chat 'history' automatically.
9
+ We hand the message to your existing RAG pipeline.
10
+ """
11
+ answer = get_rag_response(message)
12
+ return answer
13
+
14
+ # --- UI Definition ---
15
+ demo = gr.ChatInterface(
16
+ fn=chat_function,
17
+ title="My Personal Knowledge Base",
18
+ description="Ask my AI questions based on my personal notes.",
19
+ theme=gr.themes.Soft(),
20
+ examples=["What are my notes on machine learning?", "Summarize my recent project plans."]
21
+ )
22
+
23
+ if __name__ == "__main__":
24
+ # Hugging Face Spaces requires the app to bind to 0.0.0.0
25
+ demo.launch(server_name="0.0.0.0", server_port=7860)
chroma_db/09989bea-8a40-4c1f-9c95-96378d5756e5/data_level0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cea68868543f4bba4ab1015429b2ddb2958c34359559d94b39ad58acbabecda7
3
+ size 167600
chroma_db/09989bea-8a40-4c1f-9c95-96378d5756e5/header.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0e81c3b22454233bc12d0762f06dcca48261a75231cf87c79b75e69a6c00150
3
+ size 100
chroma_db/09989bea-8a40-4c1f-9c95-96378d5756e5/length.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65dac0c40a9671394281201f420c4685aed98abd8727c0244a9acca5a92c2a98
3
+ size 400
chroma_db/09989bea-8a40-4c1f-9c95-96378d5756e5/link_lists.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
3
+ size 0
chroma_db/chroma.sqlite3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:107f763763598bb28422390e9dbfbbcc7062b7688a6e6ec68bb6d1436baedf0a
3
+ size 229376
rag.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_community.vectorstores import Chroma
3
+ from langchain_community.embeddings import HuggingFaceEmbeddings
4
+ from langchain_huggingface import HuggingFaceEndpoint
5
+ from langchain_core.prompts import ChatPromptTemplate
6
+
7
+ # --- Configuration ---
8
+ CHROMA_PATH = "./chroma_db"
9
+
10
+ PROMPT_TEMPLATE = """
11
+ You are a helpful, private AI assistant.
12
+ Answer the question based ONLY on the following context from my personal notes:
13
+
14
+ {context}
15
+
16
+ ---
17
+
18
+ Question: {question}
19
+ """
20
+
21
+ # 1. Initialize DB and Embeddings ONCE globally
22
+ print("Loading embeddings and database...")
23
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
24
+ db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
25
+
26
+ # 2. Connect to Hugging Face's Cloud LLM instead of local Ollama
27
+ hf_token = os.environ.get("HF_TOKEN")
28
+ if not hf_token:
29
+ raise ValueError("HF_TOKEN missing. Please add your Hugging Face Access Token to the Space Secrets.")
30
+
31
+ llm = HuggingFaceEndpoint(
32
+ repo_id="google/gemma-2-2b-it",
33
+ task="text-generation",
34
+ max_new_tokens=512,
35
+ huggingfacehub_api_token=hf_token
36
+ )
37
+
38
+ def get_rag_response(query_text):
39
+ """This function is called by your Gradio app.py"""
40
+
41
+ # Retrieve the relevant chunks
42
+ results = db.similarity_search_with_relevance_scores(query_text, k=3)
43
+
44
+ if len(results) == 0 or results[0][1] < 0.2:
45
+ return "I couldn't find any highly relevant notes to answer that."
46
+
47
+ # Format the chunks
48
+ context_text = "\n\n---\n\n".join([doc.page_content for doc, _ in results])
49
+
50
+ # Build the prompt
51
+ prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
52
+ prompt = prompt_template.format(context=context_text, question=query_text)
53
+
54
+ # Ask Gemma
55
+ response_text = llm.invoke(prompt)
56
+
57
+ # Format the final output to return to the Gradio UI
58
+ final_answer = response_text.strip() + "\n\n### 📚 Sources Used:\n"
59
+ for doc, score in results:
60
+ source_name = doc.metadata.get('source', 'Unknown')
61
+ final_answer += f"- **{source_name}** (Relevance: {score:.2f})\n"
62
+
63
+ return final_answer