A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Improved Streamlit UI and made changes to model loading to improve response times
Joel Jamesf763c25dcc88
diff --git a/agentic_rag_with_o-3-mini_and_duckduckgo/README.md b/agentic_rag_with_o-3-mini_and_duckduckgo/README.mdindex 342451e..d4da541 100644--- a/agentic_rag_with_o-3-mini_and_duckduckgo/README.md+++ b/agentic_rag_with_o-3-mini_and_duckduckgo/README.md@@ -34,6 +34,8 @@ A Streamlit application demonstrating a Retrieval-Augmented Generation (RAG) worpip install -r requirements.txt```+ Ensure ollama is installed, with which you would need to download the corresponding model+ `ollama pull qwen3:1.7b`3. **OpenAI API Key:**Set the `OPENAI_API_KEY` environment variable or add it to your Streamlit secrets (`.streamlit/secrets.toml`).diff --git a/agentic_rag_with_qwen_and_firecrawl/app.py b/agentic_rag_with_qwen_and_firecrawl/app.pyindex 727374c..6ae9451 100644--- a/agentic_rag_with_qwen_and_firecrawl/app.py+++ b/agentic_rag_with_qwen_and_firecrawl/app.py@@ -8,13 +8,23 @@ import osfrom dotenv import load_dotenvimport base64from sentence_transformers import SentenceTransformer+import concurrent.futures+import time+from datetime import datetime+from queue import Queue-# Load embedder-embedding_model = SentenceTransformer("BAAI/bge-small-en-v1.5")+import torch+torch.classes.__path__ = []+# --- Caching for performance ---[email protected]_resource(show_spinner=False)+def get_embedding_model():+ return SentenceTransformer("BAAI/bge-small-en-v1.5")++# Custom Embedder using cached modelclass CustomEmbedder:def __init__(self):- self.model = SentenceTransformer("BAAI/bge-small-en-v1.5")+ self.model = get_embedding_model()self.dimensions = 384 # Required by agno Milvus wrapperdef get_embedding(self, text: str) -> list[float]:@@ -30,37 +40,6 @@ class CustomEmbedder:"output_vectors": len(embeddings),}return embeddings, usage--# Set Streamlit page config-st.set_page_config(- page_title="PDF RAG Agent (Local R1)",- page_icon="π",- layout="wide"-)--# Custom CSS styling-st.markdown("""-<style>-.stApp { color: #FAFAFA; }-.stSidebar > div:first-child {- background-image: linear-gradient(to bottom, #262936, #1e202a);-}-[data-testid="stChatMessage"] {- background-color: rgba(74, 74, 106, 0.4);- border-radius: 0.5rem;- padding: 1rem;- margin-bottom: 0.5rem;-}-[data-testid="stChatMessage"] p { color: inherit; }-.pdf-preview-container {- border: 1px solid #4A4A6A;- border-radius: 0.5rem;- padding: 0.5rem;- background-color: #262936;- margin-bottom: 1rem;-}-</style>-""", unsafe_allow_html=True)load_dotenv()@@ -77,16 +56,20 @@ vector_db = Milvus(embedder=CustomEmbedder())-# Create Agent-def get_rag_agent(knowledge_base: PDFKnowledgeBase, model_id="qwen3:8b", debug_mode=True):+def get_rag_agent(knowledge_base: PDFKnowledgeBase, model_id="qwen3:1.7b", debug_mode=True):model = Ollama(id=model_id)instructions = [+ "You are concise, quick and to the point. Don't display your thinking process.",+ "Do not show your reasoning, thoughts, or internal process to the user.",+ "Only output the final answer and relevant citations.",+ "Never display step-by-step thinking or tool call details.","1. Knowledge Base Search:"," - ALWAYS start by searching the knowledge base using search_knowledge_base tool"," - Analyze ALL returned documents thoroughly before responding"," - If multiple documents are returned, synthesize the information coherently","2. External Search:",- " - If knowledge base search yields insufficient results, use duckduckgo_search",+ " - If knowledge base search yields insufficient results, use FireCrawl",+ " - Use the search_web tool to search the web for the most recent information"," - Focus on reputable sources and recent information"," - Cross-reference information from multiple sources when possible","3. Citation Precision:",@@ -114,16 +97,111 @@ def get_rag_agent(knowledge_base: PDFKnowledgeBase, model_id="qwen3:8b", debug_mreturn Agent(model=model,knowledge=knowledge_base,- description="You are a helpful Agent called 'Agentic RAG' assisting with questions about a PDF document.", # Updated description+ description="You are a helpful Agent called 'Agentic RAG' assisting with questions about a PDF document.",instructions=instructions,search_knowledge=True,markdown=True,tools=[FirecrawlTools(api_key=firecrawl_api_key, scrape=False, crawl=True)],- show_tool_calls=True,+ show_tool_calls=False, #make True to debug and see what tools are being calledadd_datetime_to_instructions=False,- debug_mode=debug_mode,+ debug_mode=False, #make True if required+ stream=True,+ enable_agentic_memory=True,+ read_chat_history=True,+ read_tool_call_history=True)+def process_pdf(pdf_path, progress_queue):+ try:+ for i in range(1, 6):+ time.sleep(0.2) # Simulate progress+ progress_queue.put(i * 20)+ kb = PDFKnowledgeBase(path=pdf_path, vector_db=vector_db)+ kb.load(recreate=True)+ agent = get_rag_agent(kb)+ return kb, agent+ except Exception as e:+ progress_queue.put(("error", str(e)))+ raise e++# Set Streamlit page config+st.set_page_config(+ page_title="PDF RAG Agent (Local R1)",+ page_icon="π",+ layout="wide"+)++# Custom CSS styling+st.markdown("""+<style>+.stApp { color: #FAFAFA; }+.stSidebar > div:first-child {+ background-image: linear-gradient(to bottom, #262936, #1e202a);+}+[data-testid="stChatMessage"] {+ background-color: rgba(74, 74, 106, 0.4);+ border-radius: 0.5rem;+ padding: 1rem;+ margin-bottom: 0.5rem;+}+[data-testid="stChatMessage"] p { color: inherit; }+.pdf-preview-container {+ border: 1px solid #4A4A6A;+ border-radius: 0.5rem;+ padding: 0.5rem;+ background-color: #262936;+ margin-bottom: 1rem;+}+.user-bubble {+ background-color: #2d2d4d;+ color: #fff;+ border-radius: 0.5rem;+ padding: 0.75rem;+ margin-bottom: 0.5rem;+ position: relative;+ min-height: 2.5rem;+}+.assistant-bubble {+ background-color: #3a3a5a;+ color: #fff;+ border-radius: 0.5rem;+ padding: 0.75rem;+ margin-bottom: 0.5rem;+ position: relative;+ min-height: 2.5rem;+}+.timestamp {+ font-size: 0.8em;+ color: #aaa;+ position: absolute;+ bottom: 0.25rem;+ right: 0.75rem;+}+.message-content {+ margin-bottom: 1.5rem;+}+.message-content p {+ margin: 0;+ padding: 0;+}+.message-content ul, .message-content ol {+ margin: 0.5rem 0;+ padding-left: 1.5rem;+}+.message-content pre {+ margin: 0.5rem 0;+ padding: 0.5rem;+ background-color: rgba(0, 0, 0, 0.2);+ border-radius: 0.25rem;+}+.message-content code {+ background-color: rgba(0, 0, 0, 0.2);+ padding: 0.1rem 0.3rem;+ border-radius: 0.25rem;+}+</style>+""", unsafe_allow_html=True)+# PDF Viewerdef display_pdf_preview(pdf_path):try:@@ -134,62 +212,110 @@ def display_pdf_preview(pdf_path):st.error(f"Error displaying PDF: {e}")# Session State Init-for key in ["messages", "document_loaded", "agent", "knowledge_base"]:+for key in ["messages", "document_loaded", "agent", "knowledge_base", "processing", "progress"]:if key not in st.session_state:- st.session_state[key] = [] if key == "messages" else None+ if key == "messages":+ st.session_state[key] = []+ elif key == "progress":+ st.session_state[key] = 0+ else:+ st.session_state[key] = None-# Sidebar: Upload PDF+# --- Sidebar: Upload PDF ---with st.sidebar:- st.markdown("## Upload PDF")- uploaded_file = st.file_uploader("Choose a PDF", type=["pdf"])-- if uploaded_file:- pdf_path = "temp_uploaded.pdf"- with open(pdf_path, "wb") as f:- f.write(uploaded_file.read())-- display_pdf_preview(pdf_path)-- if not st.session_state.document_loaded:- if st.button("Process Document"):- with st.spinner("Indexing document..."):- kb = PDFKnowledgeBase(path=pdf_path, vector_db=vector_db)-- kb.load(recreate=True)- agent = get_rag_agent(kb)-- st.session_state.knowledge_base = kb- st.session_state.agent = agent- st.session_state.document_loaded = True- st.session_state.messages = []- st.rerun()-- else:+ with st.expander("Upload and Process PDF", expanded=True):+ if st.session_state.processing:+ progress_container = st.empty()+ progress_bar = progress_container.progress(0)+ status_container = st.empty()+ status_container.info("Processing document... Please wait.")+ elif st.session_state.document_loaded:st.markdown("β Document indexed!")+ else:+ uploaded_file = st.file_uploader("Choose a PDF", type=["pdf"])+ if uploaded_file:+ pdf_path = "temp_uploaded.pdf"+ with open(pdf_path, "wb") as f:+ f.write(uploaded_file.read())+ display_pdf_preview(pdf_path)+ if st.button("Process Document"):+ st.session_state.processing = True+ st.session_state.progress = 0+ progress_container = st.empty()+ progress_bar = progress_container.progress(0)+ status_container = st.empty()+ status_container.info("Processing document... Please wait.")+ progress_queue = Queue()+ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(process_pdf, pdf_path, progress_queue)+ while not future.done():+ try:+ progress = progress_queue.get_nowait()+ if isinstance(progress, tuple) and progress[0] == "error":+ st.error(f"Error during processing: {progress[1]}")+ break+ progress_bar.progress(progress)+ except:+ pass+ time.sleep(0.1)+ try:+ kb, agent = future.result()+ progress_bar.progress(100)+ st.session_state.knowledge_base = kb+ st.session_state.agent = agent+ st.session_state.document_loaded = True+ st.session_state.messages = []+ st.session_state.processing = False+ st.session_state.progress = 100+ progress_container.empty()+ status_container.empty()+ st.rerun()+ except Exception as e:+ st.error(f"Error during processing: {str(e)}")+ st.session_state.processing = False+ progress_container.empty()+ status_container.empty()+ st.rerun()-# Main Chat Area+# --- Main Chat Area ---st.markdown("# Chat with your PDF")-if not st.session_state.document_loaded:+if st.session_state.processing:+ st.info("Processing document... Please wait.")+elif not st.session_state.document_loaded:st.info("π Upload and process a PDF to begin.")else:- for msg in st.session_state.messages:- with st.chat_message(msg["role"]):- st.markdown(msg["content"])-- if prompt := st.chat_input("Ask something about your document..."):- st.session_state.messages.append({"role": "user", "content": prompt})+ with st.container():+ for msg in st.session_state.messages:+ timestamp = msg.get("timestamp")+ if not timestamp:+ timestamp = datetime.now().strftime("%H:%M:%S")+ msg["timestamp"] = timestamp+ bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"+ with st.chat_message(msg["role"]):+ st.markdown(f'<div class="{bubble_class}"><div class="message-content">{msg["content"]}</div><span class="timestamp">{timestamp}</span></div>', unsafe_allow_html=True)+ prompt = st.chat_input("Ask something about your document...")+ if prompt:+ now = datetime.now().strftime("%H:%M:%S")+ st.session_state.messages.append({"role": "user", "content": prompt, "timestamp": now})with st.chat_message("user"):- st.markdown(prompt)-+ st.markdown(f'<div class="user-bubble"><div class="message-content">{prompt}</div><span class="timestamp">{now}</span></div>', unsafe_allow_html=True)with st.chat_message("assistant"):msg_box = st.empty()- try:- response = st.session_state.agent.run(prompt)- content = response.content- msg_box.markdown(content)- except Exception as e:- content = f"Error: {e}"- st.error(content)-- st.session_state.messages.append({"role": "assistant", "content": content})- st.rerun()\ No newline at end of file+ with st.spinner("Lemme think about it..."):+ try:+ full_response = ""+ for chunk in st.session_state.agent.run(prompt):+ if hasattr(chunk, 'content'):+ full_response += chunk.content+ msg_box.markdown(f'<div class="assistant-bubble"><div class="message-content">{full_response}</div></div>', unsafe_allow_html=True)+ else:+ full_response += str(chunk)+ msg_box.markdown(f'<div class="assistant-bubble"><div class="message-content">{full_response}</div></div>', unsafe_allow_html=True)+ content = full_response+ now = datetime.now().strftime("%H:%M:%S")+ msg_box.markdown(f'<div class="assistant-bubble"><div class="message-content">{full_response}</div><span class="timestamp">{now}</span></div>', unsafe_allow_html=True)+ except Exception as e:+ content = f"Error: {e}"+ msg_box.markdown(f'<div class="assistant-bubble"><div class="message-content">{content}</div></div>', unsafe_allow_html=True)+ st.session_state.messages.append({"role": "assistant", "content": content, "timestamp": now})+ # Only rerun if document is processed, not after every message\ No newline at end of file