File size: 8,450 Bytes
f653dd8
9a4d5ce
 
f653dd8
497b4bc
09e5d34
 
 
 
9a4d5ce
 
 
 
 
497b4bc
f653dd8
 
9a4d5ce
f653dd8
9a4d5ce
 
f653dd8
f990347
92a5106
9a4d5ce
f653dd8
09e5d34
 
f653dd8
09e5d34
 
f002bf5
 
 
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
 
f002bf5
 
 
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
 
f002bf5
 
 
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
 
f002bf5
 
09e5d34
f002bf5
 
9a4d5ce
f002bf5
 
09e5d34
9a4d5ce
f002bf5
09e5d34
 
f002bf5
 
 
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
3e95386
 
 
 
 
9a4d5ce
 
3e95386
f002bf5
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
3e95386
 
 
 
 
9a4d5ce
 
3e95386
f002bf5
9a4d5ce
f002bf5
09e5d34
 
9a4d5ce
f002bf5
09e5d34
3e95386
 
 
 
 
9a4d5ce
 
3e95386
 
f653dd8
9a4d5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b885f6
497b4bc
3e95386
 
f653dd8
 
 
 
 
 
 
 
 
 
09e5d34
 
 
f653dd8
 
9a4d5ce
f653dd8
2237b5d
 
 
 
 
 
 
 
9a4d5ce
 
 
f653dd8
2237b5d
f653dd8
2237b5d
 
 
 
f653dd8
 
09e5d34
f653dd8
 
 
497b4bc
f653dd8
 
 
62309ba
f653dd8
9a4d5ce
2237b5d
9a4d5ce
 
35d1d29
 
9a4d5ce
 
 
 
 
 
 
 
35d1d29
2237b5d
9a4d5ce
2237b5d
 
 
 
9a4d5ce
35d1d29
 
 
2237b5d
9a4d5ce
f653dd8
497b4bc
 
f653dd8
2237b5d
 
 
f002bf5
2237b5d
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
import pandas as pd
import numpy as np
from dotenv import load_dotenv
from langgraph.graph import START, StateGraph, MessagesState
from langgraph.prebuilt import tools_condition
from langgraph.prebuilt import ToolNode
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_huggingface import (
    ChatHuggingFace,
    HuggingFaceEndpoint,
    HuggingFaceEmbeddings,
)
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WikipediaLoader
from langchain_community.document_loaders import ArxivLoader
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.tools import tool
from sklearn.metrics.pairwise import cosine_similarity
import ast

load_dotenv()


