simonesarti commited on
Commit
61ad317
·
1 Parent(s): 3b24931
Files changed (4) hide show
  1. .gitignore +1 -0
  2. app.py +7 -12
  3. app_local.py +169 -0
  4. requirements.txt +0 -2
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .env
app.py CHANGED
@@ -2,10 +2,8 @@ import os
2
  import gradio as gr
3
  import requests
4
  import inspect
 
5
  import pandas as pd
6
- from smolagents import InferenceClientModel, CodeAgent, Tool, DuckDuckGoSearchTool, VisitWebpageTool, PythonInterpreterTool
7
-
8
-
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
@@ -15,25 +13,22 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
  class BasicAgent:
17
  def __init__(self):
18
-
19
  tools = [
20
  VisitWebpageTool(),
21
  DuckDuckGoSearchTool(),
22
- # PythonInterpreterTool(),
23
- # PythonInterpreterTool(),
24
  ]
25
 
26
- model = InferenceClientModel(
27
- model="Qwen/Qwen2.5-Coder-32B-Instruct",
28
- )
29
 
30
  self.agent = CodeAgent(
31
  model=model,
32
  tools=tools,
33
- additional_authorizesd_imports=["requests", "json", "re", "math", "numpy", "pandas", "datetime", "time", "random", "os", "sys"],
34
- planning_interval=4,
35
- max_steps=15,
36
  verbosity_level=2,
 
37
  )
38
 
39
  print("BasicAgent initialized.")
 
2
  import gradio as gr
3
  import requests
4
  import inspect
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, InferenceClientModel, PythonInterpreterTool
6
  import pandas as pd
 
 
 
7
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
 
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
  class BasicAgent:
15
  def __init__(self):
 
16
  tools = [
17
  VisitWebpageTool(),
18
  DuckDuckGoSearchTool(),
19
+ PythonInterpreterTool(),
 
20
  ]
21
 
22
+ model = InferenceClientModel()
 
 
23
 
24
  self.agent = CodeAgent(
25
  model=model,
26
  tools=tools,
27
+ additional_authorized_imports=["requests", "json", "re", "math", "numpy", "pandas", "datetime", "time", "random", "os", "sys"],
28
+ planning_interval=5,
29
+ max_steps=8,
30
  verbosity_level=2,
31
+ add_base_tools=True,
32
  )
33
 
34
  print("BasicAgent initialized.")
