kpbotla commited on
Commit
1accc82
·
verified ·
1 Parent(s): 81917a3

Upload 7 files

Browse files
Files changed (7) hide show
  1. README.md +1 -1
  2. agent.py +53 -0
  3. app.py +17 -12
  4. env.example +3 -0
  5. gitattributes +35 -0
  6. requirements.txt +5 -1
  7. tools.py +78 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Template Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
 
1
  ---
2
+ title: Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
agent.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import os
4
+ from smolagents import DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool, LiteLLMModel
5
+ from tools import DownloadTaskAttachmentTool, VisitWebpageTool
6
+
7
+
8
+ class MyAgent:
9
+ def __init__(self):
10
+ self.agent = CodeAgent(
11
+ model=LiteLLMModel(model_id="openrouter/meta-llama/llama-4-maverick:free", api_key=os.getenv("OPENROUTER_KEY")),
12
+ tools=[DuckDuckGoSearchTool(), WikipediaSearchTool(), VisitWebpageTool(), DownloadTaskAttachmentTool()],
13
+ add_base_tools=True,
14
+ additional_authorized_imports=['pandas', 'numpy', 'csv', 'subprocess', 'exec']
15
+ )
16
+ print("MyAgent initialized.")
17
+
18
+ def __call__(self, question: str) -> str:
19
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
20
+ agent_answer = self.agent.run(question)
21
+ print(f"Agent answer: {agent_answer}")
22
+ return agent_answer
23
+
24
+ def download_file(self, task_id: str) -> str:
25
+ """
26
+ Downloads a file associated with the given task ID.
27
+ Returns the file path where the file is saved locally.
28
+ """
29
+ file_url = f"{DEFAULT_API_URL}/files/{task_id}"
30
+ local_file_path = f"downloads/{task_id}.file"
31
+
32
+ print(f"Downloading file for task ID {task_id} from {file_url}...")
33
+ try:
34
+ response = requests.get(file_url, stream=True, timeout=15)
35
+ response.raise_for_status()
36
+
37
+ os.makedirs("downloads", exist_ok=True)
38
+ with open(local_file_path, "wb") as file:
39
+ for chunk in response.iter_content(chunk_size=8192):
40
+ file.write(chunk)
41
+
42
+ print(f"File downloaded successfully: {local_file_path}")
43
+ return local_file_path
44
+ except requests.exceptions.RequestException as e:
45
+ print(f"Error downloading file for task {task_id}: {e}")
46
+ raise
47
+
48
+ def launch_ui(self):
49
+ GradioUI(self.agent).launch()
50
+
51
+ # if __name__ == "__main__":
52
+ # my_agent = MyAgent()
53
+ # my_agent.launch_ui()
app.py CHANGED
@@ -4,20 +4,13 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
 
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  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 +33,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,13 +69,25 @@ 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:
87
  print(f"Error running agent on task {task_id}: {e}")
88
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ import time
8
+ from agent import MyAgent
9
+
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def run_and_submit_all( profile: gr.OAuthProfile | None):
16
  """
 
33
 
34
  # 1. Instantiate Agent ( modify this part to create your agent)
35
  try:
36
+ agent = MyAgent()
37
  except Exception as e:
38
  print(f"Error instantiating agent: {e}")
39
  return f"Error initializing agent: {e}", None
 
69
  for item in questions_data:
70
  task_id = item.get("task_id")
71
  question_text = item.get("question")
72
+ requires_file = item.get("requires_file", False)
73
+
74
  if not task_id or question_text is None:
75
  print(f"Skipping item with missing task_id or question: {item}")
76
  continue
77
+
78
  try:
79
+ # Download file if required
80
+ if requires_file:
81
+ file_path = agent.download_file(task_id)
82
+ print(f"File for task {task_id} saved at: {file_path}")
83
+ # Optionally, pass the file path to the agent if needed
84
+ submitted_answer = agent(f"{question_text} (File: {file_path})")
85
+ else:
86
+ submitted_answer = agent(question_text)
87
+
88
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
89
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
90
+ time.sleep(2)
91
  except Exception as e:
92
  print(f"Error running agent on task {task_id}: {e}")
93
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SPACE_ID=
2
+ SPACE_HOST=
3
+ OPENROUTER_KEY=
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
requirements.txt CHANGED
@@ -1,2 +1,6 @@
1
  gradio
2
- requests
 
 
 
 
 
1
  gradio
2
+ requests
3
+ smolagents
4
+ litellm
5
+ wikipedia-api
6
+ google.auth
tools.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from markdownify import markdownify
3
+ from smolagents import Tool
4
+
5
+ class DownloadTaskAttachmentTool(Tool):
6
+ name = "download_file"
7
+ description = "Downloads the file attached to the task ID"
8
+ inputs = {'task_id': {'type': 'string', 'description': 'The task id to download attachment from.'}}
9
+ output_type = "string"
10
+
11
+ def forward(self, task_id: str) -> str:
12
+ """
13
+ Downloads a file associated with the given task ID.
14
+ Returns the file path where the file is saved locally.
15
+ """
16
+ file_url = f"{DEFAULT_API_URL}/files/{task_id}"
17
+ local_file_path = f"downloads/{task_id}.file"
18
+
19
+ print(f"Downloading file for task ID {task_id} from {file_url}...")
20
+ try:
21
+ response = requests.get(file_url, stream=True, timeout=15)
22
+ response.raise_for_status()
23
+
24
+ os.makedirs("downloads", exist_ok=True)
25
+ with open(local_file_path, "wb") as file:
26
+ for chunk in response.iter_content(chunk_size=8192):
27
+ file.write(chunk)
28
+
29
+ print(f"File downloaded successfully: {local_file_path}")
30
+ return local_file_path
31
+ except requests.exceptions.RequestException as e:
32
+ print(f"Error downloading file for task {task_id}: {e}")
33
+ raise
34
+
35
+ def __init__(self, *args, **kwargs):
36
+ self.is_initialized = False
37
+
38
+
39
+ class VisitWebpageTool(Tool):
40
+ name = "visit_webpage"
41
+ description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
42
+ inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}
43
+ output_type = "string"
44
+
45
+ def forward(self, url: str) -> str:
46
+ try:
47
+ import requests
48
+ from markdownify import markdownify
49
+ from requests.exceptions import RequestException
50
+
51
+ from smolagents.utils import truncate_content
52
+ except ImportError as e:
53
+ raise ImportError(
54
+ "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
55
+ ) from e
56
+ try:
57
+ # Send a GET request to the URL with a 20-second timeout
58
+ response = requests.get(url, timeout=20)
59
+ response.raise_for_status() # Raise an exception for bad status codes
60
+
61
+ # Convert the HTML content to Markdown
62
+ markdown_content = markdownify(response.text).strip()
63
+
64
+ # Remove multiple line breaks
65
+ markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
66
+
67
+ return truncate_content(markdown_content, 10000)
68
+
69
+ except requests.exceptions.Timeout:
70
+ return "The request timed out. Please try again later or check the URL."
71
+ except RequestException as e:
72
+ return f"Error fetching the webpage: {str(e)}"
73
+ except Exception as e:
74
+ return f"An unexpected error occurred: {str(e)}"
75
+
76
+ def __init__(self, *args, **kwargs):
77
+ self.is_initialized = False
78
+