Bandook01 commited on
Commit
711208d
·
1 Parent(s): 08d52a3

add more tools

Browse files
Files changed (2) hide show
  1. app.py +65 -30
  2. tools.py +18 -3
app.py CHANGED
@@ -3,11 +3,17 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from tools import ReverseTextTool, RunPythonFileTool, download_server
7
  from llama_index.llms.gemini import Gemini
8
  import os
9
  from dotenv import load_dotenv
10
-
 
 
 
 
 
 
11
 
12
 
13
  # (Keep Constants as is)
@@ -35,6 +41,7 @@ Tool Use Guidelines:
35
  9. Due to context length limits, keep browser-based tasks (e.g., searches) as short and efficient as possible.
36
  """
37
 
 
38
  # --- Basic Agent Definition ---
39
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
40
  class BasicAgent:
@@ -43,26 +50,33 @@ class BasicAgent:
43
  if not gemini_api_key:
44
  raise ValueError("GEMINI_API_KEY not set in environment variables.")
45
  llm = Gemini(
46
- model="models/gemini-2.0-flash",
47
- api_key=gemini_api_key,
 
 
 
 
 
48
  )
49
  print("BasicAgent initialized.")
 
50
  def __call__(self, question: str) -> str:
51
  print(f"Agent received question (first 50 chars): {question[:50]}...")
52
  fixed_answer = "This is a default answer."
53
  print(f"Agent returning fixed answer: {fixed_answer}")
54
  return fixed_answer
55
 
56
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
57
  """
58
  Fetches all questions, runs the BasicAgent on them, submits all answers,
59
  and displays the results.
60
  """
61
  # --- Determine HF Space Runtime URL and Repo URL ---
62
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
63
 
64
  if profile:
65
- username= f"{profile.username}"
66
  print(f"User logged in: {username}")
67
  else:
68
  print("User not logged in.")
@@ -89,16 +103,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
89
  response.raise_for_status()
90
  questions_data = response.json()
91
  if not questions_data:
92
- print("Fetched questions list is empty.")
93
- return "Fetched questions list is empty or invalid format.", None
94
  print(f"Fetched {len(questions_data)} questions.")
95
  except requests.exceptions.RequestException as e:
96
  print(f"Error fetching questions: {e}")
97
  return f"Error fetching questions: {e}", None
98
  except requests.exceptions.JSONDecodeError as e:
99
- print(f"Error decoding JSON response from questions endpoint: {e}")
100
- print(f"Response text: {response.text[:500]}")
101
- return f"Error decoding server response for questions: {e}", None
102
  except Exception as e:
103
  print(f"An unexpected error occurred fetching questions: {e}")
104
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -115,18 +129,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
115
  continue
116
  try:
117
  submitted_answer = agent(question_text)
118
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
119
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
120
  except Exception as e:
121
- print(f"Error running agent on task {task_id}: {e}")
122
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
123
 
124
  if not answers_payload:
125
  print("Agent did not produce any answers to submit.")
126
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
127
 
128
- # 4. Prepare Submission
129
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
130
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
131
  print(status_update)
132
 
@@ -196,20 +228,19 @@ with gr.Blocks() as demo:
196
 
197
  run_button = gr.Button("Run Evaluation & Submit All Answers")
198
 
199
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
 
200
  # Removed max_rows=10 from DataFrame constructor
201
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
202
 
203
- run_button.click(
204
- fn=run_and_submit_all,
205
- outputs=[status_output, results_table]
206
- )
207
 
208
  if __name__ == "__main__":
209
- print("\n" + "-"*30 + " App Starting " + "-"*30)
210
  # Check for SPACE_HOST and SPACE_ID at startup for information
211
  space_host_startup = os.getenv("SPACE_HOST")
212
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
213
 
214
  if space_host_startup:
215
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -217,14 +248,18 @@ if __name__ == "__main__":
217
  else:
218
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
219
 
220
- if space_id_startup: # Print repo URLs if SPACE_ID is found
221
  print(f"✅ SPACE_ID found: {space_id_startup}")
222
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
223
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
224
  else:
225
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
226
 
227
- print("-"*(60 + len(" App Starting ")) + "\n")
228
 
229
  print("Launching Gradio Interface for Basic Agent Evaluation...")
230
- demo.launch(debug=True, share=False)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from tools import ReverseTextTool, RunPythonFileTool, download_server, wiki_tool, GetChessPosition
7
  from llama_index.llms.gemini import Gemini
8
  import os
9
  from dotenv import load_dotenv
10
+ from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
11
+ from llama_index.core.agent.workflow import (
12
+ AgentWorkflow,
13
+ ToolCallResult,
14
+ AgentStream,
15
+ ReActAgent,
16
+ )
17
 
18
 
19
  # (Keep Constants as is)
 
41
  9. Due to context length limits, keep browser-based tasks (e.g., searches) as short and efficient as possible.
42
  """
43
 
44
+
45
  # --- Basic Agent Definition ---
46
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
47
  class BasicAgent:
 
50
  if not gemini_api_key:
51
  raise ValueError("GEMINI_API_KEY not set in environment variables.")
52
  llm = Gemini(
53
+ model="models/gemini-2.0-flash",
54
+ api_key=gemini_api_key,
55
+ )
56
+ agent = AgentWorkflow.from_tools_or_functions(
57
+ tools_or_functions=[ReverseTextTool,RunPythonFileTool,download_server,wiki_tool,GetChessPosition],
58
+ llm=llm,
59
+ system_prompt=SYSTEM_PROMPT,
60
  )
61
  print("BasicAgent initialized.")
62
+
63
  def __call__(self, question: str) -> str:
