3rushi commited on
Commit
117b975
·
verified ·
1 Parent(s): 8a3ecc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -20
app.py CHANGED
@@ -1,33 +1,85 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
- from langchain_core.messages import HumanMessage
7
- from agent import build_graph
8
 
9
- # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
 
14
 
15
- # --- Basic Agent Definition ---
16
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  class BasicAgent:
18
  def __init__(self):
19
- print("BasicAgent initialized.")
20
- self.graph = build_graph(provider="hf")
21
- def __call__(self, question: str) -> str:
22
- print(f"Agent received question (first 50 chars): {question[:50]}...")
23
- result = self.graph.invoke(
24
- {
25
- "messages": [HumanMessage(content=question)]
26
- }
 
 
 
 
 
 
 
 
 
 
 
27
  )
28
- answer = result["messages"][-1].content
29
- return answer.strip()
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def run_and_submit_all( profile: gr.OAuthProfile | None):
32
  """
33
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -155,11 +207,9 @@ with gr.Blocks() as demo:
155
  gr.Markdown(
156
  """
157
  **Instructions:**
158
-
159
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
160
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
161
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
162
-
163
  ---
164
  **Disclaimers:**
165
  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).
@@ -184,8 +234,9 @@ if __name__ == "__main__":
184
  print("\n" + "-"*30 + " App Starting " + "-"*30)
185
  # Check for SPACE_HOST and SPACE_ID at startup for information
186
  space_host_startup = os.getenv("SPACE_HOST")
187
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
188
-
 
189
  if space_host_startup:
190
  print(f"✅ SPACE_HOST found: {space_host_startup}")
191
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import datetime
6
+ from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool, tool
7
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
 
12
 
13
+ @tool
14
+ def get_current_time_in_timezone(timezone: str) -> str:
15
+ """A tool that fetches the current local time in a specified timezone.
16
+ Args:
17
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
18
+ """
19
+ try:
20
+ import pytz
21
+ import datetime
22
+ tz = pytz.timezone(timezone)
23
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
24
+ return f"The current local time in {timezone} is: {local_time}"
25
+ except Exception as e:
26
+ return f"Error fetching time for timezone {timezone}: {str(e)}"
27
+
28
+
29
  class BasicAgent:
30
  def __init__(self):
31
+ # 1. On initialise
32
+ self.search_tool = DuckDuckGoSearchTool()
33
+ self.visit_tool = VisitWebpageTool()
34
+
35
+ # 2. Model Blackbox
36
+ self.model = OpenAIServerModel(
37
+ model_id="blackboxai/google/gemini-3-pro-preview",
38
+ api_base="https://api.blackbox.ai",
39
+ api_key=os.getenv("BB_TOKEN")
40
+ )
41
+
42
+ # 3. On crée l'agent
43
+ self.agent = CodeAgent(
44
+ # On lui donne les 3 outils
45
+ tools=[self.search_tool, self.visit_tool, get_current_time_in_timezone],
46
+ model=self.model,
47
+ add_base_tools=True,
48
+ max_steps=20,
49
+ additional_authorized_imports=["datetime", "math", "re", "statistics", "random", "pandas", "pytz", "itertools"]
50
  )
51
+ print("✅ Agent Blackbox Initialisé avec succès.")
 
52
 
53
+ def __call__(self, question: str) -> str:
54
+ print(f" Question reque: {question}")
55
+
56
+ formatted_prompt = f"""
57
+ Answer this task by providing ONLY the final answer.
58
+
59
+ ### STRATEGY:
60
+ 1. Use 'get_current_time_in_timezone' if the question involves time.
61
+ 2. Use 'search_tool' to find info, then 'visit_tool' to read page details.
62
+ 3. If there is a file (excel/csv), use 'pandas' to read it in your python code.
63
+ 4. Calculate the result precisely using Python.
64
+
65
+ Question: {question}
66
+
67
+ Final Answer:
68
+ """
69
+
70
+ try:
71
+ output = self.agent.run(formatted_prompt)
72
+
73
+ if isinstance(output, dict) and "final_answer" in output:
74
+ return str(output["final_answer"]).strip()
75
+
76
+ return str(output).strip()
77
+
78
+ except Exception as e:
79
+ print(f"❌ Error: {e}")
80
+ return "Error."
81
+
82
+ # --- 4. EXECUTION ---
83
  def run_and_submit_all( profile: gr.OAuthProfile | None):
84
  """
85
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
207
  gr.Markdown(
208
  """
209
  **Instructions:**
 
210
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
211
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
212
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
213
  ---
214
  **Disclaimers:**
215
  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).
 
234
  print("\n" + "-"*30 + " App Starting " + "-"*30)
235
  # Check for SPACE_HOST and SPACE_ID at startup for information
236
  space_host_startup = os.getenv("SPACE_HOST")
237
+ space_id_startup = os.getenv("SPACE_ID")
238
+ BB_TOKEN = os.getenv("BB_TOKEN")# Get SPACE_ID at startup
239
+ print("$$$$$$$$$$$$$$$$$$$$", BB_TOKEN)
240
  if space_host_startup:
241
  print(f"✅ SPACE_HOST found: {space_host_startup}")
242
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")