dmvanin commited on
Commit
edf90e0
·
verified ·
1 Parent(s): 81917a3

First commit

Browse files
Files changed (1) hide show
  1. app.py +86 -26
app.py CHANGED
@@ -1,8 +1,13 @@
1
  import os
2
  import gradio as gr
3
- import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -10,14 +15,76 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -40,7 +107,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
@@ -76,11 +143,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
 
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
 
 
 
 
 
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
@@ -142,21 +216,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
142
 
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
- **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
158
- """
159
- )
160
 
161
  gr.LoginButton()
162
 
@@ -193,4 +253,4 @@ if __name__ == "__main__":
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
  print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
 
3
  import inspect
4
  import pandas as pd
5
+ import importlib
6
+ from importlib import resources
7
+ import requests
8
+ import yaml
9
+ import numpy as np
10
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, WikipediaSearchTool, Tool, OpenAIServerModel, SpeechToTextTool
11
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
 
15
 
16
  # --- Basic Agent Definition ---
17
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
+
19
+ class GetTaskFileTool(Tool):
20
+ name = "get_task_file_tool"
21
+ description = """This tool downloads the file content associated with the given task_id if exists. Returns absolute file path"""
22
+ inputs = {
23
+ "task_id": {"type": "string", "description": "Task id"},
24
+ "file_name": {"type": "string", "description": "File name"},
25
+ }
26
+ output_type = "string"
27
+
28
+ def forward(self, task_id: str, file_name: str) -> str:
29
+ response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=15)
30
+ response.raise_for_status()
31
+ with open(file_name, 'wb') as file:
32
+ file.write(response.content)
33
+ return os.path.abspath(file_name)
34
+
35
+ class LoadXlsxFileTool(Tool):
36
+ name = "load_xlsx_file_tool"
37
+ description = """This tool loads xlsx file into pandas and returns it"""
38
+ inputs = {
39
+ "file_path": {"type": "string", "description": "File path"}
40
+ }
41
+ output_type = "object"
42
+
43
+ def forward(self, file_path: str) -> object:
44
+ return pd.read_excel(file_path)
45
+
46
+ class LoadTextFileTool(Tool):
47
+ name = "load_text_file_tool"
48
+ description = """This tool loads any text file"""
49
+ inputs = {
50
+ "file_path": {"type": "string", "description": "File path"}
51
+ }
52
+ output_type = "string"
53
+
54
+ def forward(self, file_path: str) -> object:
55
+ with open(file_path, 'r', encoding='utf-8') as file:
56
+ return file.read()
57
+
58
+ prompts = yaml.safe_load(
59
+ resources.files("smolagents.prompts").joinpath("code_agent.yaml").read_text()
60
+ )
61
+
62
+ prompts["system_prompt"] = ("You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. "
63
+ + prompts["system_prompt"])
64
+
65
+ class DeepseekAgent:
66
  def __init__(self):
67
+ self.__agent = CodeAgent(
68
+ tools=[
69
+ DuckDuckGoSearchTool(),
70
+ VisitWebpageTool(),
71
+ WikipediaSearchTool(),
72
+ GetTaskFileTool(),
73
+ SpeechToTextTool(),
74
+ LoadXlsxFileTool(),
75
+ LoadTextFileTool()
76
+ ],
77
+ model=OpenAIServerModel(
78
+ model_id="deepseek-ai/DeepSeek-R1-0528",
79
+ api_base="https://llm.chutes.ai/v1",
80
+ api_key=os.getenv("CHUTES_API_KEY"),
81
+ temperature=0.6),
82
+ prompt_templates=prompts,
83
+ max_steps=15,
84
+ additional_authorized_imports = ["pandas"]
85
+ )
86
+ def ask_question(self, question):
87
+ return self.__agent.run(question)
88
 
89
  def run_and_submit_all( profile: gr.OAuthProfile | None):
90
  """
 
107
 
108
  # 1. Instantiate Agent ( modify this part to create your agent)
109
  try:
110
+ agent = DeepseekAgent()
111
  except Exception as e:
112
  print(f"Error instantiating agent: {e}")
113
  return f"Error initializing agent: {e}", None
 
143
  for item in questions_data:
144
  task_id = item.get("task_id")
145
  question_text = item.get("question")
146
+ print(question_text)
147
+ file_name = item.get("file_name")
148
  if not task_id or question_text is None:
149
  print(f"Skipping item with missing task_id or question: {item}")
150
  continue
151
  try:
152
+ submitted_answer = agent.ask_question(f"Task id: {task_id}. Task file: {file_name if file_name != '' else 'is absent'}. Task: " + question_text)
153
+ if isinstance(submitted_answer, (np.integer, np.floating)):
154
+ submitted_answer = submitted_answer.item() # Convert NumPy types to Python native types
155
+ elif isinstance(submitted_answer, list):
156
+ submitted_answer = [x.item() if isinstance(x, (np.integer, np.floating)) else x for x in submitted_answer]
157
+ submitted_answer = str(submitted_answer)
158
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
159
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
160
  except Exception as e:
 
216
 
217
  # --- Build Gradio Interface using Blocks ---
218
  with gr.Blocks() as demo:
219
+ gr.Markdown("# Final Assignment: Deepseek Agent, which undergoes certain testing")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  gr.LoginButton()
222
 
 
253
  print("-"*(60 + len(" App Starting ")) + "\n")
254
 
255
  print("Launching Gradio Interface for Basic Agent Evaluation...")
256
+ demo.launch(debug=True, share=False)