Adding new tools to the agent + downloading task files
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
from pprint import pprint
|
| 3 |
from typing import TypedDict, List, Dict, Any, Optional, Tuple
|
| 4 |
from typing_extensions import Annotated
|
|
@@ -22,10 +23,6 @@ from langchain_core.tools import tool
|
|
| 22 |
# --- Constants ---
|
| 23 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 24 |
|
| 25 |
-
# class State(TypedDict):
|
| 26 |
-
# question: str
|
| 27 |
-
# messages: Annotated[List[AnyMessage], add_messages]
|
| 28 |
-
|
| 29 |
|
| 30 |
class State(MessagesState):
|
| 31 |
question: str
|
|
@@ -33,7 +30,11 @@ class State(MessagesState):
|
|
| 33 |
|
| 34 |
class BasicAgent:
|
| 35 |
def __init__(self):
|
| 36 |
-
self.tools = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
# Chat model with tool support
|
| 39 |
self.model = ChatOpenAI(model="gpt-4o", temperature=0)
|
|
@@ -67,15 +68,15 @@ class BasicAgent:
|
|
| 67 |
- Use tools when more information is needed.
|
| 68 |
- Always ground your answer in tool results or reasoning.
|
| 69 |
- If a tool fails or returns nothing, acknowledge it and try an alternative.
|
| 70 |
-
- If you can't find a confident answer,
|
| 71 |
|
| 72 |
**Important:**
|
|
|
|
| 73 |
- Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 74 |
- 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.
|
| 75 |
- 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.
|
| 76 |
- 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.
|
| 77 |
- If there is no direct ask about the response format, think if it's possible to answer with a number, if yes - do it, if no - answer with as few words as possible, not the whole sentence.
|
| 78 |
-
- When giving the final answer, reply with only the answer — nothing else.
|
| 79 |
|
| 80 |
**Examples:**
|
| 81 |
|
|
@@ -137,6 +138,25 @@ class BasicAgent:
|
|
| 137 |
|
| 138 |
print("\nTool result:", result)
|
| 139 |
return result[:max_length]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
|
| 142 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
@@ -199,6 +219,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 199 |
if not task_id or question_text is None:
|
| 200 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 201 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
try:
|
| 203 |
submitted_answer, logs = agent(question_text)
|
| 204 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
|
@@ -206,6 +236,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 206 |
except Exception as e:
|
| 207 |
print(f"Error running agent on task {task_id}: {e}")
|
| 208 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
if not answers_payload:
|
| 211 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 1 |
import os
|
| 2 |
+
from contextlib import suppress
|
| 3 |
from pprint import pprint
|
| 4 |
from typing import TypedDict, List, Dict, Any, Optional, Tuple
|
| 5 |
from typing_extensions import Annotated
|
|
|
|
| 23 |
# --- Constants ---
|
| 24 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
class State(MessagesState):
|
| 28 |
question: str
|
|
|
|
| 30 |
|
| 31 |
class BasicAgent:
|
| 32 |
def __init__(self):
|
| 33 |
+
self.tools = [
|
| 34 |
+
BasicAgent.search_tool,
|
| 35 |
+
BasicAgent.find_local_files_tool,
|
| 36 |
+
BasicAgent.read_text_file_tool
|
| 37 |
+
]
|
| 38 |
|
| 39 |
# Chat model with tool support
|
| 40 |
self.model = ChatOpenAI(model="gpt-4o", temperature=0)
|
|
|
|
| 68 |
- Use tools when more information is needed.
|
| 69 |
- Always ground your answer in tool results or reasoning.
|
| 70 |
- If a tool fails or returns nothing, acknowledge it and try an alternative.
|
| 71 |
+
- If you can't find a confident answer, return your best guess.
|
| 72 |
|
| 73 |
**Important:**
|
| 74 |
+
- When giving the final answer, reply with only the answer — nothing else.
|
| 75 |
- Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 76 |
- 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.
|
| 77 |
- 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.
|
| 78 |
- 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.
|
| 79 |
- If there is no direct ask about the response format, think if it's possible to answer with a number, if yes - do it, if no - answer with as few words as possible, not the whole sentence.
|
|
|
|
| 80 |
|
| 81 |
**Examples:**
|
| 82 |
|
|
|
|
| 138 |
|
| 139 |
print("\nTool result:", result)
|
| 140 |
return result[:max_length]
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
@tool(
|
| 144 |
+
description="List task files.",
|
| 145 |
+
)
|
| 146 |
+
def find_local_files_tool() -> list[str]:
|
| 147 |
+
print(f"\nCalling find local files tool")
|
| 148 |
+
files = [f for f in os.listdir() if os.path.isfile(f) and f.startswith('task_file_')]
|
| 149 |
+
print(f"\nReturning", files)
|
| 150 |
+
return files
|
| 151 |
+
|
| 152 |
+
@staticmethod
|
| 153 |
+
@tool(
|
| 154 |
+
description="Read the text file and return it's content.",
|
| 155 |
+
)
|
| 156 |
+
def read_text_file_tool(file_name: str) -> str:
|
| 157 |
+
print(f"\nCalling read text file tool for", file_name)
|
| 158 |
+
with open(file_name, 'r') as f:
|
| 159 |
+
return f.read()
|
| 160 |
|
| 161 |
|
| 162 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
| 219 |
if not task_id or question_text is None:
|
| 220 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 221 |
continue
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 225 |
+
file_name = f"task_file_{task_id}"
|
| 226 |
+
with open(file_name, "wb") as file:
|
| 227 |
+
response = get(file_url)
|
| 228 |
+
file.write(response.content)
|
| 229 |
+
except:
|
| 230 |
+
print("Didn't manage to download a file, probably it's not expected for this task")
|
| 231 |
+
|
| 232 |
try:
|
| 233 |
submitted_answer, logs = agent(question_text)
|
| 234 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
|
|
|
| 236 |
except Exception as e:
|
| 237 |
print(f"Error running agent on task {task_id}: {e}")
|
| 238 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 239 |
+
finally:
|
| 240 |
+
with suppress(Exception):
|
| 241 |
+
os.remove(file_name)
|
| 242 |
|
| 243 |
if not answers_payload:
|
| 244 |
print("Agent did not produce any answers to submit.")
|