MaryamKarimi080 commited on
Commit
4acac5f
·
verified ·
1 Parent(s): 4cc2fd8

Upload 7 files

Browse files
app.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from scripts.router_simple import build_router_chain
4
+
5
+ OPENAI_KEY = os.getenv("OPENAI_API_KEY", None)
6
+ MODEL_NAME = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
7
+
8
+ if not OPENAI_KEY:
9
+ print("WARNING: OPENAI_API_KEY not set. The app may fail at runtime.")
10
+
11
+ # Build the router once (keeps vectorstore & models in memory)
12
+ router = build_router_chain(model_name=MODEL_NAME)
13
+
14
+ def chat_fn(message, history):
15
+ if not message:
16
+ return history, ""
17
+ # call router
18
+ result = router.invoke({"input": message})
19
+ # RetrievalQA returns dict with 'result' key (and maybe 'source_documents')
20
+ answer = result.get("result") if isinstance(result, dict) else str(result)
21
+ # append sources if present
22
+ sources = None
23
+ if isinstance(result, dict) and "source_documents" in result and result["source_documents"]:
24
+ try:
25
+ sources = list({str(d.metadata.get("source", "unknown")) for d in result["source_documents"]})
26
+ except Exception:
27
+ sources = None
28
+ if sources:
29
+ answer = f"{answer}\n\n📚 Sources: {', '.join(sources)}"
30
+ history.append((message, answer))
31
+ return history, ""
32
+
33
+ with gr.Blocks() as demo:
34
+ gr.Markdown("## 📚 Course Assistant — Chat with your course files")
35
+ chatbot = gr.Chatbot(elem_id="chatbot")
36
+ txt = gr.Textbox(show_label=False, placeholder="Ask about the course...")
37
+ txt.submit(chat_fn, [txt, chatbot], [chatbot, txt])
38
+ txt.submit(lambda: None, None, txt) # clear input
39
+
40
+ if __name__ == "__main__":
41
+ demo.launch(server_port=int(os.getenv("PORT", 7860)))
output/all_docs.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5f5adf7c679373919bad157bdf906af58e79d96197f5dc8d4a544b808ba9943
3
+ size 6245290
output/chunks.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0401320f1374d0169a82a3f9e66fc2814bf3c3180074d90ccaffdd530c00240a
3
+ size 6796736
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ langchain-community
3
+ langchain-openai
4
+ langchain-chroma
5
+ chromadb
6
+ tiktoken
7
+ gradio
8
+ pickle5
9
+ pydantic<2
10
+
scripts/rag_chat.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.chains import RetrievalQA
2
+ from langchain_openai import ChatOpenAI
3
+ from langchain_chroma import Chroma
4
+ from langchain_openai import OpenAIEmbeddings
5
+ from langchain.prompts import PromptTemplate
6
+ from pathlib import Path
7
+
8
+ BASE_DIR = Path(__file__).resolve().parent.parent
9
+ DB_DIR = str(BASE_DIR / "db")
10
+
11
+ def build_general_qa_chain(model_name=None):
12
+ embedding = OpenAIEmbeddings(model="text-embedding-3-small")
13
+ vectorstore = Chroma(persist_directory=DB_DIR, embedding_function=embedding)
14
+
15
+ # Custom prompt with source attribution
16
+ template = """Use the following context to answer the question.
17
+ If the answer isn't found in the context, use your general knowledge but say so.
18
+ Always cite your sources at the end with 'Source: <filename>' when using course materials.
19
+
20
+ Context: {context}
21
+ Question: {question}
22
+ Helpful Answer:"""
23
+
24
+ QA_PROMPT = PromptTemplate(
25
+ template=template,
26
+ input_variables=["context", "question"]
27
+ )
28
+
29
+ llm = ChatOpenAI(model_name=model_name or "gpt-4o-mini", temperature=0.0)
30
+ qa_chain = RetrievalQA.from_chain_type(
31
+ llm=llm,
32
+ retriever=vectorstore.as_retriever(search_kwargs={"k": 4}),
33
+ chain_type_kwargs={"prompt": QA_PROMPT},
34
+ return_source_documents=True
35
+ )
36
+ return qa_chain
scripts/router_chain.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/router_simple.py
2
+ from typing import Dict, Any
3
+ from langchain.chat_models import ChatOpenAI
4
+ from langchain.prompts import ChatPromptTemplate
5
+ from scripts.rag_chat import build_general_qa_chain
6
+
7
+ def build_router_chain(model_name=None):
8
+ general_qa = build_general_qa_chain(model_name=model_name)
9
+ llm = ChatOpenAI(model_name=model_name or "gpt-4o-mini", temperature=0.0)
10
+
11
+ class Router:
12
+ def invoke(self, input_dict: Dict[str, Any]):
13
+ text = input_dict.get("input", "").lower()
14
+ if "code" in text or "program" in text or "debug" in text:
15
+ prompt = ChatPromptTemplate.from_template(
16
+ "As a coding assistant, help with this Python question.\nQuestion: {input}\nAnswer:"
17
+ )
18
+ chain = prompt | llm
19
+ return {"result": chain.invoke({"input": input_dict["input"]}).content}
20
+ elif "summarize" in text or "summary" in text:
21
+ prompt = ChatPromptTemplate.from_template(
22
+ "Provide a concise summary about: {input}\nSummary:"
23
+ )
24
+ chain = prompt | llm
25
+ return {"result": chain.invoke({"input": input_dict["input"]}).content}
26
+ elif "calculate" in text or any(char.isdigit() for char in text):
27
+ return {"result": "For calculations, please ask a specific calculation or provide more context."}
28
+ else:
29
+ # Use RAG chain
30
+ result = general_qa({"query": input_dict["input"]})
31
+ return result
32
+
33
+ return Router()
scripts/summarizer.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from langchain.chains.summarize import load_summarize_chain
2
+ from langchain_openai import ChatOpenAI
3
+
4
+ def get_summarizer():
5
+ llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0)
6
+ chain = load_summarize_chain(llm, chain_type="map_reduce")
7
+ return chain