@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers.
    Args:
        a: first int
        b: second int
    """
    return a * b


@tool
def add(a: int, b: int) -> int:
    """Add two numbers.

    Args:
        a: first int
        b: second int
    """
    return a + b


@tool
def subtract(a: int, b: int) -> int:
    """Subtract two numbers.

    Args:
        a: first int
        b: second int
    """
    return a - b


@tool
def divide(a: int, b: int) -> int:
    """Divide two numbers.

    Args:
        a: first int
        b: second int
    """
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b


@tool
def modulus(a: int, b: int) -> int:
    """Get the modulus of two numbers.

    Args:
        a: first int
        b: second int
    """
    return a % b


@tool
def wiki_search(query: str) -> str:
    """Search Wikipedia for a query and return maximum 2 results.

    Args:
        query: The search query."""
    search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
            for doc in search_docs
        ]
    )
    return {"wiki_results": formatted_search_docs}


@tool
def web_search(query: str) -> str:
    """Search Tavily for a query and return maximum 3 results.

    Args:
        query: The search query."""
    search_docs = TavilySearchResults(max_results=3).invoke(query=query)
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
            for doc in search_docs
        ]
    )
    return {"web_results": formatted_search_docs}


@tool
def arvix_search(query: str) -> str:
    """Search Arxiv for a query and return maximum 3 result.

    Args:
        query: The search query."""
    search_docs = ArxivLoader(query=query, load_max_docs=3).load()
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
            for doc in search_docs
        ]
    )
    return {"arvix_results": formatted_search_docs}


# Load CSV data and embeddings
class LocalCSVRetriever:
    def __init__(self, csv_file_path="supabase_docs.csv"):
        self.csv_file_path = csv_file_path
        self.df = None
        self.embeddings_model = HuggingFaceEmbeddings(
            model_name="sentence-transformers/all-mpnet-base-v2"
        )
        self.load_data()
    
    def load_data(self):
        """Load data from CSV file"""
        try:
            self.df = pd.read_csv(self.csv_file_path)
            print(f"Loaded {len(self.df)} documents from {self.csv_file_path}")
            
            # Convert string representation of embeddings back to numpy arrays
            if 'embedding' in self.df.columns:
                self.df['embedding_array'] = self.df['embedding'].apply(
                    lambda x: np.array(ast.literal_eval(x)) if isinstance(x, str) else np.array(x)
                )
        except FileNotFoundError:
            print(f"CSV file {self.csv_file_path} not found!")
            self.df = pd.DataFrame()
        except Exception as e:
            print(f"Error loading CSV: {e}")
            self.df = pd.DataFrame()
    
    def similarity_search(self, query: str, k: int = 1):
        """Perform similarity search on local data"""
        if self.df.empty:
            return []
        
        # Get query embedding
        query_embedding = self.embeddings_model.embed_query(query)
        query_embedding = np.array(query_embedding).reshape(1, -1)
        
        # Calculate similarities
        similarities = []
        for idx, row in self.df.iterrows():
            doc_embedding = row['embedding_array'].reshape(1, -1)
            similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
            similarities.append((idx, similarity, row['content']))
        
        # Sort by similarity and return top k
        similarities.sort(key=lambda x: x[1], reverse=True)
        
        # Create simple document-like objects
        results = []
        for i in range(min(k, len(similarities))):
            idx, sim_score, content = similarities[i]
            # Create a simple object with page_content attribute
            doc = type('Document', (), {
                'page_content': content,
                'metadata': ast.literal_eval(self.df.iloc[idx]['metadata']) if isinstance(self.df.iloc[idx]['metadata'], str) else self.df.iloc[idx]['metadata']
            })()
            results.append(doc)
        
        return results


# Initialize the local retriever
local_retriever = LocalCSVRetriever()

# load the system prompt from the file
with open("system_prompt.txt", "r", encoding="utf-8") as f:
    system_prompt = f.read()

# System message
sys_msg = SystemMessage(content=system_prompt)

tools = [
    multiply,
    add,
    subtract,
    divide,
    modulus,
    wiki_search,
    web_search,
    arvix_search,
]


# Build graph function
def build_graph(provider: str = "groq"):
    """Build the graph"""
    # Load environment variables from .env file
    if provider == "google":
        # Google Gemini
        llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
    elif provider == "groq":
        # Groq https://console.groq.com/docs/models
        llm = ChatGroq(
            model="qwen-qwq-32b", temperature=0
        )  # optional : qwen-qwq-32b gemma2-9b-it
    elif provider == "huggingface":
        # TODO: Add huggingface endpoint
        llm = ChatHuggingFace(
            llm=HuggingFaceEndpoint(
                url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
                temperature=0,
            ),
        )
    else:
        raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
    # Bind tools to LLM
    llm_with_tools = llm.bind_tools(tools)

    # Node
    def assistant(state: MessagesState):
        """Assistant node"""
        return {"messages": [llm_with_tools.invoke(state["messages"])]}

    def retriever(state: MessagesState):
        """Modified retriever to use local CSV data"""
        query = state["messages"][-1].content
        similar_docs = local_retriever.similarity_search(query, k=1)

        # Handle empty results
        if not similar_docs:
            return {
                "messages": [
                    AIMessage(
                        content="I don't have information about this topic in my knowledge base. Please try a different question."
                    )
                ]
            }

        similar_doc = similar_docs[0]
        content = similar_doc.page_content

        if "Final answer :" in content:
            answer = content.split("Final answer :")[-1].strip()
        else:
            answer = content.strip()

        # Ensure answer is not empty
        if not answer:
            answer = "I found related information but couldn't extract a clear answer. Please rephrase your question."

        return {"messages": [AIMessage(content=answer)]}

    builder = StateGraph(MessagesState)
    builder.add_node("retriever", retriever)

    # Retriever ist Start und Endpunkt
    builder.set_entry_point("retriever")
    builder.set_finish_point("retriever")

    # Compile graph
    return builder.compile()