File size: 4,193 Bytes
b6fb167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LangGraph Agent"""
import os

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_community.vectorstores import SupabaseVectorStore
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.tools import tool
# from langchain.tools.retriever import create_retriever_tool
# from supabase.client import Client, create_client
from langchain_core.messages import AIMessage
from difflib import SequenceMatcher
import time  # Add time import

from tools import add, subtract, multiply, divide, modulus, wiki_search, web_search, arvix_search, search_metadata

# 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,
    search_metadata,
]

# Build graph function
def build_graph(provider: str = "google"):
    """Build the graph"""
    # Load environment variables from .env file
    if provider == "google":
        # Google Gemini
        llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash-preview-05-20", temperature=1)
    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"""
        messages = state["messages"]
        # If we have retrieved information, use it
        if len(messages) > 1 and "No matching results found in metadata" not in messages[-1].content:
            # Create a new message list with proper structure
            new_messages = [
                SystemMessage(content="You are a helpful assistant. Use the following retrieved information to answer the question. If the information is relevant, use it directly. If not, use your own knowledge."),
                HumanMessage(content=f"Question: {messages[-2].content}\n\nRetrieved Information:\n{messages[-1].content}")
            ]
            time.sleep(2)  # Add 2 second sleep before tool call
            return {"messages": [llm_with_tools.invoke(new_messages)]}
        else:
            # If no retrieved information, just use the original message
            time.sleep(2)  # Add 2 second sleep before tool call
            return {"messages": [llm_with_tools.invoke(messages)]}
    
    def retriever(state: MessagesState):
        query = state["messages"][-1].content
        result = search_metadata(query)
        return {"messages": [AIMessage(content=result)]}

    builder = StateGraph(MessagesState)
    builder.add_node("retriever", retriever)
    builder.add_node("assistant", assistant)
    builder.add_node("tools", ToolNode(tools))
    
    # Start with retriever
    builder.set_entry_point("retriever")
    
    # After retriever, go to assistant
    builder.add_edge("retriever", "assistant")
    
    # Assistant can either use tools or finish
    builder.add_conditional_edges(
        "assistant",
        tools_condition,
    )
    builder.add_edge("tools", "assistant")

    # Compile graph
    return builder.compile()