64
  print(f"Agent received question (first 50 chars): {question[:50]}...")
65
  fixed_answer = "This is a default answer."
66
  print(f"Agent returning fixed answer: {fixed_answer}")
67
  return fixed_answer
68
 
69
+
70
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
71
  """
72
  Fetches all questions, runs the BasicAgent on them, submits all answers,
73
  and displays the results.
74
  """
75
  # --- Determine HF Space Runtime URL and Repo URL ---
76
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
77
 
78
  if profile:
79
+ username = f"{profile.username}"
80
  print(f"User logged in: {username}")
81
  else:
82
  print("User not logged in.")
 
103
  response.raise_for_status()
104
  questions_data = response.json()
105
  if not questions_data:
106
+ print("Fetched questions list is empty.")
107
+ return "Fetched questions list is empty or invalid format.", None
108
  print(f"Fetched {len(questions_data)} questions.")
109
  except requests.exceptions.RequestException as e:
110
  print(f"Error fetching questions: {e}")
111
  return f"Error fetching questions: {e}", None
112
  except requests.exceptions.JSONDecodeError as e:
113
+ print(f"Error decoding JSON response from questions endpoint: {e}")
114
+ print(f"Response text: {response.text[:500]}")
115
+ return f"Error decoding server response for questions: {e}", None
116
  except Exception as e:
117
  print(f"An unexpected error occurred fetching questions: {e}")
118
  return f"An unexpected error occurred fetching questions: {e}", None
 
129
  continue
130
  try:
131
  submitted_answer = agent(question_text)
132
+ answers_payload.append(
133
+ {"task_id": task_id, "submitted_answer": submitted_answer}
134
+ )
135
+ results_log.append(
136
+ {
137
+ "Task ID": task_id,
138
+ "Question": question_text,
139
+ "Submitted Answer": submitted_answer,
140
+ }
141
+ )
142
  except Exception as e:
143
+ print(f"Error running agent on task {task_id}: {e}")
144
+ results_log.append(
145
+ {
146
+ "Task ID": task_id,
147
+ "Question": question_text,
148
+ "Submitted Answer": f"AGENT ERROR: {e}",
149
+ }
150
+ )
151
 
152
  if not answers_payload:
153
  print("Agent did not produce any answers to submit.")
154
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
155
 
156
+ # 4. Prepare Submission
157
+ submission_data = {
158
+ "username": username.strip(),
159
+ "agent_code": agent_code,
160
+ "answers": answers_payload,
161
+ }
162
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
163
  print(status_update)
164
 
 
228
 
229
  run_button = gr.Button("Run Evaluation & Submit All Answers")
230
 
231
+ status_output = gr.Textbox(
232
+ label="Run Status / Submission Result", lines=5, interactive=False
233
+ )
234
  # Removed max_rows=10 from DataFrame constructor
235
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
236
 
237
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
238
 
239
  if __name__ == "__main__":
240
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
241
  # Check for SPACE_HOST and SPACE_ID at startup for information
242
  space_host_startup = os.getenv("SPACE_HOST")
243
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
244
 
245
  if space_host_startup:
246
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
248
  else:
249
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
250
 
251
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
252
  print(f"✅ SPACE_ID found: {space_id_startup}")
253
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
254
+ print(
255
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
256
+ )
257
  else:
258
+ print(
259
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
260
+ )
261
 
262
+ print("-" * (60 + len(" App Starting ")) + "\n")
263
 
264
  print("Launching Gradio Interface for Basic Agent Evaluation...")
265
+ demo.launch(debug=True, share=False)
tools.py CHANGED
@@ -1,7 +1,22 @@
1
  from smolagents import PythonInterpreterTool, tool
2
  import requests
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- @tool
5
  def ReverseTextTool(text: str) -> str:
6
  """
7
  Reverses a text string character by character.
@@ -13,7 +28,7 @@ def ReverseTextTool(text: str) -> str:
13
  return text[::-1]
14
 
15
 
16
- @tool
17
  def RunPythonFileTool(file_path: str) -> str:
18
  """
19
  Executes a Python script loaded from the specified path using the PythonInterpreterTool.
@@ -32,7 +47,7 @@ def RunPythonFileTool(file_path: str) -> str:
32
  return f"Execution failed: {e}"
33
 
34
 
35
- @tool
36
  def download_server(url: str, save_path: str) -> str:
37
  """
38
  Downloads a file from a URL and saves it to the given path.
 
1
  from smolagents import PythonInterpreterTool, tool
2
  import requests
3
+ from llama_index.core.agent.workflow import FunctionAgent
4
+ from llama_index.core.tools.tool_spec.load_and_search import (
5
+ LoadAndSearchToolSpec,
6
+ )
7
+ from llama_index.tools.wikipedia import WikipediaToolSpec
8
+ from recognizer import predict_fen
9
+
10
+
11
+
12
+ wiki_spec = WikipediaToolSpec()
13
+ # Get the search wikipedia tool
14
+ wiki_tool = wiki_spec.to_tool_list()[1]
15
+
16
+ def GetChessPosition(file_path:str) -> str:
17
+ fen = predict_fen("../images/chess_image.png")
18
+ return(fen)
19
 
 
20
  def ReverseTextTool(text: str) -> str:
21
  """
22
  Reverses a text string character by character.
 
28
  return text[::-1]
29
 
30
 
31
+
32
  def RunPythonFileTool(file_path: str) -> str:
33
  """
34
  Executes a Python script loaded from the specified path using the PythonInterpreterTool.
 
47
  return f"Execution failed: {e}"
48
 
49
 
50
+
51
  def download_server(url: str, save_path: str) -> str:
52
  """
53
  Downloads a file from a URL and saves it to the given path.