Ilol commited on
Commit
b8ab5ba
·
verified ·
1 Parent(s): 6645c16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -11
app.py CHANGED
@@ -1,8 +1,12 @@
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 +14,86 @@ 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 +116,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 +152,12 @@ 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:
 
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
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, WikipediaSearchTool, Tool, OpenAIServerModel, SpeechToTextTool
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
 
14
 
15
  # --- Basic Agent Definition ---
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
+
18
+
19
+
20
+
21
+
22
+ class GetTaskFileTool(Tool):
23
+ name = "get_task_file_tool"
24
+ description = """This tool downloads the file content associated with the given task_id if exists. Returns absolute file path"""
25
+ inputs = {
26
+ "task_id": {"type": "string", "description": "Task id"},
27
+ "file_name": {"type": "string", "description": "File name"},
28
+ }
29
+ output_type = "string"
30
+
31
+ def forward(self, task_id: str, file_name: str) -> str:
32
+ response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=15)
33
+ response.raise_for_status()
34
+ with open(file_name, 'wb') as file:
35
+ file.write(response.content)
36
+ return os.path.abspath(file_name)
37
+
38
+ class LoadXlsxFileTool(Tool):
39
+ name = "load_xlsx_file_tool"
40
+ description = """This tool loads xlsx file into pandas and returns it"""
41
+ inputs = {
42
+ "file_path": {"type": "string", "description": "File path"}
43
+ }
44
+ output_type = "object"
45
+
46
+ def forward(self, file_path: str) -> object:
47
+ return pd.read_excel(file_path)
48
+
49
+ class LoadTextFileTool(Tool):
50
+ name = "load_text_file_tool"
51
+ description = """This tool loads any text file"""
52
+ inputs = {
53
+ "file_path": {"type": "string", "description": "File path"}
54
+ }
55
+ output_type = "string"
56
+
57
+ def forward(self, file_path: str) -> object:
58
+ with open(file_path, 'r', encoding='utf-8') as file:
59
+ return file.read()
60
+
61
+ prompts = yaml.safe_load(
62
+ resources.files("smolagents.prompts").joinpath("code_agent.yaml").read_text()
63
+ )
64
+
65
+ 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. "
66
+ + prompts["system_prompt"])
67
+
68
+ def init_agent():
69
+ gemini_model = OpenAIServerModel(
70
+ model_id="deepseek-ai/DeepSeek-R1-0528",
71
+ api_base="https://llm.chutes.ai/v1",
72
+ api_key=os.getenv("API_KEY"),
73
+ temperature=0.7
74
+ )
75
+ agent = CodeAgent(
76
+ tools=[
77
+ DuckDuckGoSearchTool(),
78
+ VisitWebpageTool(),
79
+ WikipediaSearchTool(),
80
+ GetTaskFileTool(),
81
+ SpeechToTextTool(),
82
+ LoadXlsxFileTool(),
83
+ LoadTextFileTool()
84
+ ],
85
+ model=gemini_model,
86
+ prompt_templates=prompts,
87
+ max_steps=15,
88
+ additional_authorized_imports = ["pandas"]
89
+ )
90
+ return agent
91
+
92
+
93
+
94
+
95
+
96
+
97
 
98
  def run_and_submit_all( profile: gr.OAuthProfile | None):
99
  """
 
116
 
117
  # 1. Instantiate Agent ( modify this part to create your agent)
118
  try:
119
+ agent = init_agent()
120
  except Exception as e:
121
  print(f"Error instantiating agent: {e}")
122
  return f"Error initializing agent: {e}", None
 
152
  for item in questions_data:
153
  task_id = item.get("task_id")
154
  question_text = item.get("question")
155
+ file_name = item.get("file_name")
156
  if not task_id or question_text is None:
157
  print(f"Skipping item with missing task_id or question: {item}")
158
  continue
159
  try:
160
+ submitted_answer = agent.run(f"Task id: {task_id}. Task file: {file_name if file_name != '' else 'is absent'}. Task: " + question_text)
161
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
162
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
163
  except Exception as e: