File size: 2,030 Bytes
2e97ffd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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"

@tool
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)}"