File size: 6,977 Bytes
8c269dc
b64c7e2
960e946
b64c7e2
73f74f6
8c269dc
b64c7e2
 
73f74f6
b64c7e2
960e946
b64c7e2
66bfc35
960e946
 
66bfc35
b64c7e2
 
66bfc35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
960e946
 
 
 
 
 
73f74f6
960e946
 
b64c7e2
73f74f6
 
b64c7e2
51d5738
73f74f6
b64c7e2
73f74f6
 
b64c7e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
960e946
 
 
 
 
 
 
 
 
 
 
 
73f74f6
 
 
 
 
 
 
73cd47f
73f74f6
960e946
 
 
73f74f6
960e946
 
 
 
 
 
 
73cd47f
73f74f6
960e946
 
 
b64c7e2
 
8c269dc
 
 
 
 
960e946
b64c7e2
66bfc35
 
 
 
 
 
 
8c269dc
66bfc35
 
73f74f6
66bfc35
b64c7e2
 
 
 
 
73f74f6
 
b64c7e2
 
 
 
 
 
 
 
 
960e946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b64c7e2
 
 
8c269dc
73f74f6
 
73cd47f
960e946
73f74f6
 
 
 
b64c7e2
 
 
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
from dotenv import load_dotenv, find_dotenv
import os
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
from langchain_community.tools.google_search.tool import GoogleSearchAPIWrapper
from langchain_tavily import TavilySearch
from langchain_community.document_loaders import AsyncHtmlLoader
from langchain.tools import tool
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import AgentExecutor, create_tool_calling_agent
from csv_cache import CSVSCache
from prompt import get_prompt
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
from enum import Enum
from langchain_core.tools import Tool

import re

# --- Define Tools ---
@tool
def multiply(a: int, b: int) -> int:
    """Multiply two integers."""
    return a * b

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

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

@tool
def divide(a: int, b: int) -> float:
    """Divide a by b, error on zero."""
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b

@tool
def modulus(a: int, b: int) -> int:
    """Compute a mod b."""
    return a % b

@tool
def wiki_search(query: str) -> dict:
    """Search Wikipedia and return up to 2 documents."""
    docs = WikipediaLoader(query=query, load_max_docs=2).load()
    results = [f"<Document source=\"{d.metadata['source']}\" page=\"{d.metadata.get('page','')}\"/>\n{d.page_content}" for d in docs]
    return {"wiki_results": "\n---\n".join(results)}

@tool
def arxiv_search(query: str) -> dict:
    """Search Arxiv and return up to 3 docs."""
    docs = ArxivLoader(query=query, load_max_docs=3).load()
    results = [f"<Document source=\"{d.metadata['source']}\" page=\"{d.metadata.get('page','')}\"/>\n{d.page_content[:1000]}" for d in docs]
    return {"arxiv_results": "\n---\n".join(results)}

class LLMProvider(Enum):
    """
    An Enum to represent the different LLM providers and their
    corresponding environment variable names for API keys.
    """
    HUGGINGFACE = ("HuggingFace", "HF_TOKEN")
    HUGGINGFACE_LLAMA = ("HUGGINGFACE_LLAMA", "HF_TOKEN")
    GOOGLE_GEMINI = ("Google Gemini", "GOOGLE_API_KEY")

class Model:
    def __init__(self, provider: LLMProvider = LLMProvider.HUGGINGFACE):        
        load_dotenv(find_dotenv())
        self.system_prompt = get_prompt()
        print(f"system_prompt: {self.system_prompt}")
        self.provider = provider
        self.agent_executor = self.setup_model()
        


    def get_answer(self, question: str) -> str:
        try:
            result = self.agent_executor.invoke({"input": question})
        except BaseException as e:
            print(f"An error occurred: {e}")
            result = {"FINAL_ANSWER":"ERROR"}

        # The final answer is typically in the 'output' key of the result dictionary
        final_answer = result['output']

        pattern = r'FINAL_ANSWER:"(.*?)"'
        match = re.search(pattern, final_answer, re.DOTALL)
        if match:
            final_answer_value = match.group(1)
            print(f"The extracted FINAL_ANSWER is: {final_answer_value}")  
        else:
            print("ERROR: Pattern not found.: {r}")
            final_answer_value = "ERROR"

        return final_answer_value

    def get_chat_with_tools(self, provider: LLMProvider, tools):
     
        api_token = os.getenv(provider.value[1])
        if not api_token:
            raise ValueError(
                f"API key for {provider.value[0]} not found. "
                f"Please set the '{provider.value[1]}' environment variable."
            )

        if provider == LLMProvider.HUGGINGFACE:
            llm = HuggingFaceEndpoint(
            repo_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
            huggingfacehub_api_token=api_token,
            temperature=0
        )
            return ChatHuggingFace(llm=llm).bind_tools(tools)
        
        if provider == LLMProvider.HUGGINGFACE_LLAMA:
            llm = HuggingFaceEndpoint(
            repo_id="meta-llama/Llama-3.3-70B-Instruct",
            huggingfacehub_api_token=api_token,
            temperature=0
        )
            return ChatHuggingFace(llm=llm).bind_tools(tools)
           
            
        
        elif provider == LLMProvider.GOOGLE_GEMINI:
            chat = ChatGoogleGenerativeAI(
                model="gemini-2.5-flash",
                temperature=0
            )
            
            return chat.bind_tools(tools)
    
        else:
            raise ValueError(f"Unknown LLM provider: {provider}")

    def setup_model(self):
        tavily_search_tool = TavilySearch(
            api_key=os.getenv("TAVILY_API_KEY"),
            max_results=5,
            topic="general",
        )

        # # Define a tool for the agent to use
        tools = [
            multiply,
            add,
            subtract,
            divide,
            modulus,
            wiki_search,
            tavily_search_tool,
            arxiv_search,
        ]
        chat = self.get_chat_with_tools(self.provider, tools)
        
        # Create the ReAct prompt template
        prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),  # Use the new, detailed ReAct prompt
                ("human", "{input}"),
                MessagesPlaceholder(variable_name="agent_scratchpad"),

            ]
        )

        # Create the agent
        agent = create_tool_calling_agent(chat, tools, prompt)

        # Create the agent executor
        return AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)

def update_mode(model):
    csv = CSVSCache()
    df = csv.get_all_entries()
    # Loop over the rows using iterrows() for clear, row-by-row logic.
    i = 0
    for index, row in df.iterrows():
        if row['answer'] == 'unknown':
            question = row['question']
            print(f"Found unknown answer for question: '{question}'")

            # Call the provided LLM function to get the new answer.
            llm_response = model.get_answer(question)

            # Update the DataFrame at the specific row and column.
            # We use .at for efficient single-cell updates.
            df.at[index, 'answer'] = llm_response
            print(f"Updated with new answer: '{llm_response}'")

        if index > 20:
            break

    print("\nProcessing complete.")
    csv.df = df
    csv._save_cache()


def main():
    load_dotenv(find_dotenv())
    csv = CSVSCache()
    df = csv.get_all_entries()
    model = Model(LLMProvider.HUGGINGFACE_LLAMA)
    #update_mode(model)
    test_questions = [0, 6, 10, 12, 15]
    for row in test_questions:
        response = model.get_answer(df.iloc[row]['question'])
        print(f"the output is: {response}")

if __name__ == "__main__":
    main()