pilgrim-65 commited on
Commit
655b11f
·
1 Parent(s): 2f773cf

First commit

Browse files
Files changed (8) hide show
  1. .gitignore +10 -0
  2. agent.py +151 -0
  3. answers.json +1 -0
  4. app.py +216 -0
  5. chess_tool.py +43 -0
  6. logging_config.py +15 -0
  7. requirements.txt +15 -0
  8. tools.py +245 -0
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # secrets
2
+ .env
3
+ # logs
4
+ *.log
5
+ # vscode
6
+ .vscode/
7
+ # Python
8
+ __pycache__
9
+ #files
10
+ files/
agent.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional, TypedDict, Literal
3
+ from langgraph.graph import MessagesState, StateGraph, START, END
4
+ from langgraph.prebuilt import ToolNode
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ from langchain_openai import ChatOpenAI
7
+ from langchain_core.messages import HumanMessage, SystemMessage
8
+ from logging_config import logger
9
+ from tools import (
10
+ python_tool,
11
+ reverse_tool,
12
+ excel_file_to_markdown,
13
+ sum_numbers,
14
+ web_search,
15
+ get_wikipedia_info,
16
+ ask_audio_model
17
+ )
18
+ from chess_tool import chess_tool
19
+
20
+ MAX_ITERATIONS = 5
21
+ SYSTEM_PROMPT = \
22
+ """You are a general AI assistant. This is a GAIA problem to solve, be succinct in your answer.
23
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
24
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless
25
+ specified otherwise.
26
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits
27
+ in plain text unless specified otherwise.
28
+ If you need to access a file, use the provided task_id as a parameter to the corresponding tool, unless a url is provided.
29
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put
30
+ in the list is a number or a string.
31
+ """
32
+
33
+ llm_gemini = ChatGoogleGenerativeAI(
34
+ model="gemini-2.5-flash",
35
+ include_thoughts=False,
36
+ temperature=0,
37
+ max_output_tokens=256,
38
+ timeout=60, # The maximum number of seconds to wait for a response.
39
+ max_retries=2,
40
+ )
41
+
42
+ llm_openai = ChatOpenAI(
43
+ model="openai/gpt-oss-120b:together",
44
+ temperature=0,
45
+ max_tokens=256, # type: ignore
46
+ timeout=60,
47
+ max_retries=2,
48
+ api_key=os.getenv("HF_TOKEN"),
49
+ base_url="https://router.huggingface.co/v1",
50
+ )
51
+
52
+ llm = llm_openai
53
+
54
+ tools = [python_tool,
55
+ reverse_tool,
56
+ excel_file_to_markdown,
57
+ sum_numbers,
58
+ web_search,
59
+ get_wikipedia_info,
60
+ ask_audio_model,
61
+ chess_tool]
62
+
63
+ llm_with_tools = llm.bind_tools(tools)
64
+
65
+ class InputState(TypedDict):
66
+ question: str
67
+ task_id: str
68
+
69
+ # Define the state type with annotations
70
+ class AgentState(MessagesState):
71
+ system_message: str
72
+ question: str
73
+ task_id: str
74
+ final_answer: str
75
+ iterations: int
76
+ error: Optional[str]
77
+
78
+ class OutputState(TypedDict):
79
+ final_answer: str
80
+ error: Optional[str]
81
+
82
+ def input(state: InputState) -> AgentState:
83
+ question = state["question"]
84
+ messages = [
85
+ SystemMessage(content=SYSTEM_PROMPT),
86
+ HumanMessage(content=question)
87
+ ]
88
+ return {"messages": messages, # type: ignore
89
+ "iterations": 0}
90
+
91
+ def agent(state: AgentState) -> AgentState:
92
+ logger.info(f"LLM invoked: {state['question'][:50]=}{state['task_id']=}")
93
+ question = state["question"]
94
+ try:
95
+ result = llm_with_tools.invoke(state["messages"])
96
+ logger.info(f"model metadata = {result.usage_metadata}") # type: ignore
97
+ logger.info(f"LLM answer: {result.content}")
98
+ # Append the new message to the messages list
99
+ messages = state["messages"] + [result]
100
+ return {"messages": messages} # type: ignore
101
+ except Exception as e:
102
+ logger.error(f"LLM invocation failed: {e}")
103
+ return {"error": str(e)} # type: ignore
104
+
105
+ def increment_iterations(state: AgentState) -> AgentState:
106
+ # Additional node to increment the iteration count
107
+ iterations = state.get("iterations", 0) + 1
108
+ return {"iterations": iterations} #type: ignore
109
+
110
+ def route_tools(state: AgentState) -> Literal["tools", "final_output"]:
111
+ """
112
+ Decide if we should continue execution or stop.
113
+ """
114
+ messages = state["messages"]
115
+ ai_message = messages[-1]
116
+ iterations = state["iterations"]
117
+
118
+ if iterations > MAX_ITERATIONS:
119
+ return "final_output" # Stop execution if max iterations are reached
120
+ if hasattr(ai_message, "tool_calls") and len(ai_message.tool_calls) > 0: # type: ignore
121
+ return "tools"
122
+ return "final_output" # Stop execution if no tool calls are present
123
+
124
+ def final_output(state: AgentState) -> OutputState:
125
+ try:
126
+ messages = state["messages"]
127
+ ai_message = messages[-1]
128
+ return {"final_answer": ai_message.content} # type: ignore
129
+ except Exception as e:
130
+ return {"error": e} # type: ignore
131
+
132
+ builder = StateGraph(AgentState)
133
+ tool_node = ToolNode(tools=tools)
134
+ builder.add_node("input", input)
135
+ builder.add_node("agent", agent)
136
+ builder.add_node("increase", increment_iterations)
137
+ builder.add_node("tools", tool_node)
138
+ builder.add_node("final_output", final_output)
139
+ # Define edges for the standard flow
140
+ builder.add_edge(START, "input")
141
+ builder.add_edge("input", "agent")
142
+ builder.add_conditional_edges("agent",
143
+ route_tools,
144
+ {"tools": "increase",
145
+ "final_output": "final_output"}
146
+ )
147
+ builder.add_edge("increase", "tools")
148
+ builder.add_edge("tools", "agent")
149
+ builder.add_edge("final_output", END)
150
+ builder.compile()
151
+ graph = builder.compile()
answers.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [{"task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be", "submitted_answer": "No answer provided"}, {"task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6", "submitted_answer": "No answer provided"}, {"task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0", "submitted_answer": "No answer provided"}, {"task_id": "cca530fc-4052-43b2-b130-b30968d8aa44", "submitted_answer": "No answer provided"}, {"task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8", "submitted_answer": "No answer provided"}, {"task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4", "submitted_answer": "No answer provided"}, {"task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2", "submitted_answer": "No answer provided"}, {"task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91", "submitted_answer": "No answer provided"}, {"task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7", "submitted_answer": "No answer provided"}, {"task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3", "submitted_answer": "No answer provided"}, {"task_id": "305ac316-eef6-4446-960a-92d80d542f82", "submitted_answer": "No answer provided"}, {"task_id": "f918266a-b3e0-4914-865d-4faa564f1aef", "submitted_answer": "No answer provided"}, {"task_id": "3f57289b-8c60-48be-bd80-01f8099ca449", "submitted_answer": "No answer provided"}, {"task_id": "1f975693-876d-457b-a649-393859e79bf3", "submitted_answer": "No answer provided"}, {"task_id": "840bfca7-4f7b-481a-8794-c560c340185d", "submitted_answer": "No answer provided"}, {"task_id": "bda648d7-d618-4883-88f4-3466eabd860e", "submitted_answer": "No answer provided"}, {"task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d", "submitted_answer": "No answer provided"}, {"task_id": "a0c07678-e491-4bbc-8f0b-07405144218f", "submitted_answer": "No answer provided"}, {"task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733", "submitted_answer": "No answer provided"}, {"task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d", "submitted_answer": "No answer provided"}]
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ import json
7
+ from logging_config import logger # Import the shared logger
8
+
9
+ # (Keep Constants as is)
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+ # --- Basic Agent Definition ---
14
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
+ # --- Basic Agent Definition ---
16
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
+ class BasicAgent:
18
+ def __init__(self):
19
+ from agent import graph # Importing here to avoid circular imports
20
+ print("BasicAgent initialized.")
21
+ self.graph = graph
22
+ def __call__(self, item: dict) -> str:
23
+ """Process the input item and return a response.
24
+ Args:
25
+ item (dict): Input dictionary containing the question.
26
+ """
27
+ question = item.get("question", "")
28
+ task_id = item.get("task_id", "")
29
+ file_name = item.get("file_name", "")
30
+ if file_name:
31
+ # file_name provided, adding task_id to question for context
32
+ question += f"\nTask ID: {task_id}"
33
+ logger.info(f"Agent received question (first 50 chars): {question[:50]}...")
34
+ # fixed_answer = "This is a default answer."
35
+ # print(f"Agent returning fixed answer: {fixed_answer}")
36
+ answer = self.graph.invoke({"question": question, "task_id": task_id})
37
+ return answer.get("final_answer", "No answer generated.") # type: ignore
38
+
39
+ def run_all(profile: gr.OAuthProfile | None):
40
+ """
41
+ Fetches all questions, runs the BasicAgent on them caching all answers,
42
+ and displays the results.
43
+ """
44
+ # --- Determine HF Space Runtime URL and Repo URL ---
45
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
46
+
47
+ if profile:
48
+ username= f"{profile.username}"
49
+ print(f"User logged in: {username}")
50
+ else:
51
+ print("User not logged in.")
52
+ return "Please Login to Hugging Face with the button.", None
53
+
54
+ api_url = DEFAULT_API_URL
55
+ questions_url = f"{api_url}/questions"
56
+ submit_url = f"{api_url}/submit"
57
+
58
+ # 1. Instantiate Agent ( modify this part to create your agent)
59
+ try:
60
+ agent = BasicAgent()
61
+ except Exception as e:
62
+ print(f"Error instantiating agent: {e}")
63
+ return f"Error initializing agent: {e}", None
64
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
65
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
66
+ print(agent_code)
67
+
68
+ # 2. Fetch Questions
69
+ print(f"Fetching questions from: {questions_url}")
70
+ try:
71
+ response = requests.get(questions_url, timeout=15)
72
+ response.raise_for_status()
73
+ questions_data = response.json()
74
+ if not questions_data:
75
+ print("Fetched questions list is empty.")
76
+ return "Fetched questions list is empty or invalid format.", None
77
+ print(f"Fetched {len(questions_data)} questions.")
78
+ except requests.exceptions.RequestException as e:
79
+ print(f"Error fetching questions: {e}")
80
+ return f"Error fetching questions: {e}", None
81
+ except requests.exceptions.JSONDecodeError as e: # type: ignore
82
+ print(f"Error decoding JSON response from questions endpoint: {e}")
83
+ print(f"Response text: {response.text[:500]}") # type: ignore
84
+ return f"Error decoding server response for questions: {e}", None
85
+ except Exception as e:
86
+ print(f"An unexpected error occurred fetching questions: {e}")
87
+ return f"An unexpected error occurred fetching questions: {e}", None
88
+
89
+ # 3. Run your Agent
90
+ results_log = []
91
+ answers_payload = []
92
+ print(f"Running agent on {len(questions_data)} questions...")
93
+ for item in questions_data:
94
+ task_id = item.get("task_id")
95
+ question_text = item.get("question")
96
+ if not task_id or question_text is None:
97
+ print(f"Skipping item with missing task_id or question: {item}")
98
+ continue
99
+ try:
100
+ submitted_answer = agent(question_text)
101
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
102
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
103
+ except Exception as e:
104
+ print(f"Error running agent on task {task_id}: {e}")
105
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
106
+
107
+ if not answers_payload:
108
+ print("Agent did not produce any answers to submit.")
109
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
110
+
111
+ # 4. Prepare Submission
112
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
113
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
114
+ print(status_update)
115
+
116
+ # 5. Submit
117
+ def submit_all(profile: gr.OAuthProfile | None):
118
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
119
+ try:
120
+ response = requests.post(submit_url, json=submission_data, timeout=60)
121
+ response.raise_for_status()
122
+ result_data = response.json()
123
+ final_status = (
124
+ f"Submission Successful!\n"
125
+ f"User: {result_data.get('username')}\n"
126
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
127
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
+ f"Message: {result_data.get('message', 'No message received.')}"
129
+ )
130
+ print("Submission successful.")
131
+ results_df = pd.DataFrame(results_log)
132
+ return final_status, results_df
133
+ except requests.exceptions.HTTPError as e:
134
+ error_detail = f"Server responded with status {e.response.status_code}."
135
+ try:
136
+ error_json = e.response.json()
137
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
138
+ except requests.exceptions.JSONDecodeError:
139
+ error_detail += f" Response: {e.response.text[:500]}"
140
+ status_message = f"Submission Failed: {error_detail}"
141
+ print(status_message)
142
+ results_df = pd.DataFrame(results_log)
143
+ return status_message, results_df
144
+ except requests.exceptions.Timeout:
145
+ status_message = "Submission Failed: The request timed out."
146
+ print(status_message)
147
+ results_df = pd.DataFrame(results_log)
148
+ return status_message, results_df
149
+ except requests.exceptions.RequestException as e:
150
+ status_message = f"Submission Failed: Network error - {e}"
151
+ print(status_message)
152
+ results_df = pd.DataFrame(results_log)
153
+ return status_message, results_df
154
+ except Exception as e:
155
+ status_message = f"An unexpected error occurred during submission: {e}"
156
+ print(status_message)
157
+ results_df = pd.DataFrame(results_log)
158
+ return status_message, results_df
159
+
160
+
161
+ # --- Build Gradio Interface using Blocks ---
162
+ with gr.Blocks() as demo:
163
+ gr.Markdown("# Basic Agent Evaluation Runner")
164
+ gr.Markdown(
165
+ """
166
+ **Instructions:**
167
+
168
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
169
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
170
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
171
+
172
+ ---
173
+ **Disclaimers:**
174
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
175
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
176
+ For instance for the delay process of the submit button, a solution could be to cache the answers and submit
177
+ in a seperate action or even to answer the questions in async.
178
+ """
179
+ )
180
+
181
+ gr.LoginButton()
182
+
183
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
184
+
185
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
186
+ # Removed max_rows=10 from DataFrame constructor
187
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
188
+
189
+ run_button.click(
190
+ fn=submit_all,
191
+ outputs=[status_output, results_table]
192
+ )
193
+
194
+ if __name__ == "__main__":
195
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
196
+ # Check for SPACE_HOST and SPACE_ID at startup for information
197
+ space_host_startup = os.getenv("SPACE_HOST")
198
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
199
+
200
+ if space_host_startup:
201
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
202
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
203
+ else:
204
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
205
+
206
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
207
+ print(f"✅ SPACE_ID found: {space_id_startup}")
208
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
209
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
210
+ else:
211
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
212
+
213
+ print("-"*(60 + len(" App Starting ")) + "\n")
214
+
215
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
216
+ demo.launch(debug=True, share=False)
chess_tool.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from chessimg2pos import predict_fen
2
+ from stockfish import Stockfish
3
+ from langchain_core.tools import tool
4
+ from logging_config import logger # Import the shared logger
5
+
6
+ # Adapted from Alberto Formaggio's GAIA agents
7
+ # https://github.com/AlbertoFormaggio1/gaia-ai-agents/blob/main/tools/chess_tool.py
8
+
9
+ @tool
10
+ def chess_tool(task_id: str, color_to_move: str) -> str:
11
+ """
12
+ Given an image of a chessboard, and the color to move,
13
+ predict the FEN notation and suggest the best move.
14
+
15
+ Args:
16
+ task_id (str): The identifier for the chessboard image.
17
+ color_to_move (str): 'w' or 'b', the color to move ('white' or 'black').
18
+
19
+ Returns:
20
+ str: Best move suggestion.
21
+ """
22
+ logger.info(f"Invoking chess tool with task_id: {task_id!r} and color_to_move: {color_to_move!r}")
23
+
24
+ if color_to_move not in ['w', 'b']:
25
+ return "Error: color_to_move must be 'w' or 'b'."
26
+
27
+ predicted_fen = predict_fen(f'./files/{task_id}.png', output_type='simple')
28
+
29
+ if color_to_move == 'b':
30
+ rows = reversed(predicted_fen.split('/'))
31
+ board = '/'.join([row[::-1] for row in rows])
32
+ elif color_to_move == 'w':
33
+ board = predicted_fen
34
+
35
+ fen = f"{board} {color_to_move} -- 0 1"
36
+
37
+ # Initialize Stockfish engine (ensure the path to executable is correct)
38
+ stockfish = Stockfish(path="/home/jmlv/engines/stockfish/stockfish")
39
+ stockfish.set_fen_position(fen)
40
+ best_move = stockfish.get_best_move()
41
+ logger.info(f"Best move determined: {best_move!r}")
42
+
43
+ return best_move
logging_config.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from logging.handlers import RotatingFileHandler
3
+
4
+ # Set up logging
5
+ #logging.basicConfig(level=logging.INFO)
6
+ logger = logging.getLogger(__name__)
7
+ logger.setLevel(logging.DEBUG)
8
+ if not logger.hasHandlers():
9
+ rotation_handler = RotatingFileHandler("app.log", maxBytes=1048576, backupCount=1)
10
+ console_handler = logging.StreamHandler()
11
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
12
+ rotation_handler.setFormatter(formatter)
13
+ console_handler.setFormatter(formatter)
14
+ logger.addHandler(rotation_handler)
15
+ logger.addHandler(console_handler)
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ beautifulsoup4==4.13.5
2
+ chessimg2pos==0.1.4
3
+ gradio==5.47.0
4
+ langchain_community==0.3.29
5
+ langchain_core==0.3.76
6
+ langchain_experimental==0.3.4
7
+ langchain_google_genai==2.1.12
8
+ langchain_openai==0.3.33
9
+ langchain_tavily==0.2.11
10
+ langgraph==0.6.7
11
+ pandas==2.3.2
12
+ python-dotenv==1.1.1
13
+ Requests==2.32.5
14
+ stockfish==3.28.0
15
+ wikipedia==1.4.0
tools.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from io import StringIO
3
+ import re
4
+ import base64
5
+ from langchain_core.tools import tool
6
+ from langchain_tavily import TavilySearch
7
+ from langchain_experimental.utilities import PythonREPL
8
+ from langchain_community.retrievers import WikipediaRetriever
9
+ from langchain_google_genai import ChatGoogleGenerativeAI
10
+ from langchain_core.messages import HumanMessage
11
+ from typing import List
12
+ import wikipedia
13
+ from bs4 import BeautifulSoup, Tag
14
+ import json
15
+ import pandas as pd
16
+ from logging_config import logger # Import the shared logger
17
+ from dotenv import load_dotenv
18
+ load_dotenv()
19
+
20
+ @tool
21
+ def python_tool(code: str) -> str:
22
+ """A Python shell. Use this to execute python commands.
23
+ Input should be an str with a valid python script.
24
+ If you want to see the output of a value,
25
+ you should print it out with `print(...)`."""
26
+
27
+ logger.info(f"Invoking Python REPL tool{code!r}")
28
+ repl = PythonREPL()
29
+ try:
30
+ # print("Running the Python REPL tool")
31
+ # print(code)
32
+ result = repl.run(code)
33
+ except BaseException as e:
34
+ return f"Failed to execute. Error: {e!r}"
35
+ return f"Result of code execution: {result}"
36
+
37
+ @tool
38
+ def reverse_tool(question: str) -> str:
39
+ """Reverses the input string."""
40
+ logger.info(f"Invoking reverse tool with question: {question!r}")
41
+ return question[::-1]
42
+
43
+ @tool
44
+ def excel_file_to_markdown(task_id):
45
+ """Given a task_id corresponding to an Excel file,
46
+ fetch the file and convert its content to markdown format."""
47
+ import pandas as pd
48
+
49
+ path = f"./files/{task_id}.xlsx"
50
+ df = pd.read_excel(path)
51
+ logger.info(f"Converted Excel file {path} to markdown")
52
+ return df.to_markdown()
53
+
54
+ @tool
55
+ def sum_numbers(all_numbers: List[float]) -> float:
56
+ """
57
+ Sums a list of numbers and returns the result.
58
+
59
+ Args:
60
+ all_numbers ('list' of float): A list of numbers.
61
+
62
+ """
63
+ logger.info(f"Summing numbers: {all_numbers}")
64
+ numbers_list = [float(x) for x in all_numbers]
65
+ result = sum(numbers_list)
66
+ return result
67
+
68
+ @tool
69
+ def web_search(question: str) -> str: # Tool expects arguments, not the whole state
70
+ """Perform a web search using TavilySearch and return relevant documents.
71
+ Args:
72
+ question (str): The query for the web search.
73
+ Returns:
74
+ web_search_result (str): The result of the web search.
75
+ """
76
+ logger.info(f"Performing web search for query: {question}")
77
+
78
+ web_tool = TavilySearch(chunks_per_source=3,
79
+ max_results=3,
80
+ include_answer=True,
81
+ include_raw_content="markdown",
82
+ search_depth="advanced"
83
+ )
84
+ try:
85
+ search_results = web_tool.invoke(question)
86
+ logger.info(f"Web search completed with {len(search_results.get('results', []))} results")
87
+ if search_results.get('answer'):
88
+ logger.info(f"Web search answer length: {len(search_results['answer'])}")
89
+ return search_results['answer'] # type: ignore
90
+ retrieved_docs = [{"url": sr.get('url', ""), "content": sr.get('content', "")} \
91
+ for sr in search_results.get('results', [])]
92
+ web_search_result = json.dumps(retrieved_docs, indent=2)
93
+ return web_search_result # type: ignore
94
+
95
+ except Exception as e:
96
+ logger.error(f"Web search failed: {e}")
97
+ # Return an empty list or specific error document if the search fails
98
+ return f"Web search failed: {e}"
99
+
100
+ # This tool is not needed for the assignment???
101
+ @tool
102
+ def wiki_search(query: str) -> str:
103
+ """Search Wikipedia for query and return maximum 2 results
104
+
105
+ Args:
106
+ query (str): query to search on Wikipedia
107
+ Returns:
108
+ wiki_result (str): result of search
109
+ """
110
+ try:
111
+ retriever = WikipediaRetriever(top_k_results=2, doc_content_chars_max=20000) # type: ignore
112
+ docs = retriever.invoke(query)
113
+ wiki_result = "\n".join([f"- {doc.page_content} (source: {doc.metadata.get('source', 'unknown')})" for doc in docs])
114
+ url = docs[0].metadata.get('source', 'unknown') if docs else 'unknown'
115
+
116
+ logger.info(f"Wikipedia search completed for query: {query} with length {len(wiki_result)}")
117
+ return wiki_result # type: ignore
118
+ except Exception as e:
119
+ return f"wiki_search failed {e}"
120
+
121
+ @tool
122
+ def get_wikipedia_info(query: str) -> str:
123
+ """
124
+ Fetches and parses all HTML tables and their preceding Hx headers
125
+ from a given Wikipedia page.
126
+ Use this to get structured data from Wikipedia pages, such as lists of items,
127
+ tables of statistics, discographies, etc.
128
+ Args:
129
+ query (str): The query to search on Wikipedia.
130
+ Returns:
131
+ formatted_output (str): a string representation of the structured data,
132
+ formatted in a Markdown-like style.
133
+ """
134
+ logger.info(f"Tool get_wikipedia_info invoked with query: {query!r}")
135
+ try:
136
+ page_title = wikipedia.search(query, results=1)[0]
137
+ page_content = wikipedia.page(page_title, auto_suggest=False).html()
138
+ logger.info(f"Fetching Wikipedia page for title: {page_title!r}")
139
+ soup = BeautifulSoup(page_content, 'html.parser')
140
+
141
+ # main_content = soup.find('div', {'id': 'mw-content-text'})
142
+ # if not main_content:
143
+ # return "Could not find the main content area on the page."
144
+
145
+ # Compile a regular expression for h1 to h6 tags
146
+ heading_pattern = re.compile('^h[1-6]$')
147
+
148
+ # Find all headings and tables in one pass
149
+ elements = soup.find_all([heading_pattern, 'table'])
150
+
151
+ extracted_data = []
152
+ current_headers = {} # Using a dictionary for flexibility
153
+
154
+ for element in elements:
155
+ if isinstance(element, Tag):
156
+ if re.match(heading_pattern, element.name):
157
+ current_headers[element.name] = element.get_text().strip()
158
+ # Reset lower-level headers when a higher-level one is found
159
+ for i in range(int(element.name[1]) + 1, 7):
160
+ current_headers.pop(f'h{i}', None)
161
+ elif element.name == 'table' and 'wikitable' in element.get('class', []): # type: ignore
162
+ try:
163
+ df = pd.read_html(StringIO(str(element)))[0] # type: ignore
164
+ table_info = {
165
+ 'headers': current_headers.copy(),
166
+ 'table_data': df.to_markdown()
167
+ }
168
+ extracted_data.append(table_info)
169
+ except ValueError:
170
+ continue
171
+
172
+ if not extracted_data:
173
+ return "No 'wikitable' found on the specified page."
174
+
175
+ # Format the extracted data into a readable, markdown string
176
+ formatted_output = "### Extracted Tables with Headers\n\n"
177
+
178
+ for i, item in enumerate(extracted_data):
179
+ formatted_output += f"--- Table {i+1} ---\n"
180
+
181
+ # Sort headers by level (h1, h2, h3...) to ensure correct order
182
+ sorted_headers = sorted(item['headers'].items(), key=lambda x: int(x[0][1]))
183
+
184
+ for header_tag, header_text in sorted_headers:
185
+ header_level = len(header_tag)
186
+ formatted_output += f"{'#' * (header_level + 2)} {header_text}\n"
187
+
188
+ formatted_output += f"```\n{item['table_data']}\n```\n\n"
189
+
190
+ return formatted_output
191
+
192
+ except wikipedia.exceptions.PageError:
193
+ return "Wikipedia page not found."
194
+ except Exception as e:
195
+ return f"An error occurred: {e}"
196
+
197
+
198
+ @tool
199
+ def ask_audio_model(query: str, task_id: str) -> str:
200
+ """
201
+ Processes an audio query by sending both a text prompt and an task_id
202
+ (associated with an audio file)
203
+ to a generative AI model, and returns the model's response.
204
+
205
+ Args:
206
+ query (str): The text prompt or question for the model.
207
+ task_id (str): The identifier used to load the audio file (MP3) in the downloaded files directory.
208
+
209
+ Returns:
210
+ str: The response generated by the AI model based on the provided text and audio.
211
+ """
212
+
213
+ logger.info(f"audio_model called with query='{query[:30]}...'")
214
+
215
+ if "GOOGLE_API_KEY" not in os.environ:
216
+ os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
217
+
218
+ llm = ChatGoogleGenerativeAI(
219
+ model="gemini-2.5-flash-lite-preview-06-17",
220
+ temperature=0,
221
+ max_tokens=None,
222
+ timeout=60, # Added a timeout
223
+ max_retries=2,
224
+ )
225
+
226
+ audio_file_path = f"./files/{task_id}.mp3" # Assuming MP3 for a general use case
227
+
228
+ audio_mime_type = "audio/mpeg"
229
+
230
+ with open(audio_file_path, "rb") as audio_file:
231
+ encoded_audio = base64.b64encode(audio_file.read()).decode("utf-8")
232
+
233
+ message = HumanMessage(
234
+ content=[
235
+ {"type": "text", "text": query},
236
+ {
237
+ "type": "media",
238
+ "data": encoded_audio, # Use base64 string directly
239
+ "mime_type": audio_mime_type,
240
+ },
241
+ ]
242
+ )
243
+ response = llm.invoke([message])
244
+ logger.info(f"ask_audio_model metadata = {response.usage_metadata}") # type: ignore
245
+ return response.content # type: ignore