app_local.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import pandas as pd
4
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, LiteLLMModel, PythonInterpreterTool
5
+ # from smolagents import InferenceClientModel, Tool, PythonInterpreterTool
6
+ from huggingface_hub import HfApi, login
7
+
8
+
9
+
10
+ # (Keep Constants as is)
11
+ # --- Constants ---
12
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+
14
+ # --- Basic Agent Definition ---
15
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
+ class BasicAgent:
17
+ def __init__(self):
18
+
19
+ tools = [
20
+ VisitWebpageTool(),
21
+ DuckDuckGoSearchTool(),
22
+ PythonInterpreterTool(),
23
+ ]
24
+
25
+ model = LiteLLMModel(
26
+ model_id="ollama_chat/qwen-coder:30b",
27
+ api_base="http://127.0.0.1:11434",
28
+ )
29
+
30
+ self.agent = CodeAgent(
31
+ model=model,
32
+ tools=tools,
33
+ additional_authorized_imports=["requests", "json", "re", "math", "numpy", "pandas", "datetime", "time", "random", "os", "sys"],
34
+ planning_interval=5,
35
+ max_steps=8,
36
+ verbosity_level=2,
37
+ add_base_tools=True,
38
+ )
39
+
40
+ print("BasicAgent initialized.")
41
+ def __call__(self, question: str) -> str:
42
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
43
+ response = self.agent.run(question)
44
+ print(f"Agent returning response: {response}")
45
+ return response
46
+
47
+ def run_and_submit_all():
48
+ """
49
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
50
+ and displays the results.
51
+ """
52
+ # Step 1: Log in with your User Access Token
53
+ # (You can also run `huggingface-cli login` in your terminal instead of doing it in Python)
54
+ login(token=os.environ.get("HF_TOKEN"))
55
+
56
+ # Step 2: Initialize the API client and fetch user info
57
+ api = HfApi()
58
+ user_info = api.whoami()
59
+
60
+ # Step 3: Get the username
61
+ username = user_info["name"]
62
+ print(f"Logged in as: {username}")
63
+
64
+ api_url = DEFAULT_API_URL
65
+ questions_url = f"{api_url}/questions"
66
+ submit_url = f"{api_url}/submit"
67
+
68
+ agent_code = f"https://huggingface.co/spaces/{os.environ.get('HF_SPACE')}/tree/main"
69
+
70
+ # 1. Instantiate Agent ( modify this part to create your agent)
71
+ try:
72
+ agent = BasicAgent()
73
+ except Exception as e:
74
+ print(f"Error instantiating agent: {e}")
75
+ return f"Error initializing agent: {e}", None
76
+
77
+ # 2. Fetch Questions
78
+ print(f"Fetching questions from: {questions_url}")
79
+ try:
80
+ response = requests.get(questions_url, timeout=15)
81
+ response.raise_for_status()
82
+ questions_data = response.json()
83
+ if not questions_data:
84
+ print("Fetched questions list is empty.")
85
+ return "Fetched questions list is empty or invalid format.", None
86
+ print(f"Fetched {len(questions_data)} questions.")
87
+ except requests.exceptions.RequestException as e:
88
+ print(f"Error fetching questions: {e}")
89
+ return f"Error fetching questions: {e}", None
90
+ except requests.exceptions.JSONDecodeError as e:
91
+ print(f"Error decoding JSON response from questions endpoint: {e}")
92
+ print(f"Response text: {response.text[:500]}")
93
+ return f"Error decoding server response for questions: {e}", None
94
+ except Exception as e:
95
+ print(f"An unexpected error occurred fetching questions: {e}")
96
+ return f"An unexpected error occurred fetching questions: {e}", None
97
+
98
+ # 3. Run your Agent
99
+ results_log = []
100
+ answers_payload = []
101
+ print(f"Running agent on {len(questions_data)} questions...")
102
+ for item in questions_data:
103
+ task_id = item.get("task_id")
104
+ question_text = item.get("question")
105
+ if not task_id or question_text is None:
106
+ print(f"Skipping item with missing task_id or question: {item}")
107
+ continue
108
+ try:
109
+ submitted_answer = agent(question_text)
110
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
111
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
112
+ except Exception as e:
113
+ print(f"Error running agent on task {task_id}: {e}")
114
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
115
+
116
+ if not answers_payload:
117
+ print("Agent did not produce any answers to submit.")
118
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
119
+
120
+ # 4. Prepare Submission
121
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
122
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
123
+ print(status_update)
124
+
125
+ # 5. Submit
126
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
127
+ try:
128
+ response = requests.post(submit_url, json=submission_data, timeout=60)
129
+ response.raise_for_status()
130
+ result_data = response.json()
131
+ final_status = (
132
+ f"Submission Successful!\n"
133
+ f"User: {result_data.get('username')}\n"
134
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
135
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
136
+ f"Message: {result_data.get('message', 'No message received.')}"
137
+ )
138
+ print("Submission successful.")
139
+ results_df = pd.DataFrame(results_log)
140
+ return final_status, results_df
141
+ except requests.exceptions.HTTPError as e:
142
+ error_detail = f"Server responded with status {e.response.status_code}."
143
+ try:
144
+ error_json = e.response.json()
145
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
146
+ except requests.exceptions.JSONDecodeError:
147
+ error_detail += f" Response: {e.response.text[:500]}"
148
+ status_message = f"Submission Failed: {error_detail}"
149
+ print(status_message)
150
+ results_df = pd.DataFrame(results_log)
151
+ return status_message, results_df
152
+ except requests.exceptions.Timeout:
153
+ status_message = "Submission Failed: The request timed out."
154
+ print(status_message)
155
+ results_df = pd.DataFrame(results_log)
156
+ return status_message, results_df
157
+ except requests.exceptions.RequestException as e:
158
+ status_message = f"Submission Failed: Network error - {e}"
159
+ print(status_message)
160
+ results_df = pd.DataFrame(results_log)
161
+ return status_message, results_df
162
+ except Exception as e:
163
+ status_message = f"An unexpected error occurred during submission: {e}"
164
+ print(status_message)
165
+ results_df = pd.DataFrame(results_log)
166
+ return status_message, results_df
167
+
168
+ if __name__ == "__main__":
169
+ run_and_submit_all()
requirements.txt DELETED
@@ -1,2 +0,0 @@
1
- gradio
2
- requests