Spaces:
Paused
Paused
Download tools/database_tool.py from bharathmunakala/ANAM: direct link, hf CLI and curl.
- Browser
- Download file 2.03 kB
-
https://huggingface.co/spaces/bharathmunakala/ANAM/resolve/main/tools/database_tool.py
- Command line
-
hf download hf://spaces/bharathmunakala/ANAM/tools/database_tool.py
-
curl -L -o database_tool.py https://huggingface.co/spaces/bharathmunakala/ANAM/resolve/main/tools/database_tool.py
2.03 kB
| import os | |
| from langchain.tools import tool | |
| from langchain_chroma import Chroma | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from loguru import logger | |
| # Configuration | |
| CHROMA_PATH = "chroma_db" | |
| EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2" | |
| def database_search(query: str) -> str: | |
| """ | |
| Search the internal knowledge base (database) for information from uploaded documents (PDF, TXT, MD). | |
| Use this tool when the user asks about specific documents, manuals, or uploaded content. | |
| Args: | |
| query: The search query to find relevant information. | |
| Returns: | |
| Relevant context from the database. | |
| """ | |
| try: | |
| logger.info(f"π Searching database for: {query}") | |
| embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL) | |
| # Initialize Chroma client | |
| if not os.path.exists(CHROMA_PATH): | |
| return "β Database not found. Please upload documents using the ingestion app first." | |
| db = Chroma( | |
| persist_directory=CHROMA_PATH, | |
| embedding_function=embeddings | |
| ) | |
| # Search for top 3 relevant chunks | |
| results = db.similarity_search(query, k=3) | |
| if not results: | |
| return f"β No relevant information found in the database for '{query}'." | |
| # Format output | |
| output = f"π Database Results for '{query}'\n\n" | |
| for idx, doc in enumerate(results, 1): | |
| source = doc.metadata.get("source", "Unknown") | |
| page = doc.metadata.get("page", "N/A") | |
| content = doc.page_content | |
| output += f"π *Source:* {os.path.basename(source)} (Page {page})\n" | |
| output += f"{content}\n\n" | |
| return output | |
| except Exception as e: | |
| logger.error(f"Error in database search: {e}") | |
| return f"β Database Search Error: {str(e)}" | |