Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293import streamlit as stimport osimport asynciofrom pathlib import Pathfrom typing import Listfrom dotenv import load_dotenvfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext, load_index_from_storage, Documentfrom llama_index.llms.openai import OpenAIfrom llama_index.embeddings.openai import OpenAIEmbeddingfrom llama_cloud_services import LlamaParse# Load environment variables from .env (if present)load_dotenv()# Backend configuration (from llama_test.ipynb)# These values are fixed and cannot be changed from the UILLM_MODEL = "gpt-5-nano-2025-08-07"EMBEDDING_MODEL = "text-embedding-3-small"TEMPERATURE = 0.1DATA_DIR = "data"PERSIST_DIR = "./storage"# System prompt configuration# This can be customized to change the chatbot's behavior and personality# You can also set this via SYSTEM_PROMPT environment variableDEFAULT_SYSTEM_PROMPT = """You are a helpful AI assistant with access to a knowledge base.Answer questions based on the provided context. If you cannot find the answer in the context,let the user know that the information is not available in the documents."""# Allow overriding system prompt via environment variableSYSTEM_PROMPT = os.getenv('SYSTEM_PROMPT', DEFAULT_SYSTEM_PROMPT)# Configure Streamlit pagest.set_page_config(page_title="CatBot",page_icon="😺",layout="centered")# Helper function to get API keys from multiple sourcesdef get_api_key(key_name: str) -> str:"""Get API key from multiple sources in priority order:1. Environment variables (works for local dev, Docker, and Hugging Face Spaces)2. Streamlit secrets (works for Streamlit Cloud)Hugging Face Spaces: Set secrets in Space Settings > Repository secretsStreamlit Cloud: Set secrets in App Settings > SecretsLocal dev: Use .env file or export environment variables"""# Try environment variable first (highest priority)api_key = os.getenv(key_name)if api_key:return api_key# Try Streamlit secrets as fallbacktry:if key_name in st.secrets:return st.secrets[key_name]except (FileNotFoundError, KeyError):passreturn None# Get API keys from environment variables or Streamlit secrets# For Hugging Face Spaces: Add these as secrets in your Space settings# For Streamlit Cloud: Add these in the app secrets# For local development: Use .env fileopenai_api_key = get_api_key('OPENAI_API_KEY')llama_cloud_api_key = get_api_key('LLAMA_CLOUD_API_KEY')# Initialize chat historyif "messages" not in st.session_state:st.session_state.messages = []# Helper function to load documents with LlamaParsedef load_documents_with_llamaparse(data_dir: str, llama_api_key: str) -> List[Document]:"""Load documents from data directory using LlamaParse for complex file typesand SimpleDirectoryReader for basic text files.Supported complex file types: PDF, DOCX, PPTX, XLSX"""data_path = Path(data_dir)if not data_path.exists():return []# File extensions that benefit from LlamaParsellamaparse_extensions = {'.pdf', '.docx', '.pptx', '.xlsx', '.doc', '.ppt', '.xls'}# File extensions for simple text readingsimple_extensions = {'.txt', '.md', '.csv', '.json', '.html', '.xml'}all_files = list(data_path.glob('*'))llamaparse_files = []simple_files = []for file_path in all_files:if file_path.is_file():ext = file_path.suffix.lower()if ext in llamaparse_extensions:llamaparse_files.append(str(file_path))elif ext in simple_extensions:simple_files.append(str(file_path))documents = []# Process complex files with LlamaParseif llamaparse_files:st.info(f"📄 Processing {len(llamaparse_files)} complex file(s) with LlamaParse: {', '.join([Path(f).name for f in llamaparse_files])}")try:# Configure LlamaParse with optimal settingsparser = LlamaParse(api_key=llama_api_key,parse_mode="parse_page_with_agent",model="openai-gpt-4-1-mini",high_res_ocr=True,adaptive_long_table=True,outlined_table_extraction=True,output_tables_as_HTML=True,num_workers=4,verbose=True,language="en")# Parse files (LlamaParse handles batch processing)# Use asyncio to run the async parse methodloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)try:if len(llamaparse_files) == 1:result = loop.run_until_complete(parser.aparse(llamaparse_files[0]))results = [result]else:results = loop.run_until_complete(parser.aparse(llamaparse_files))finally:loop.close()# Convert JobResults to LlamaIndex Documentsfor result in results:# Get markdown documents with page splitting for better chunkingllamaparse_docs = result.get_markdown_documents(split_by_page=True)documents.extend(llamaparse_docs)except Exception as e:st.warning(f"LlamaParse processing failed for some files: {str(e)}")st.info("Falling back to SimpleDirectoryReader for these files...")# Fall back to simple reader if LlamaParse failssimple_files.extend(llamaparse_files)# Process simple text files with SimpleDirectoryReaderif simple_files:st.info(f"📝 Processing {len(simple_files)} simple file(s) with SimpleDirectoryReader: {', '.join([Path(f).name for f in simple_files])}")for file_path in simple_files:try:file_docs = SimpleDirectoryReader(input_files=[file_path]).load_data()documents.extend(file_docs)except Exception as e:st.warning(f"Failed to load {file_path}: {str(e)}")return documents# Initialize query engine@st.cache_resourcedef initialize_query_engine(_openai_api_key, _llama_api_key, _system_prompt):"""Initialize the LlamaIndex query engine with caching"""# Set API keysos.environ['OPENAI_API_KEY'] = _openai_api_keyif _llama_api_key:os.environ['LLAMA_CLOUD_API_KEY'] = _llama_api_key# Configure models with backend configurationllm = OpenAI(model=LLM_MODEL,temperature=TEMPERATURE,system_prompt=_system_prompt)embed_model = OpenAIEmbedding(model=EMBEDDING_MODEL)try:if not os.path.exists(PERSIST_DIR):# Load documents and create indexif not os.path.exists(DATA_DIR):os.makedirs(DATA_DIR)return None, "Please add documents to the 'data' directory"# Use LlamaParse if API key is available, otherwise fall back to SimpleDirectoryReaderif _llama_api_key:st.info("Using LlamaParse for advanced document processing...")documents = load_documents_with_llamaparse(DATA_DIR, _llama_api_key)else:st.info("Using SimpleDirectoryReader (LlamaParse API key not found)...")documents = SimpleDirectoryReader(DATA_DIR).load_data()if not documents:return None, "No documents found in the 'data' directory"index = VectorStoreIndex.from_documents(documents,llm=llm,embed_model=embed_model)# Store for laterindex.storage_context.persist(persist_dir=PERSIST_DIR)status = f"Index created with {len(documents)} documents"else:# Load existing indexstorage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)index = load_index_from_storage(storage_context)# Configure the loaded index with LLM and embedding models# This ensures the query engine uses the correct modelsindex._llm = llmindex._embed_model = embed_modelstatus = "Index loaded from storage"# Create query enginequery_engine = index.as_query_engine(llm=llm, embed_model=embed_model)return query_engine, statusexcept Exception as e:return None, f"❌ Error: {str(e)}"# Main chat interfaceif not openai_api_key:st.error("⚠️ OPENAI_API_KEY is required to run CatBot")st.info("""**How to set the API key:**- **Hugging Face Spaces**: Go to Settings → Repository secrets �� Add `OPENAI_API_KEY`- **Local Development**: Create a `.env` file with `OPENAI_API_KEY=your_key_here`- **Streamlit Cloud**: Add to App Settings → SecretsGet your OpenAI API key from: https://platform.openai.com/api-keys""")st.stop()# Display info about LlamaParse availabilityif not llama_cloud_api_key:st.info("💡 Tip: Set LLAMA_CLOUD_API_KEY to enable advanced parsing of PDFs, DOCX, and other complex documents.")# Initialize query engineif "query_engine" not in st.session_state:with st.spinner("Initializing RAG agent..."):query_engine, status = initialize_query_engine(openai_api_key,llama_cloud_api_key,SYSTEM_PROMPT)st.session_state.query_engine = query_engineif query_engine is None:st.error(status)st.stop()else:st.success(status)# Display chat historyfor message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])# Chat inputif prompt := st.chat_input("Ask a question about your documents"):# Display user messagewith st.chat_message("user"):st.markdown(prompt)# Add user message to historyst.session_state.messages.append({"role": "user", "content": prompt})# Generate responsewith st.chat_message("assistant"):with st.spinner("Thinking..."):try:response = st.session_state.query_engine.query(prompt)response_text = str(response)st.markdown(response_text)# Add assistant response to historyst.session_state.messages.append({"role": "assistant","content": response_text})except Exception as e:error_msg = f"Error generating response: {str(e)}"st.error(error_msg)st.session_state.messages.append({"role": "assistant","content": error_msg})
src/streamlit_app.py+291-38