Spaces:
Runtime error
Runtime error
Multiple updates refining the design with updated prompt , updated tool set
Browse files
app.py
CHANGED
|
@@ -23,12 +23,52 @@ from langchain_openai import ChatOpenAI
|
|
| 23 |
from openai import OpenAI
|
| 24 |
|
| 25 |
# tools imported from helper.py
|
| 26 |
-
from helper import repl_tool, get_travily_api_search_tool,audio_transcriber_tool,wikipedia_search_tool,
|
| 27 |
|
| 28 |
# (Keep Constants as is)
|
| 29 |
# --- Constants ---
|
| 30 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# --- Basic Agent Definition ---
|
| 33 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 34 |
class BasicAgent:
|
|
@@ -63,12 +103,12 @@ class BasicAgent:
|
|
| 63 |
# Adjust this check if your error type is different
|
| 64 |
return isinstance(e, genai.errors.APIError) and getattr(e, "code", None) in {429, 503}
|
| 65 |
|
| 66 |
-
def invoke_with_retry(self,question: str, max_retries: int = 5, initial_delay: float = 10.0) -> str:
|
| 67 |
current_delay = initial_delay
|
| 68 |
for attempt in range(max_retries):
|
| 69 |
try:
|
| 70 |
result = self.agent_obj.invoke(
|
| 71 |
-
{"input": question},
|
| 72 |
config={"configurable": {"session_id": "test-session"}},
|
| 73 |
)
|
| 74 |
return result['output']
|
|
@@ -91,11 +131,11 @@ class BasicAgent:
|
|
| 91 |
# If all retries fail, raise a RuntimeError
|
| 92 |
raise RuntimeError(f"Max retries ({max_retries}) exceeded due to persistent quota errors or other retriable issues.")
|
| 93 |
|
| 94 |
-
def __call__(self, question: str) -> str:
|
| 95 |
"""
|
| 96 |
Allows the instance to be called directly to get an AgentExecutor.
|
| 97 |
"""
|
| 98 |
-
return self.invoke_with_retry(question)
|
| 99 |
|
| 100 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 101 |
"""
|
|
@@ -158,172 +198,64 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 158 |
print(f"Using Tavily API key: {tavily_api_key[:4]}... (truncated for security)")
|
| 159 |
|
| 160 |
travily_api_search_tool = get_travily_api_search_tool(tavily_api_key)
|
| 161 |
-
tools = [ repl_tool,
|
| 162 |
-
|
| 163 |
-
EX5_OBSERVATION_STRING = (
|
| 164 |
-
"[{{'title': '1977 New York Yankees Hitting Stats - Baseball-Reference.com', "
|
| 165 |
-
"'url': 'https://www.baseball-reference.com/teams/NYY/1977.shtml', "
|
| 166 |
-
"'content': '| Rk | Player | Age | Pos | WAR | W | L | W-L% | ERA | G | GS | GF | CG | SHO | SV | IP | H | R | ER | HR | BB | IBB | SO | HBP | BK | WP | BF | ERA+ | FIP | WHIP | H9 | HR9 | BB9 | SO9 | SO/BB | Awards | All logos are the trademark & property of their owners and not Sports Reference LLC. Copyright © 2000-2025 Sports Reference LLC. Sports Info Solutions logo Sports Info Solutions logo Sports Info Solutions logo'}}]"
|
| 167 |
-
)
|
| 168 |
|
| 169 |
prompt = PromptTemplate(
|
| 170 |
-
input_variables=["input", "agent_scratchpad", "
|
| 171 |
template="""
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
Here are some examples of how you should respond:
|
| 211 |
-
|
| 212 |
-
Example 1:
|
| 213 |
-
Question: What is the capital of France?
|
| 214 |
-
Thought: I need to use a tool to find the capital of France.
|
| 215 |
-
Action: tavily_search
|
| 216 |
-
Action Input: capital of France
|
| 217 |
-
Observation: The capital of France is Paris.
|
| 218 |
-
Thought: I have found the answer.
|
| 219 |
-
Final Answer: Paris
|
| 220 |
-
|
| 221 |
-
Example 2:
|
| 222 |
-
Question: What is 2 + 2?
|
| 223 |
-
Thought: This is a simple arithmetic question, no tool is needed.
|
| 224 |
-
Final Answer: 4
|
| 225 |
-
|
| 226 |
-
Example 3:
|
| 227 |
-
Question: How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.
|
| 228 |
-
Thought: The user is asking for specific information about discography, which might be found with a search tool. The `serpapi_Google Search_tool` can fetch detailed sections. After getting the content, I will need to parse it using `python_repl` to count the albums within the specified years.
|
| 229 |
-
Action: serpapi_Google Search
|
| 230 |
-
Action Input: Mercedes Sosa discography
|
| 231 |
-
Observation: [Discography text content from search result]
|
| 232 |
-
Thought: I have retrieved discography text. Now I need to parse this text to identify and count studio albums released between 2000 and 2009. I will use the `python_repl` tool for this.
|
| 233 |
-
Action: python_repl
|
| 234 |
-
Action Input:
|
| 235 |
-
```python
|
| 236 |
-
import re
|
| 237 |
-
text = "[Discography text content from previous observation]" # Replace with actual text
|
| 238 |
-
albums_2000_2009 = []
|
| 239 |
-
pattern = r"\((\d{{4}})\)\s*(.*?)(?:\[|\n|$)" # Ensures year is captured. Double braces {{}} to escape regex literal braces
|
| 240 |
-
for match in re.finditer(pattern, text):
|
| 241 |
-
year = int(match.group(1))
|
| 242 |
-
if 2000 <= year <= 2009:
|
| 243 |
-
albums_2000_2009.append(match.group(2).strip())
|
| 244 |
-
print(len(albums_2000_2009))
|
| 245 |
-
```
|
| 246 |
-
Observation: 3
|
| 247 |
-
Thought: I have parsed the discography and counted the albums. I have found the answer.
|
| 248 |
-
Final Answer: 3
|
| 249 |
-
|
| 250 |
-
**Example 4: (Crucial new example for image processing)**
|
| 251 |
-
Question: What is the next best move in this chess position? Attachment 'chess_board.png' available at EXACT URL: https://agents-course-unit4-scoring.hf.space/files/cca530fc-4052-43b2-b130-b30968d8aa44
|
| 252 |
-
Thought: The user is asking a question about a chess position and has provided an image. I need to first save the image locally using the 'file_saver' tool, and then use the 'gemini_multimodal_tool' to analyze the image and answer the question.
|
| 253 |
-
Action: file_saver
|
| 254 |
-
Action Input: {{"url": "https://agents-course-unit4-scoring.hf.space/files/cca530fc-4052-43b2-b130-b30968d8aa44", "local_filename": "cca530fc-4052-43b2-b130-b30968d8aa44.png"}}
|
| 255 |
-
Observation: File downloaded successfully to cca530fc-4052-43b2-b130-b30968d8aa44.png
|
| 256 |
-
Thought: The image has been successfully downloaded. Now I need to analyze its content to determine the next best chess move using the 'gemini_multimodal_tool'.
|
| 257 |
-
Action: gemini_multimodal_tool
|
| 258 |
-
Action Input: {{"image_path": "cca530fc-4052-43b2-b130-b30968d8aa44.png", "question": "What is the next best move in this chess position?"}}
|
| 259 |
-
Observation: The next best move is e4.
|
| 260 |
-
Thought: I have used the 'gemini_multimodal_tool' to get the best move based on the image.
|
| 261 |
-
Final Answer: e4
|
| 262 |
-
|
| 263 |
-
Example 5: (Crucial negative example for conciseness)
|
| 264 |
-
Question: What is the opposite of up?
|
| 265 |
-
Thought: The question asks for the opposite of up. This is a direct knowledge question.
|
| 266 |
-
Final Answer: down
|
| 267 |
-
DO NOT RESPOND LIKE THIS: The opposite of up is down. or The answer is down.
|
| 268 |
-
|
| 269 |
-
Example 6: (New example for parsing baseball stats)
|
| 270 |
-
Question: How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?
|
| 271 |
-
Thought: I need to find the Yankee player with the most walks in 1977 and then find their at bats. This will require searching for Yankees 1977 stats and then parsing the results to extract the relevant player and their at-bats. I will use 'tavily_search' first to find the stats. After getting the search results, I will examine their content for a list or table of players and their stats. If found, I will use 'python_repl' to parse it.
|
| 272 |
-
Action: tavily_search
|
| 273 |
-
Action Input: New York Yankees 1977 batting stats
|
| 274 |
-
Observation: {{EX5_OBSERVATION_STRING}}
|
| 275 |
-
Thought: I have received an observation from `tavily_search`. I need to examine its `content` to determine if it contains the necessary data (e.g., a list or table of players/stats/winners). If so, my next step is to use `python_repl` to parse this content to extract the specific information needed to answer the question. I should only consider another `tavily_search` if the current observation's content is clearly insufficient.
|
| 276 |
-
Action: python_repl
|
| 277 |
-
Action Input:
|
| 278 |
-
```python
|
| 279 |
-
# Example: Parse the text content from the tavily_search observation.
|
| 280 |
-
# This is a placeholder for the actual parsing logic you would write.
|
| 281 |
-
# For the Malko question, you would parse the list of winners and their nationalities.
|
| 282 |
-
# For instance, if the observation content contains:
|
| 283 |
-
# "1983 | Claus Peter Flor | East Germany"
|
| 284 |
-
# You would extract this and apply your filtering logic.
|
| 285 |
-
```
|
| 286 |
-
Observation: 519
|
| 287 |
-
Thought: I have parsed the data and identified Roy White as the Yankee with the most walks (75) in 1977, and his at-bats were 519. I have found the answer.
|
| 288 |
-
Final Answer: 519
|
| 289 |
-
|
| 290 |
-
Example 7: (Parsing a table for minimum value)
|
| 291 |
-
Question: What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.
|
| 292 |
-
Thought: I need to find a table of athlete counts by country for the 1928 Olympics. I will use 'tavily_search' to find the data. After getting the search results, I will examine their content for a list or table of countries and their athlete counts. If found, I will use 'python_repl' to parse it.
|
| 293 |
-
Action: tavily_search
|
| 294 |
-
Action Input: 1928 Summer Olympics athlete count by country
|
| 295 |
-
Observation: [Table or HTML/text with country and athlete counts]
|
| 296 |
-
Thought: I have found the table in the `tavily_search` observation. Now I need to parse it to find the country with the least athletes, and if there is a tie, pick the first alphabetically. I will use 'python_repl' for this.
|
| 297 |
-
Action: python_repl
|
| 298 |
-
Action Input:
|
| 299 |
-
```python
|
| 300 |
-
# Example: python code to parse the text table and find the IOC country code with the least athletes.
|
| 301 |
-
# (Replace this with actual code as needed)
|
| 302 |
-
```
|
| 303 |
-
Observation: LUX Thought: I have found the country with the least athletes.
|
| 304 |
-
Final Answer: LUX
|
| 305 |
-
|
| 306 |
-
---
|
| 307 |
-
Previous conversation history:
|
| 308 |
-
{chat_history}
|
| 309 |
-
|
| 310 |
-
New input: {input}
|
| 311 |
-
---
|
| 312 |
-
{agent_scratchpad}
|
| 313 |
"""
|
| 314 |
)
|
| 315 |
|
| 316 |
-
summary_memory = ConversationSummaryMemory(llm=llm_client, memory_key="chat_history")
|
| 317 |
|
| 318 |
|
| 319 |
# Initialize gemini model with streaming enabled
|
| 320 |
|
|
|
|
| 321 |
summary_llm = ChatGoogleGenerativeAI(
|
| 322 |
model=gemini_model,
|
| 323 |
google_api_key=google_api_key,
|
| 324 |
temperature=0,
|
| 325 |
streaming=True
|
| 326 |
)
|
|
|
|
| 327 |
|
| 328 |
|
| 329 |
#summary_llm = ChatOpenAI(model='gpt-4o', temperature=0, streaming=False,api_key=openai_api_key)
|
|
@@ -331,15 +263,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 331 |
|
| 332 |
|
| 333 |
# Create a ReAct agent
|
| 334 |
-
|
| 335 |
-
llm=
|
| 336 |
tools=tools,
|
| 337 |
prompt=prompt
|
| 338 |
)
|
| 339 |
|
| 340 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 341 |
try:
|
| 342 |
-
agent = BasicAgent(
|
| 343 |
except Exception as e:
|
| 344 |
print(f"Error instantiating agent: {e}")
|
| 345 |
return f"Error initializing agent: {e}", None
|
|
@@ -374,35 +306,32 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 374 |
for item in questions_data:
|
| 375 |
task_id = item.get("task_id")
|
| 376 |
question_text = item.get("question")
|
| 377 |
-
file_name = item.get("file_name") # Get the file_name if it exists
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
full_question_for_agent = question_text
|
| 382 |
-
if file_name:
|
| 383 |
-
attachment_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
|
| 384 |
-
full_question_for_agent += f"\n\nAttachment '{file_name}' available at EXACT URL: {attachment_url}"
|
| 385 |
-
print(f"Running agent on task {task_id}: {full_question_for_agent}",flush=True)
|
| 386 |
|
| 387 |
-
'''
|
| 388 |
allowed_ids = {
|
| 389 |
#"cca530fc-4052-43b2-b130-b30968d8aa44",
|
| 390 |
#"a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
|
| 391 |
-
"3f57289b-8c60-48be-bd80-01f8099ca449",
|
| 392 |
#"2d83110e-a098-4ebb-9987-066c06fa42d0",
|
| 393 |
#"cf106601-ab4f-4af9-b045-5295fe67b37d",
|
| 394 |
#"7bd855d8-463d-4ed5-93ca-5fe35145f733",
|
| 395 |
-
"5a0c1adf-205e-4841-a666-7c3ef95def9d",
|
| 396 |
"f918266a-b3e0-4914-865d-4faa564f1aef",
|
| 397 |
}
|
| 398 |
if task_id not in allowed_ids:
|
| 399 |
continue
|
| 400 |
-
|
| 401 |
try:
|
| 402 |
-
|
|
|
|
|
|
|
|
|
|
| 403 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 404 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 405 |
-
time.sleep(61) # Add a 1 min delay before running the agent
|
| 406 |
except Exception as e:
|
| 407 |
print(f"Error running agent on task {task_id}: {e}")
|
| 408 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
| 23 |
from openai import OpenAI
|
| 24 |
|
| 25 |
# tools imported from helper.py
|
| 26 |
+
from helper import repl_tool, get_travily_api_search_tool,audio_transcriber_tool,wikipedia_search_tool,gemini_multimodal_tool, load_text_file_tool
|
| 27 |
|
| 28 |
# (Keep Constants as is)
|
| 29 |
# --- Constants ---
|
| 30 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 31 |
|
| 32 |
+
from PIL import Image
|
| 33 |
+
import PIL
|
| 34 |
+
from io import BytesIO
|
| 35 |
+
from openai import OpenAI
|
| 36 |
+
|
| 37 |
+
def download_file(task_id):
|
| 38 |
+
file_response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}")
|
| 39 |
+
return BytesIO(file_response.content)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def save_local(buffer, fname):
|
| 43 |
+
os.makedirs('file_cache/', exist_ok=True)
|
| 44 |
+
path = os.path.join('file_cache', fname)
|
| 45 |
+
with open(path, 'wb') as outfile:
|
| 46 |
+
outfile.write(buffer.read())
|
| 47 |
+
return path
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def download_image(task_id: str):
|
| 51 |
+
return Image.open(download_file(task_id))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def attachment_kwargs(task_id, fname):
|
| 55 |
+
kwargs = {}
|
| 56 |
+
ext = os.path.splitext(fname)[1].lower()
|
| 57 |
+
if ext in ['.jpg', '.jpeg', '.png']:
|
| 58 |
+
kwargs['images'] = [download_image(task_id)]
|
| 59 |
+
elif ext:
|
| 60 |
+
buffer = download_file(task_id)
|
| 61 |
+
path = save_local(buffer, fname)
|
| 62 |
+
kwargs['additional_args'] = {
|
| 63 |
+
"file": {
|
| 64 |
+
"name": fname,
|
| 65 |
+
"type": ext,
|
| 66 |
+
"path": path
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
return kwargs
|
| 70 |
+
|
| 71 |
+
|
| 72 |
# --- Basic Agent Definition ---
|
| 73 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 74 |
class BasicAgent:
|
|
|
|
| 103 |
# Adjust this check if your error type is different
|
| 104 |
return isinstance(e, genai.errors.APIError) and getattr(e, "code", None) in {429, 503}
|
| 105 |
|
| 106 |
+
def invoke_with_retry(self,question: str, max_retries: int = 5, initial_delay: float = 10.0, kwargs=None) -> str:
|
| 107 |
current_delay = initial_delay
|
| 108 |
for attempt in range(max_retries):
|
| 109 |
try:
|
| 110 |
result = self.agent_obj.invoke(
|
| 111 |
+
{"input": question, **kwargs} if kwargs else {"input": question},
|
| 112 |
config={"configurable": {"session_id": "test-session"}},
|
| 113 |
)
|
| 114 |
return result['output']
|
|
|
|
| 131 |
# If all retries fail, raise a RuntimeError
|
| 132 |
raise RuntimeError(f"Max retries ({max_retries}) exceeded due to persistent quota errors or other retriable issues.")
|
| 133 |
|
| 134 |
+
def __call__(self, question: str, additional_args=None) -> str:
|
| 135 |
"""
|
| 136 |
Allows the instance to be called directly to get an AgentExecutor.
|
| 137 |
"""
|
| 138 |
+
return self.invoke_with_retry(question,additional_args)
|
| 139 |
|
| 140 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 141 |
"""
|
|
|
|
| 198 |
print(f"Using Tavily API key: {tavily_api_key[:4]}... (truncated for security)")
|
| 199 |
|
| 200 |
travily_api_search_tool = get_travily_api_search_tool(tavily_api_key)
|
| 201 |
+
tools = [ repl_tool,audio_transcriber_tool,travily_api_search_tool, gemini_multimodal_tool, wikipedia_search_tool, load_text_file_tool]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
prompt = PromptTemplate(
|
| 204 |
+
input_variables=["input", "agent_scratchpad", "tool_names"],
|
| 205 |
template="""
|
| 206 |
+
You are a highly capable and autonomous agent designed to solve complex, multi-step problems accurately and efficiently. Your goal is to answer the user's question based on the provided information and tools.
|
| 207 |
+
|
| 208 |
+
**GUIDING PRINCIPLES:**
|
| 209 |
+
|
| 210 |
+
1. **Deconstruct the Goal:** Carefully analyze the user's question (`input`). Break it down into a logical sequence of smaller, manageable steps.
|
| 211 |
+
2. **Think Step-by-Step:** For each step, reason about the best tool to use to gather the necessary information or perform the required action.
|
| 212 |
+
3. **Pay Attention to Detail:** Meticulously follow all constraints in the user's prompt, especially regarding the final answer's format (e.g., "comma-separated list", "alphabetical order", "algebraic notation", "first name only").
|
| 213 |
+
4. **Be Self-Reliant:** The user's request is complete. Do not ask for clarification. Use your tools to find the answer. If a file is mentioned, use a tool to read it.
|
| 214 |
+
5. **Synthesize:** Once all necessary information is gathered, synthesize it to formulate the final, precise answer.
|
| 215 |
+
|
| 216 |
+
**TOOLS:**
|
| 217 |
+
|
| 218 |
+
You have access to the following tools. You must use them one at a time to find the information you need.
|
| 219 |
+
|
| 220 |
+
{{tools}}
|
| 221 |
+
|
| 222 |
+
**RESPONSE FORMAT:**
|
| 223 |
+
|
| 224 |
+
You must always use the following format for your responses. The `Thought`, `Action`, `Action Input` cycle can repeat multiple times.
|
| 225 |
+
|
| 226 |
+
**Thought:** Your internal monologue. Analyze the user's request, break it down into steps, and decide which tool to use next. Criticize your own plan.
|
| 227 |
+
**Action:** The name of the single tool to use from the list above.
|
| 228 |
+
**Action Input:** The specific input to send to that tool.
|
| 229 |
+
**Observation:** [The result of the tool will be inserted here by the system]
|
| 230 |
+
|
| 231 |
+
... (This Thought/Action/Action Input/Observation cycle can repeat N times) ...
|
| 232 |
+
|
| 233 |
+
**Thought:** I have now gathered all the necessary information and can confidently answer the user's original question. I will now format the final answer exactly as requested.
|
| 234 |
+
**Final Answer:** [The final, direct, and precisely formatted answer to the user's question]
|
| 235 |
+
NOTE: Final Answer format: 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.
|
| 236 |
+
Remember that you can open xlsx files using pandas
|
| 237 |
+
Remember that you are smart and a perceptive reader! If you need to extract information from a piece of text, you should be able to do that just by reading the text and without writing code to extract entities.
|
| 238 |
+
Begin!
|
| 239 |
+
|
| 240 |
+
**User's Question:** {{input}}
|
| 241 |
+
**Scratchpad:** {{agent_scratchpad}}
|
| 242 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
"""
|
| 244 |
)
|
| 245 |
|
| 246 |
+
#summary_memory = ConversationSummaryMemory(llm=llm_client, memory_key="chat_history")
|
| 247 |
|
| 248 |
|
| 249 |
# Initialize gemini model with streaming enabled
|
| 250 |
|
| 251 |
+
'''
|
| 252 |
summary_llm = ChatGoogleGenerativeAI(
|
| 253 |
model=gemini_model,
|
| 254 |
google_api_key=google_api_key,
|
| 255 |
temperature=0,
|
| 256 |
streaming=True
|
| 257 |
)
|
| 258 |
+
'''
|
| 259 |
|
| 260 |
|
| 261 |
#summary_llm = ChatOpenAI(model='gpt-4o', temperature=0, streaming=False,api_key=openai_api_key)
|
|
|
|
| 263 |
|
| 264 |
|
| 265 |
# Create a ReAct agent
|
| 266 |
+
my_react_agent = create_react_agent(
|
| 267 |
+
llm=llm_client,
|
| 268 |
tools=tools,
|
| 269 |
prompt=prompt
|
| 270 |
)
|
| 271 |
|
| 272 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 273 |
try:
|
| 274 |
+
agent = BasicAgent(my_react_agent, tools, True, True, 30,None)
|
| 275 |
except Exception as e:
|
| 276 |
print(f"Error instantiating agent: {e}")
|
| 277 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 306 |
for item in questions_data:
|
| 307 |
task_id = item.get("task_id")
|
| 308 |
question_text = item.get("question")
|
| 309 |
+
#file_name = item.get("file_name") # Get the file_name if it exists
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
|
|
|
| 314 |
allowed_ids = {
|
| 315 |
#"cca530fc-4052-43b2-b130-b30968d8aa44",
|
| 316 |
#"a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
|
| 317 |
+
#"3f57289b-8c60-48be-bd80-01f8099ca449",
|
| 318 |
#"2d83110e-a098-4ebb-9987-066c06fa42d0",
|
| 319 |
#"cf106601-ab4f-4af9-b045-5295fe67b37d",
|
| 320 |
#"7bd855d8-463d-4ed5-93ca-5fe35145f733",
|
| 321 |
+
#"5a0c1adf-205e-4841-a666-7c3ef95def9d",
|
| 322 |
"f918266a-b3e0-4914-865d-4faa564f1aef",
|
| 323 |
}
|
| 324 |
if task_id not in allowed_ids:
|
| 325 |
continue
|
| 326 |
+
|
| 327 |
try:
|
| 328 |
+
kwargs = attachment_kwargs(item['task_id'], item['file_name'])
|
| 329 |
+
submitted_answer = agent(question=question_text, **kwargs)
|
| 330 |
+
|
| 331 |
+
#submitted_answer = agent(full_question_for_agent)
|
| 332 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 333 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 334 |
+
#time.sleep(61) # Add a 1 min delay before running the agent
|
| 335 |
except Exception as e:
|
| 336 |
print(f"Error running agent on task {task_id}: {e}")
|
| 337 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|