gabejavitt commited on
Commit
ba1c1bf
Β·
verified Β·
1 Parent(s): 87f9e05

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +514 -280
app.py CHANGED
@@ -5,33 +5,34 @@ import inspect
5
  import pandas as pd
6
  import io
7
  import contextlib
8
- import traceback # <-- Added for detailed errors
9
- from typing import TypedDict, Annotated, List # <-- Added List
10
  import torch
11
  import json
12
- import re # <-- Added for robust parsing
13
- import uuid # <-- Added for robust parsing
 
14
 
15
  # --- Multimodal & Web Tool Imports ---
16
  from transformers import pipeline
17
  from youtube_transcript_api import YouTubeTranscriptApi
18
- import requests
19
  from bs4 import BeautifulSoup
20
 
21
  # --- LangChain & LangGraph Imports ---
22
  from langgraph.graph.message import add_messages
23
- from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, ToolCall # <-- Ensure ToolCall is imported
24
  from langgraph.prebuilt import ToolNode
25
  from langgraph.graph import START, END, StateGraph
26
  from langchain_community.tools import DuckDuckGoSearchRun
27
- from langchain_core.tools import tool, BaseTool
28
  from langchain_groq import ChatGroq
29
 
30
  # --- Constants ---
31
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # Still not working
32
- MAX_TURNS = 15 # <-- Added turn limit
 
33
 
34
- # --- Initialize ASR Pipeline (Keep as is) ---
35
  asr_pipeline = None
36
  try:
37
  print("Loading ASR (Whisper) pipeline globally...")
@@ -47,46 +48,60 @@ try:
47
  print("βœ… ASR (Whisper) pipeline loaded successfully.")
48
  except Exception as e:
49
  print(f"⚠️ Warning: Could not load ASR pipeline globally. Error: {e}")
50
- traceback.print_exc()
51
  asr_pipeline = None
52
 
53
  # ====================================================
54
- # --- Tool Definitions (Standalone Functions) ---
 
55
  @tool
56
  def search_tool(query: str) -> str:
57
  """Calls DuckDuckGo search and returns the results. Use this for recent information or general web searches."""
58
- # --- Input Validation ---
59
  if not isinstance(query, str) or not query.strip():
60
  return "Error: Invalid input. 'query' must be a non-empty string."
61
- # --- End Validation ---
62
  print(f"--- Calling Search Tool with query: {query} ---")
63
  try:
64
  search = DuckDuckGoSearchRun()
65
- return search.run(query)
 
 
 
 
66
  except Exception as e:
67
- # --- Granular Error ---
68
  tb_str = traceback.format_exc()
69
  print(f"--- Search Tool FAILED ---\n{tb_str}\n---")
70
- return f"Error running search for '{query}': {str(e)}\nTraceback:\n{tb_str}"
 
71
 
72
  @tool
73
  def code_interpreter(code: str) -> str:
74
  """
75
  Executes a string of Python code and returns its stdout, stderr, and any error.
76
- Use for calculations, data manipulation (pandas), logic puzzles.
77
- RULES:
78
- 1. ALWAYS use print() for final results.
79
- 2. Write simple, single-step scripts. Use plan text output to plan next steps.
80
- 3. Write reasoning as Python comments (#) before code.
81
- 'pandas' (as pd) is available.
82
  """
83
- # --- Input Validation ---
84
- if not isinstance(code, str): # Basic check, could add more (e.g., length)
85
  return "Error: Invalid input. 'code' must be a string."
86
- # --- End Validation ---
87
- print(f"--- Calling Code Interpreter with code:\n{code}\n---")
 
 
 
 
 
 
 
 
 
 
 
88
  output_stream = io.StringIO()
89
  error_stream = io.StringIO()
 
90
  try:
91
  with contextlib.redirect_stdout(output_stream), contextlib.redirect_stderr(error_stream):
92
  safe_globals = {
@@ -94,196 +109,372 @@ def code_interpreter(code: str) -> str:
94
  "__builtins__": __builtins__
95
  }
96
  exec(code, safe_globals, {})
97
- stdout = output_stream.getvalue(); stderr = error_stream.getvalue()
98
- if stderr: return f"Error: {stderr}\nStdout: {stdout}"
99
- if stdout: return f"Success:\n{stdout}"
100
- return "Success: Code executed without error and produced no stdout."
 
 
 
 
 
 
 
 
 
 
 
101
  except Exception as e:
102
- # --- Granular Error with Traceback ---
103
  tb_str = traceback.format_exc()
104
  print(f"--- Code Interpreter FAILED ---\n{tb_str}\n---")
105
- return f"Execution failed with error:\n{tb_str}"
 
 
106
 
107
  @tool
108
  def read_file(path: str) -> str:
109
- """Reads the content of a file at the specified path relative to the app's CWD. Use this to examine files provided."""
110
- # --- 1. Stricter Input Validation ---
111
  if not isinstance(path, str) or not path.strip():
112
  return "Error: Invalid input. 'path' must be a non-empty string."
113
- # --- End Validation ---
114
- print(f"--- Calling Read File Tool at path: {path} ---")
 
115
  try:
116
- # --- Path Finding Logic ---
117
  script_dir = os.getcwd()
118
- print(f"Base directory for reading: {script_dir}")
119
- safe_path = os.path.normpath(path) # Normalize path
120
- full_path = os.path.join(script_dir, safe_path)
121
- print(f"Attempting to read relative path: {full_path}")
122
- if not os.path.exists(full_path):
123
- full_path = safe_path # Try direct/absolute
124
- print(f"Attempting to read direct/absolute path: {full_path}")
125
- if not os.path.exists(full_path):
126
- base_path = os.path.basename(safe_path)
127
- cwd_base_path = os.path.join(os.getcwd(), base_path)
128
- print(f"Attempting to read basename path in CWD: {cwd_base_path}")
129
- if os.path.exists(cwd_base_path):
130
- full_path = cwd_base_path
131
- else:
132
- # --- 2a. Granular Error: File Not Found ---
133
- try: cwd_files = os.listdir(".")
134
- except Exception as list_e: cwd_files = [f"Error listing CWD: {list_e}"]
135
- return (f"Error: File not found.\n"
136
- f"Tried relative: '{os.path.join(script_dir, safe_path)}'\n"
137
- f"Tried direct/absolute: '{safe_path}'\n"
138
- f"Tried basename in CWD: '{cwd_base_path}'\n"
139
- f"Files in CWD (.): {cwd_files}")
 
 
140
  print(f"Reading file: {full_path}")
141
- # --- File Reading Logic with Specific Error Handling ---
 
 
 
142
  try:
143
  with open(full_path, 'r', encoding='utf-8') as f:
144
- return f.read()
145
- # --- 2b. Granular Errors during file open/read ---
146
- except FileNotFoundError:
147
- return f"Error: File not found at final path '{full_path}'."
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  except PermissionError:
149
- return f"Error: Permission denied when trying to read file '{full_path}'."
150
  except IsADirectoryError:
151
- return f"Error: Specified path '{full_path}' is a directory, not a file."
152
- except UnicodeDecodeError:
153
- return f"Error: Could not decode file '{full_path}' as UTF-8. It might be binary or have a different encoding."
154
  except Exception as read_e:
155
  tb_str = traceback.format_exc()
156
- return f"Error reading file content from {full_path}: {str(read_e)}\nTraceback:\n{tb_str}"
 
157
  except Exception as e:
158
- # --- 2c. Fallback for Unexpected Errors ---
159
  tb_str = traceback.format_exc()
160
- print(f"--- Read File Tool FAILED UNEXPECTEDLY ---\n{tb_str}\n---")
161
- return f"Unexpected error setting up file read for '{path}': {str(e)}\nTraceback:\n{tb_str}"
 
162
 
163
- # --- (Keep write_file, list_directory, audio_transcription_tool, get_youtube_transcript, scrape_web_page as they were,
164
- # but consider adding similar input validation and granular errors to them too) ---
165
  @tool
166
  def write_file(path: str, content: str) -> str:
167
- """Writes the given content to a file at the specified path relative to the app's current directory. Creates directories if they don't exist."""
168
- if not isinstance(path, str) or not path.strip(): return "Error: Invalid input. 'path' must be a non-empty string."
169
- if not isinstance(content, str): return "Error: Invalid input. 'content' must be a string."
170
- print(f"--- Calling Write File Tool at path: {path} ---")
 
 
 
 
171
  try:
172
- base_dir = os.getcwd(); full_path = os.path.join(base_dir, path)
173
- print(f"Writing file to: {full_path}"); os.makedirs(os.path.dirname(full_path), exist_ok=True)
174
- with open(full_path, 'w', encoding='utf-8') as f: f.write(content)
175
- return f"Successfully wrote to file {path} (relative to CWD)."
176
- except PermissionError: return f"Error: Permission denied writing to file '{full_path}'."
177
- except Exception as e: tb_str = traceback.format_exc(); return f"Error writing to file {path}: {str(e)}\nTraceback:\n{tb_str}"
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  @tool
180
  def list_directory(path: str = ".") -> str:
181
- """Lists the contents (files and directories) of a directory at the specified path relative to the app's current directory."""
182
- if not isinstance(path, str): return "Error: Invalid input. 'path' must be a string (or empty for current directory)."
183
- print(f"--- Calling List Directory Tool at path: {path} ---")
 
 
 
184
  try:
185
- base_dir = os.getcwd(); full_path = os.path.join(base_dir, path)
186
- print(f"Listing directory: {full_path}")
187
- if not os.path.isdir(full_path): return f"Error: '{path}' is not a valid directory relative to CWD."
188
- files = os.listdir(full_path); return "\n".join(files) if files else "Directory is empty."
189
- except FileNotFoundError: return f"Error: Directory not found at '{full_path}'."
190
- except PermissionError: return f"Error: Permission denied listing directory '{full_path}'."
191
- except Exception as e: tb_str = traceback.format_exc(); return f"Error listing directory {path}: {str(e)}\nTraceback:\n{tb_str}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
  @tool
194
  def audio_transcription_tool(file_path: str) -> str:
195
- """Transcribes an audio file (like .mp3 or .wav) and returns the text content."""
196
- if not isinstance(file_path, str) or not file_path.strip(): return "Error: Invalid input. 'file_path' must be a non-empty string."
 
 
197
  print(f"--- Calling Audio Transcription: {file_path} ---")
198
- if asr_pipeline is None: return "Error: ASR pipeline unavailable."
 
 
 
199
  try:
200
- # (Keep your existing path finding logic for audio files)
201
- script_dir = os.getcwd(); full_path = os.path.join(script_dir, file_path)
202
- if not os.path.exists(full_path):
203
- full_path = file_path
204
- if not os.path.exists(full_path):
205
- base_path = os.path.basename(file_path)
206
- cwd_base_path = os.path.join(os.getcwd(), base_path)
207
- if os.path.exists(cwd_base_path): full_path = cwd_base_path
208
- else: return f"Error: Audio file not found." # More specific error
 
 
 
 
 
 
 
 
 
 
209
  print(f"Transcribing file: {full_path}")
210
  transcription = asr_pipeline(full_path)
211
  result_text = transcription.get("text", "")
212
- if not result_text: return "Error: Transcription failed or produced empty text."
213
- return result_text
214
- except Exception as e: tb_str = traceback.format_exc(); return f"Error transcribing '{file_path}': {str(e)}\nTraceback:\n{tb_str}"
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  @tool
217
  def get_youtube_transcript(video_url: str) -> str:
218
- """Fetches YouTube transcript for the given video URL."""
219
- if not isinstance(video_url, str) or not video_url.strip(): return "Error: Invalid input. 'video_url' must be a non-empty string."
 
 
220
  print(f"--- Calling YouTube Transcript: {video_url} ---")
 
221
  try:
 
222
  video_id = None
223
- if "watch?v=" in video_url: video_id = video_url.split("v=")[1].split("&")[0]
224
- elif "youtu.be/" in video_url: video_id = video_url.split("youtu.be/")[1].split("?")[0]
225
- if not video_id: return f"Error: Could not extract YouTube video ID from URL '{video_url}'."
 
 
 
 
 
 
 
 
226
  transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
227
- if not transcript_list: return "Error: No transcript found for this video."
 
 
 
228
  full_transcript = " ".join([item["text"] for item in transcript_list])
229
- return full_transcript[:8000] # Keep length limit
230
- except Exception as e: tb_str = traceback.format_exc(); return f"Error getting transcript for '{video_url}': {str(e)}\nTraceback:\n{tb_str}"
 
 
 
 
 
 
 
 
 
231
 
232
  @tool
233
  def scrape_web_page(url: str) -> str:
234
- """Fetches primary text content of a webpage specified by URL."""
235
- if not isinstance(url, str) or not url.strip(): return "Error: Invalid input. 'url' must be a non-empty string."
236
- # Basic URL scheme check
237
- if not url.lower().startswith(('http://', 'https://')): return f"Error: Invalid URL scheme. URL must start with http:// or https://. Received: '{url}'"
 
 
 
238
  print(f"--- Calling Web Scraper: {url} ---")
 
239
  try:
240
- headers = {'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'} # Be a good bot
241
- response = requests.get(url, headers=headers, timeout=20); response.raise_for_status()
 
 
 
 
 
242
  content_type = response.headers.get('Content-Type', '').lower()
243
- if 'html' not in content_type: return f"Error: Content type is '{content_type}', not HTML."
 
 
244
  soup = BeautifulSoup(response.text, 'html.parser')
245
- # (Keep your existing tag extraction logic)
246
- for tag in soup(["script", "style", "nav", "footer", "aside", "header", "form", "button", "input", "img", "link", "meta"]): tag.extract()
247
- main_content = soup.find('main') or soup.find('article') or soup.find('div', role='main') or soup.body
248
- if not main_content: return "Error: Could not find main body content."
 
 
 
 
 
 
 
 
 
 
 
 
249
  text = main_content.get_text(separator='\n', strip=True)
250
- lines = (line.strip() for line in text.splitlines()); chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
 
 
 
251
  text = '\n'.join(chunk for chunk in chunks if chunk)
252
- if not text: return "Error: Scraped content was empty after cleaning."
253
- return text[:8000] # Keep length limit
 
 
 
 
 
 
 
 
 
 
254
  except requests.exceptions.RequestException as req_e:
255
  return f"Error fetching URL {url}: {str(req_e)}"
256
- except Exception as e: tb_str = traceback.format_exc(); return f"Error scraping {url}: {str(e)}\nTraceback:\n{tb_str}"
 
 
257
 
258
 
259
  @tool
260
  def final_answer_tool(answer: str) -> str:
261
  """
262
  Call this tool ONLY when you have the final, definitive answer.
263
- The 'answer' argument must be a string containing only the concise, factual answer.
 
 
 
 
264
  """
265
- # --- Input Validation ---
266
  if not isinstance(answer, str):
267
- # Attempt conversion, or return error if not possible/sensible
268
- try: answer = str(answer)
269
- except: return "Error: Invalid input. 'answer' must be a string or convertible to a string."
270
- # --- End Validation ---
271
- print(f"--- AGENT CALLING FINAL ANSWER TOOL ---")
272
- return answer # The tool itself just returns the answer
273
-
274
- # --- Helper Function for Cleaning Fences (Keep as is) ---
 
 
 
275
  def remove_fences_simple(text):
276
- original_text = text; text = text.strip()
 
 
 
277
  if text.startswith("```") and text.endswith("```"):
278
  text = text[3:-3].strip()
279
  if '\n' in text:
280
  first_line, rest = text.split('\n', 1)
 
281
  if first_line.strip().replace('_','').isalnum() and len(first_line.strip()) < 15:
282
  text = rest.strip()
283
  return text
 
284
  return original_text
285
 
286
- # List of standalone tool functions
 
287
  defined_tools = [
288
  search_tool,
289
  code_interpreter,
@@ -294,195 +485,238 @@ defined_tools = [
294
  get_youtube_transcript,
295
  scrape_web_page,
296
  final_answer_tool
297
- ] # Ensure remove_fences_simple is NOT here
 
298
 
299
  # --- LangGraph Agent State ---
300
  class AgentState(TypedDict):
301
  messages: Annotated[List[AnyMessage], add_messages]
302
- turn: int # <-- Added turn counter
303
 
304
- # --- Custom Conditional Edge ---
 
305
  def should_continue(state: AgentState):
306
- """
307
- Custom logic: loop for thoughts, route to tools, end on final_answer or limit.
308
- """
309
  last_message = state['messages'][-1]
310
  current_turn = state.get('turn', 0)
311
 
312
- # 1. Check for explicit end signal (final_answer_tool)
313
  if isinstance(last_message, AIMessage) and last_message.tool_calls:
314
- if last_message.tool_calls[0].get("name") == "final_answer_tool":
315
- print("--- Condition: Saw final_answer_tool, ending graph. ---")
316
- return END
 
317
 
318
- # 2. Check turn limit *before* deciding to loop or call tools
319
  if current_turn >= MAX_TURNS:
320
- print(f"--- Condition: Reached max turns ({MAX_TURNS}). Forcing END. ---")
321
- # Optional: Append an error message for clarity in final output
322
- state['messages'].append(SystemMessage(content=f"SYSTEM: Agent reached maximum turn limit ({MAX_TURNS}). Ending execution."))
 
323
  return END
324
 
325
- # 3. If tools were called (and it wasn't final_answer), route to tools node
326
  if isinstance(last_message, AIMessage) and last_message.tool_calls:
327
- print("--- Condition: Saw other tools, calling tools node. ---")
328
  return "tools"
329
 
330
- # 4. If no tool call and not over limit, loop back to agent (reasoning loop)
331
- print(f"--- Condition: No tool call (Turn {current_turn}). Looping back to agent. ---")
332
  return "agent"
333
 
334
- # --- Basic Agent Definition ---
 
 
335
  class BasicAgent:
336
  def __init__(self):
337
  print("BasicAgent (LangGraph) initializing...")
 
338
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
339
- if not GROQ_API_KEY: raise ValueError("GROQ_API_KEY secret is not set!")
 
340
 
341
  self.tools = defined_tools
342
 
343
- # Build tool descriptions separately to avoid f-string backslash issues
344
  tool_desc_list = []
345
  for tool in self.tools:
346
  if tool.name == 'code_interpreter':
347
- desc = (f"- {tool.name}: Executes Python code. Use for calculations, data manipulation, or logic puzzles.\n"
348
- f" **CODE INTERPRETER RULES:**\n"
349
- f" 1. ALWAYS use `print()` for final results.\n"
350
- f" 2. Write SIMPLE, single-step scripts.\n"
351
- f" 3. PLAN your next script using plain text output first.\n"
352
- f" 4. Write reasoning as Python comments (#) before code.\n"
353
- f" 'pandas' (as pd) is available.")
 
354
  else:
355
  desc = f"- {tool.name}: {tool.description}"
356
  tool_desc_list.append(desc)
357
 
358
  tool_descriptions = "\n".join(tool_desc_list)
359
 
360
- # ==================== SYSTEM PROMPT V5 (Improved) ====================
361
- self.system_prompt = f"""You are a highly intelligent and meticulous AI assistant for the GAIA benchmark.
362
- Your goal is to provide the EXACT, concise, factual answer by strictly following a step-by-step reasoning process.
363
 
364
- **CRITICAL PROTOCOL: YOU MUST FOLLOW THIS PROCESS**
365
 
366
- 1. **ANALYZE:** Read the question carefully. Identify what format the answer should be in (number, yes/no, list, name, etc.).
367
- 2. **PLAN (First Turn Only):** Your *first* response MUST be a brief plan in plain text:
368
- - What information do you need?
369
- - Which tool will you use first?
370
- - What format should the final answer be in?
371
- DO NOT call any tool on your first turn.
372
-
373
- 3. **EXECUTE ONE TOOL:** Call exactly ONE tool per turn. Wait for the result before planning your next step.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
- 4. **VERIFY TOOL OUTPUT:**
376
- - Read the ToolMessage carefully
377
- - Check if it contains errors - if so, plan a different approach
378
- - Check if you have enough information for the final answer
379
-
380
- 5. **ITERATE OR FINISH:**
381
- - **Need more info?** Write a brief plan (1-2 sentences) then call the next tool
382
- - **Have the answer?** Call `final_answer_tool` immediately with the EXACT answer from the tool output
383
-
384
  **CRITICAL RULES:**
385
 
386
- * **ANSWER FORMAT:** Match the exact format requested (if question asks for a number, return ONLY the number; if it asks for a list, return ONLY the list)
387
- * **NO HALLUCINATIONS:** The answer MUST come from tool outputs, NEVER from your training data
388
- * **ONE TOOL PER TURN:** Never call multiple tools or make plans and tool calls in the same turn
389
- * **USE CODE FOR LOGIC:** For ANY calculation, counting, or logical reasoning, use `code_interpreter` and ensure it prints the result
390
- * **ERROR RECOVERY:** If a tool fails, analyze WHY and try a completely different approach
391
- * **FINAL ANSWER FORMAT:** Strip ALL explanatory text. Examples:
392
- - Question asks for number β†’ Answer: "42" (not "The answer is 42" or "42 coins")
393
- - Question asks for list β†’ Answer: "apple, banana, cherry" (not "The list is: apple, banana, cherry")
394
- - Question asks for yes/no β†’ Answer: "Yes" or "No" (not "Yes, because...")
 
 
 
395
 
396
  **TOOLS:**
397
  {tool_descriptions}
398
 
399
- **REMEMBER:**
400
- - Use tools, don't guess
401
- - One tool at a time
402
- - Final answer must match requested format exactly
403
- - No explanations in final answer
404
  """
405
 
406
- print("Initializing Groq LLM Endpoint...")
407
  try:
408
  chat_llm = ChatGroq(
409
- temperature=0, # Changed from 0.01 to 0 for maximum determinism
410
  groq_api_key=GROQ_API_KEY,
411
- model_name="llama-3.3-70b-versatile", # Better model for reasoning
412
- max_tokens=4096, # Explicit limit
413
- timeout=60 # Add timeout for stability
414
  )
415
- print("βœ… Groq LLM Endpoint initialized with llama-3.3-70b-versatile.")
416
- except Exception as e:
417
- print(f"Error initializing Groq: {e}")
418
  raise
419
 
420
  self.llm_with_tools = chat_llm.bind_tools(self.tools)
421
- print("βœ… Tools bound to LLM (using bind_tools).")
422
-
423
- # --- Agent Node with Robust Parsing Fallback ---
424
- def agent_node(state: AgentState):
425
- current_turn = state.get('turn', 0) + 1
426
- print(f"--- Running Agent Node (Turn {current_turn}) ---")
427
-
428
- # Ensure message history isn't excessively long (optional safety)
429
- # if len(state['messages']) > 20:
430
- # print("Warning: Pruning message history to prevent excessive length.")
431
- # messages_to_send = [state['messages'][0]] + state['messages'][-19:] # Keep system + last N
432
- # else:
433
- # messages_to_send = state["messages"]
434
- messages_to_send = state["messages"] # Keep all for now
435
- ai_message: AIMessage = self.llm_with_tools.invoke(messages_to_send)
436
- # --- Robust Parsing Fallback ---
437
- if not ai_message.tool_calls and isinstance(ai_message.content, str) and ai_message.content.strip():
438
- # Simple JSON block finder (might need refinement for complex cases)
439
- json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```|(\{.*?\})", ai_message.content, re.DOTALL | re.IGNORECASE)
440
- if json_match:
441
- json_str = json_match.group(1) or json_match.group(2)
442
  try:
443
- parsed_json = json.loads(json_str)
444
- # Basic validation for *our* tool format
445
- if isinstance(parsed_json, dict) and "tool" in parsed_json and "tool_input" in parsed_json:
446
- tool_name = parsed_json.get("tool")
447
- tool_input = parsed_json.get("tool_input", {})
448
- # Check if the tool name is actually one we defined
449
- if any(t.name == tool_name for t in self.tools):
450
- print(f"--- Fallback: Manually parsed tool call for '{tool_name}' from content ---")
451
- tool_call = ToolCall(name=tool_name, args=tool_input, id=str(uuid.uuid4()))
452
- ai_message.tool_calls = [tool_call]
453
- ai_message.content = "" # Clear content as it's parsed
454
- else:
455
- print(f"--- Fallback Warning: Found JSON, but tool '{tool_name}' is not defined. ---")
456
- else:
457
- print("--- Fallback Warning: Found JSON, but not in expected tool format {tool:..., tool_input:...}. ---")
458
- except json.JSONDecodeError as json_err:
459
- print(f"--- Fallback Warning: Found text resembling JSON, but failed to parse: {json_err} ---")
460
- # --- End Fallback ---
461
- print(f"AI Message Raw Content: {ai_message.content}")
462
- if ai_message.tool_calls: print(f"AI tool calls: {ai_message.tool_calls}")
463
- elif ai_message.invalid_tool_calls: print(f"AI INVALID tool calls: {ai_message.invalid_tool_calls}")
464
- else: print(f"AI content (no calls): {ai_message.pretty_repr()}")
465
- return {"messages": [ai_message], "turn": current_turn}
466
- tool_node = ToolNode(self.tools)
467
- print("Building agent graph...")
468
- graph_builder = StateGraph(AgentState)
469
- graph_builder.add_node("agent", agent_node)
470
- graph_builder.add_node("tools", tool_node)
471
- graph_builder.add_edge(START, "agent")
472
- graph_builder.add_edge("tools", "agent") # Always go back to agent after tools
473
- # --- Updated Conditional Edges ---
474
- graph_builder.add_conditional_edges(
475
- "agent",
476
- should_continue,
477
- {
478
- "tools": "tools", # If tools are called (and not final_answer)
479
- "agent": "agent", # If text/plan is generated (reasoning loop)
480
- END: END # If final_answer called or turn limit reached
481
- }
482
- )
483
- self.graph = graph_builder.compile()
484
- print("βœ… Graph compiled.")
485
- # --- __call__ Method (Keep mostly as is, just init turn) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  def __call__(self, question: str) -> str:
487
  print(f"\n--- Starting Agent Run for Question ---")
488
  print(f"Agent received question (first 100 chars): {question[:100]}...")
 
5
  import pandas as pd
6
  import io
7
  import contextlib
8
+ import traceback
9
+ from typing import TypedDict, Annotated, List
10
  import torch
11
  import json
12
+ import re
13
+ import uuid
14
+ import time
15
 
16
  # --- Multimodal & Web Tool Imports ---
17
  from transformers import pipeline
18
  from youtube_transcript_api import YouTubeTranscriptApi
 
19
  from bs4 import BeautifulSoup
20
 
21
  # --- LangChain & LangGraph Imports ---
22
  from langgraph.graph.message import add_messages
23
+ from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, ToolCall
24
  from langgraph.prebuilt import ToolNode
25
  from langgraph.graph import START, END, StateGraph
26
  from langchain_community.tools import DuckDuckGoSearchRun
27
+ from langchain_core.tools import tool
28
  from langchain_groq import ChatGroq
29
 
30
  # --- Constants ---
31
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
32
+ MAX_TURNS = 20 # Increased from 15 for complex questions
33
+ MAX_MESSAGE_LENGTH = 8000 # Truncate long outputs
34
 
35
+ # --- Initialize ASR Pipeline ---
36
  asr_pipeline = None
37
  try:
38
  print("Loading ASR (Whisper) pipeline globally...")
 
48
  print("βœ… ASR (Whisper) pipeline loaded successfully.")
49
  except Exception as e:
50
  print(f"⚠️ Warning: Could not load ASR pipeline globally. Error: {e}")
 
51
  asr_pipeline = None
52
 
53
  # ====================================================
54
+ # --- Tool Definitions ---
55
+
56
  @tool
57
  def search_tool(query: str) -> str:
58
  """Calls DuckDuckGo search and returns the results. Use this for recent information or general web searches."""
 
59
  if not isinstance(query, str) or not query.strip():
60
  return "Error: Invalid input. 'query' must be a non-empty string."
61
+
62
  print(f"--- Calling Search Tool with query: {query} ---")
63
  try:
64
  search = DuckDuckGoSearchRun()
65
+ result = search.run(query)
66
+ # Truncate if too long
67
+ if len(result) > MAX_MESSAGE_LENGTH:
68
+ result = result[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, {len(result)} total chars]"
69
+ return result
70
  except Exception as e:
 
71
  tb_str = traceback.format_exc()
72
  print(f"--- Search Tool FAILED ---\n{tb_str}\n---")
73
+ return f"Error running search for '{query}': {str(e)}"
74
+
75
 
76
  @tool
77
  def code_interpreter(code: str) -> str:
78
  """
79
  Executes a string of Python code and returns its stdout, stderr, and any error.
80
+ Use for calculations, data manipulation (pandas), logic puzzles, file processing.
81
+ CRITICAL RULES:
82
+ 1. ALWAYS use print() to output your final answer.
83
+ 2. Write simple, focused code. One task per execution.
84
+ 3. Add comments (#) to explain your logic.
85
+ Available: pandas as pd, basic Python libraries.
86
  """
87
+ if not isinstance(code, str):
 
88
  return "Error: Invalid input. 'code' must be a string."
89
+
90
+ # Basic safety checks
91
+ dangerous_patterns = ['__import__', 'eval(', 'compile(', 'subprocess', 'os.system']
92
+ code_lower = code.lower()
93
+ for pattern in dangerous_patterns:
94
+ if pattern in code_lower:
95
+ return f"Error: Potentially dangerous operation '{pattern}' is not allowed."
96
+
97
+ # Check for file writing in code
98
+ if 'open(' in code_lower and any(mode in code for mode in ["'w'", '"w"', "'a'", '"a"', "'wb'", '"wb"']):
99
+ return "Error: Writing files is not allowed in code_interpreter. Use write_file tool instead."
100
+
101
+ print(f"--- Calling Code Interpreter ---\nCode:\n{code}\n---")
102
  output_stream = io.StringIO()
103
  error_stream = io.StringIO()
104
+
105
  try:
106
  with contextlib.redirect_stdout(output_stream), contextlib.redirect_stderr(error_stream):
107
  safe_globals = {
 
109
  "__builtins__": __builtins__
110
  }
111
  exec(code, safe_globals, {})
112
+
113
+ stdout = output_stream.getvalue()
114
+ stderr = error_stream.getvalue()
115
+
116
+ if stderr:
117
+ return f"Error in execution:\n{stderr}\n\nStdout (if any):\n{stdout}"
118
+
119
+ if stdout:
120
+ # Truncate if too long
121
+ if len(stdout) > MAX_MESSAGE_LENGTH:
122
+ stdout = stdout[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, {len(stdout)} total chars]"
123
+ return f"Success:\n{stdout}"
124
+
125
+ return "Success: Code executed without error but produced no output.\n⚠️ Remember to use print() to output your results!"
126
+
127
  except Exception as e:
 
128
  tb_str = traceback.format_exc()
129
  print(f"--- Code Interpreter FAILED ---\n{tb_str}\n---")
130
+ error_msg = f"Execution failed:\n{tb_str}\n\nπŸ’‘ Hints:\n- Check your syntax\n- Ensure you're using print() for output\n- Verify variable names and types"
131
+ return error_msg
132
+
133
 
134
  @tool
135
  def read_file(path: str) -> str:
136
+ """Reads the content of a file at the specified path. Use this to examine uploaded files or files you've created."""
 
137
  if not isinstance(path, str) or not path.strip():
138
  return "Error: Invalid input. 'path' must be a non-empty string."
139
+
140
+ print(f"--- Calling Read File Tool: {path} ---")
141
+
142
  try:
 
143
  script_dir = os.getcwd()
144
+ safe_path = os.path.normpath(path)
145
+
146
+ # Try multiple path strategies
147
+ paths_to_try = [
148
+ os.path.join(script_dir, safe_path), # Relative to CWD
149
+ safe_path, # Direct/absolute
150
+ os.path.join(os.getcwd(), os.path.basename(safe_path)) # Basename in CWD
151
+ ]
152
+
153
+ full_path = None
154
+ for attempt_path in paths_to_try:
155
+ if os.path.exists(attempt_path):
156
+ full_path = attempt_path
157
+ break
158
+
159
+ if not full_path:
160
+ try:
161
+ cwd_files = os.listdir(".")
162
+ except Exception:
163
+ cwd_files = ["(could not list)"]
164
+ return (f"Error: File not found: '{path}'\n"
165
+ f"Tried paths:\n" + "\n".join(f" - {p}" for p in paths_to_try) +
166
+ f"\n\nFiles in current directory: {cwd_files}")
167
+
168
  print(f"Reading file: {full_path}")
169
+
170
+ # Try to detect file type
171
+ _, ext = os.path.splitext(full_path)
172
+
173
  try:
174
  with open(full_path, 'r', encoding='utf-8') as f:
175
+ content = f.read()
176
+
177
+ # Truncate if too long
178
+ if len(content) > MAX_MESSAGE_LENGTH:
179
+ content = content[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, {len(content)} total chars]"
180
+
181
+ return content
182
+
183
+ except UnicodeDecodeError:
184
+ # Try binary read for non-text files
185
+ try:
186
+ with open(full_path, 'rb') as f:
187
+ binary_content = f.read()
188
+ return f"File appears to be binary ({len(binary_content)} bytes). Cannot display as text.\nFile type: {ext}\nConsider using audio_transcription_tool for audio files."
189
+ except Exception as bin_e:
190
+ return f"Error: Could not read file as text or binary: {str(bin_e)}"
191
+
192
  except PermissionError:
193
+ return f"Error: Permission denied reading '{full_path}'."
194
  except IsADirectoryError:
195
+ return f"Error: '{full_path}' is a directory, not a file. Use list_directory to see its contents."
 
 
196
  except Exception as read_e:
197
  tb_str = traceback.format_exc()
198
+ return f"Error reading file: {str(read_e)}\n{tb_str}"
199
+
200
  except Exception as e:
 
201
  tb_str = traceback.format_exc()
202
+ print(f"--- Read File Tool FAILED ---\n{tb_str}\n---")
203
+ return f"Unexpected error accessing file '{path}': {str(e)}"
204
+
205
 
 
 
206
  @tool
207
  def write_file(path: str, content: str) -> str:
208
+ """Writes content to a file at the specified path. Creates directories if needed."""
209
+ if not isinstance(path, str) or not path.strip():
210
+ return "Error: Invalid input. 'path' must be a non-empty string."
211
+ if not isinstance(content, str):
212
+ return "Error: Invalid input. 'content' must be a string."
213
+
214
+ print(f"--- Calling Write File Tool: {path} ---")
215
+
216
  try:
217
+ base_dir = os.getcwd()
218
+ full_path = os.path.join(base_dir, path)
219
+
220
+ # Create directories if needed
221
+ dir_path = os.path.dirname(full_path)
222
+ if dir_path:
223
+ os.makedirs(dir_path, exist_ok=True)
224
+
225
+ with open(full_path, 'w', encoding='utf-8') as f:
226
+ f.write(content)
227
+
228
+ return f"Successfully wrote {len(content)} characters to '{path}'."
229
+
230
+ except PermissionError:
231
+ return f"Error: Permission denied writing to '{path}'."
232
+ except Exception as e:
233
+ tb_str = traceback.format_exc()
234
+ return f"Error writing file '{path}': {str(e)}\n{tb_str}"
235
+
236
 
237
  @tool
238
  def list_directory(path: str = ".") -> str:
239
+ """Lists the contents of a directory. Useful for finding available files."""
240
+ if not isinstance(path, str):
241
+ return "Error: Invalid input. 'path' must be a string."
242
+
243
+ print(f"--- Calling List Directory Tool: {path} ---")
244
+
245
  try:
246
+ base_dir = os.getcwd()
247
+ full_path = os.path.join(base_dir, path) if path != "." else base_dir
248
+
249
+ if not os.path.isdir(full_path):
250
+ return f"Error: '{path}' is not a valid directory."
251
+
252
+ items = os.listdir(full_path)
253
+
254
+ if not items:
255
+ return f"Directory '{path}' is empty."
256
+
257
+ # Separate files and directories
258
+ files = []
259
+ directories = []
260
+
261
+ for item in sorted(items):
262
+ item_path = os.path.join(full_path, item)
263
+ if os.path.isdir(item_path):
264
+ directories.append(f"πŸ“ {item}/")
265
+ else:
266
+ size = os.path.getsize(item_path)
267
+ files.append(f"πŸ“„ {item} ({size} bytes)")
268
+
269
+ result = f"Contents of '{path}':\n\n"
270
+ if directories:
271
+ result += "Directories:\n" + "\n".join(directories) + "\n\n"
272
+ if files:
273
+ result += "Files:\n" + "\n".join(files)
274
+
275
+ return result
276
+
277
+ except PermissionError:
278
+ return f"Error: Permission denied listing directory '{path}'."
279
+ except Exception as e:
280
+ tb_str = traceback.format_exc()
281
+ return f"Error listing directory '{path}': {str(e)}\n{tb_str}"
282
+
283
 
284
  @tool
285
  def audio_transcription_tool(file_path: str) -> str:
286
+ """Transcribes an audio file (mp3, wav, etc.) to text using Whisper."""
287
+ if not isinstance(file_path, str) or not file_path.strip():
288
+ return "Error: Invalid input. 'file_path' must be a non-empty string."
289
+
290
  print(f"--- Calling Audio Transcription: {file_path} ---")
291
+
292
+ if asr_pipeline is None:
293
+ return "Error: ASR pipeline is not available. Audio transcription cannot be performed."
294
+
295
  try:
296
+ # Find file using same strategy as read_file
297
+ script_dir = os.getcwd()
298
+ safe_path = os.path.normpath(file_path)
299
+
300
+ paths_to_try = [
301
+ os.path.join(script_dir, safe_path),
302
+ safe_path,
303
+ os.path.join(os.getcwd(), os.path.basename(safe_path))
304
+ ]
305
+
306
+ full_path = None
307
+ for attempt_path in paths_to_try:
308
+ if os.path.exists(attempt_path):
309
+ full_path = attempt_path
310
+ break
311
+
312
+ if not full_path:
313
+ return f"Error: Audio file not found: '{file_path}'"
314
+
315
  print(f"Transcribing file: {full_path}")
316
  transcription = asr_pipeline(full_path)
317
  result_text = transcription.get("text", "")
318
+
319
+ if not result_text:
320
+ return "Error: Transcription produced no text. The audio file may be empty or corrupted."
321
+
322
+ # Truncate if too long
323
+ if len(result_text) > MAX_MESSAGE_LENGTH:
324
+ result_text = result_text[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, original length unknown]"
325
+
326
+ return f"Transcription:\n{result_text}"
327
+
328
+ except Exception as e:
329
+ tb_str = traceback.format_exc()
330
+ return f"Error transcribing '{file_path}': {str(e)}\n{tb_str}"
331
+
332
 
333
  @tool
334
  def get_youtube_transcript(video_url: str) -> str:
335
+ """Fetches the transcript/captions for a YouTube video."""
336
+ if not isinstance(video_url, str) or not video_url.strip():
337
+ return "Error: Invalid input. 'video_url' must be a non-empty string."
338
+
339
  print(f"--- Calling YouTube Transcript: {video_url} ---")
340
+
341
  try:
342
+ # Extract video ID
343
  video_id = None
344
+ if "watch?v=" in video_url:
345
+ video_id = video_url.split("v=")[1].split("&")[0]
346
+ elif "youtu.be/" in video_url:
347
+ video_id = video_url.split("youtu.be/")[1].split("?")[0]
348
+ elif len(video_url) == 11 and video_url.isalnum(): # Direct video ID
349
+ video_id = video_url
350
+
351
+ if not video_id:
352
+ return f"Error: Could not extract YouTube video ID from '{video_url}'. Provide a valid YouTube URL."
353
+
354
+ print(f"Fetching transcript for video ID: {video_id}")
355
  transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
356
+
357
+ if not transcript_list:
358
+ return "Error: No transcript found for this video. It may not have captions available."
359
+
360
  full_transcript = " ".join([item["text"] for item in transcript_list])
361
+
362
+ # Truncate if too long
363
+ if len(full_transcript) > MAX_MESSAGE_LENGTH:
364
+ full_transcript = full_transcript[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, {len(full_transcript)} total chars]"
365
+
366
+ return f"YouTube Transcript:\n{full_transcript}"
367
+
368
+ except Exception as e:
369
+ tb_str = traceback.format_exc()
370
+ return f"Error getting transcript for '{video_url}': {str(e)}\nThis video may not have transcripts available.\n{tb_str}"
371
+
372
 
373
  @tool
374
  def scrape_web_page(url: str) -> str:
375
+ """Fetches and extracts the main text content from a webpage."""
376
+ if not isinstance(url, str) or not url.strip():
377
+ return "Error: Invalid input. 'url' must be a non-empty string."
378
+
379
+ if not url.lower().startswith(('http://', 'https://')):
380
+ return f"Error: Invalid URL. Must start with http:// or https://. Got: '{url}'"
381
+
382
  print(f"--- Calling Web Scraper: {url} ---")
383
+
384
  try:
385
+ headers = {
386
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
387
+ }
388
+
389
+ response = requests.get(url, headers=headers, timeout=20)
390
+ response.raise_for_status()
391
+
392
  content_type = response.headers.get('Content-Type', '').lower()
393
+ if 'html' not in content_type:
394
+ return f"Error: URL returned '{content_type}', not HTML. Cannot scrape non-HTML content."
395
+
396
  soup = BeautifulSoup(response.text, 'html.parser')
397
+
398
+ # Remove unwanted elements
399
+ for tag in soup(["script", "style", "nav", "footer", "aside", "header",
400
+ "form", "button", "input", "img", "link", "meta"]):
401
+ tag.extract()
402
+
403
+ # Try to find main content area
404
+ main_content = (soup.find('main') or
405
+ soup.find('article') or
406
+ soup.find('div', role='main') or
407
+ soup.find('div', class_=lambda x: x and 'content' in x.lower()) or
408
+ soup.body)
409
+
410
+ if not main_content:
411
+ return "Error: Could not find main content area on the page."
412
+
413
  text = main_content.get_text(separator='\n', strip=True)
414
+
415
+ # Clean up whitespace
416
+ lines = (line.strip() for line in text.splitlines())
417
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
418
  text = '\n'.join(chunk for chunk in chunks if chunk)
419
+
420
+ if not text:
421
+ return "Error: Scraped content was empty after cleaning."
422
+
423
+ # Truncate if too long
424
+ if len(text) > MAX_MESSAGE_LENGTH:
425
+ text = text[:MAX_MESSAGE_LENGTH] + f"\n...[truncated, {len(text)} total chars]"
426
+
427
+ return f"Content from {url}:\n\n{text}"
428
+
429
+ except requests.exceptions.Timeout:
430
+ return f"Error: Request to {url} timed out after 20 seconds."
431
  except requests.exceptions.RequestException as req_e:
432
  return f"Error fetching URL {url}: {str(req_e)}"
433
+ except Exception as e:
434
+ tb_str = traceback.format_exc()
435
+ return f"Error scraping {url}: {str(e)}\n{tb_str}"
436
 
437
 
438
  @tool
439
  def final_answer_tool(answer: str) -> str:
440
  """
441
  Call this tool ONLY when you have the final, definitive answer.
442
+ The 'answer' must be EXACTLY what was asked for, with no extra text.
443
+ Examples:
444
+ - If asked for a number: "42" (not "The answer is 42")
445
+ - If asked for a list: "apple, banana, cherry"
446
+ - If asked for a name: "John Smith"
447
  """
 
448
  if not isinstance(answer, str):
449
+ try:
450
+ answer = str(answer)
451
+ except:
452
+ return "Error: Invalid input. 'answer' must be a string."
453
+
454
+ print(f"--- FINAL ANSWER TOOL CALLED ---")
455
+ print(f"Answer: {answer}")
456
+ return answer
457
+
458
+
459
+ # --- Helper Function ---
460
  def remove_fences_simple(text):
461
+ """Remove code fences from text."""
462
+ original_text = text
463
+ text = text.strip()
464
+
465
  if text.startswith("```") and text.endswith("```"):
466
  text = text[3:-3].strip()
467
  if '\n' in text:
468
  first_line, rest = text.split('\n', 1)
469
+ # Remove language identifier
470
  if first_line.strip().replace('_','').isalnum() and len(first_line.strip()) < 15:
471
  text = rest.strip()
472
  return text
473
+
474
  return original_text
475
 
476
+
477
+ # List of all tools
478
  defined_tools = [
479
  search_tool,
480
  code_interpreter,
 
485
  get_youtube_transcript,
486
  scrape_web_page,
487
  final_answer_tool
488
+ ]
489
+
490
 
491
  # --- LangGraph Agent State ---
492
  class AgentState(TypedDict):
493
  messages: Annotated[List[AnyMessage], add_messages]
494
+ turn: int
495
 
496
+
497
+ # --- Conditional Edge Function ---
498
  def should_continue(state: AgentState):
499
+ """Decide whether to continue, call tools, or end."""
 
 
500
  last_message = state['messages'][-1]
501
  current_turn = state.get('turn', 0)
502
 
503
+ # 1. Check for final_answer_tool
504
  if isinstance(last_message, AIMessage) and last_message.tool_calls:
505
+ for tool_call in last_message.tool_calls:
506
+ if tool_call.get("name") == "final_answer_tool":
507
+ print("--- Condition: final_answer_tool called, ending. ---")
508
+ return END
509
 
510
+ # 2. Check turn limit
511
  if current_turn >= MAX_TURNS:
512
+ print(f"--- Condition: Max turns ({MAX_TURNS}) reached. Ending. ---")
513
+ state['messages'].append(
514
+ SystemMessage(content=f"SYSTEM: Maximum turn limit ({MAX_TURNS}) reached. Ending execution.")
515
+ )
516
  return END
517
 
518
+ # 3. Route to tools if tool calls exist
519
  if isinstance(last_message, AIMessage) and last_message.tool_calls:
520
+ print("--- Condition: Tools called, routing to tools node. ---")
521
  return "tools"
522
 
523
+ # 4. Loop back to agent (reasoning/planning step)
524
+ print(f"--- Condition: No tool call (Turn {current_turn}). Continuing to agent. ---")
525
  return "agent"
526
 
527
+
528
+ # ====================================================
529
+ # --- Basic Agent Class ---
530
  class BasicAgent:
531
  def __init__(self):
532
  print("BasicAgent (LangGraph) initializing...")
533
+
534
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
535
+ if not GROQ_API_KEY:
536
+ raise ValueError("GROQ_API_KEY environment variable is not set!")
537
 
538
  self.tools = defined_tools
539
 
540
+ # Build tool descriptions
541
  tool_desc_list = []
542
  for tool in self.tools:
543
  if tool.name == 'code_interpreter':
544
+ desc = (
545
+ f"- {tool.name}: Executes Python code. Use for calculations, data analysis, logic puzzles.\n"
546
+ f" **CRITICAL RULES:**\n"
547
+ f" 1. ALWAYS use print() to output results\n"
548
+ f" 2. Write simple, focused code (one task per execution)\n"
549
+ f" 3. Add comments (#) to explain your logic\n"
550
+ f" Available: pandas as pd"
551
+ )
552
  else:
553
  desc = f"- {tool.name}: {tool.description}"
554
  tool_desc_list.append(desc)
555
 
556
  tool_descriptions = "\n".join(tool_desc_list)
557
 
558
+ # ==================== SYSTEM PROMPT V5 ====================
559
+ self.system_prompt = f"""You are a highly intelligent AI assistant for the GAIA benchmark.
560
+ Your goal: Provide the EXACT answer in the EXACT format requested.
561
 
562
+ **PROTOCOL:**
563
 
564
+ 1. **ANALYZE QUESTION:**
565
+ - What information is needed?
566
+ - What format should the answer be? (number, list, yes/no, name, etc.)
567
+ - Are there any files attached?
568
+
569
+ 2. **FIRST TURN - MAKE A PLAN:**
570
+ Your FIRST response MUST be a brief plan (2-3 sentences):
571
+ - What tools you'll use
572
+ - What order you'll use them
573
+ - What format the final answer should be
574
+ DO NOT call tools on your first turn!
575
+
576
+ 3. **EXECUTE:**
577
+ - Call ONE tool per turn
578
+ - Wait for the result before planning your next step
579
+ - For ANY calculation or logic: use code_interpreter with print()
580
+
581
+ 4. **VERIFY RESULTS:**
582
+ - Check if tool output contains errors
583
+ - If error: plan a different approach
584
+ - If success: decide if you need more info or have the answer
585
+
586
+ 5. **FINISH:**
587
+ When you have the answer from a tool output:
588
+ - Call final_answer_tool immediately
589
+ - Provide ONLY the exact answer (no explanations!)
590
 
 
 
 
 
 
 
 
 
 
591
  **CRITICAL RULES:**
592
 
593
+ ❌ NEVER guess or use training data for the final answer
594
+ ❌ NEVER call multiple tools in one turn
595
+ ❌ NEVER add explanations to final_answer_tool
596
+ βœ… ALWAYS use code_interpreter for calculations/logic
597
+ βœ… ALWAYS match the requested answer format exactly
598
+ βœ… ALWAYS base your answer on tool outputs, not memory
599
+
600
+ **ANSWER FORMAT EXAMPLES:**
601
+ - "What is 5+5?" β†’ final_answer("10")
602
+ - "List the colors" β†’ final_answer("red, blue, green")
603
+ - "Is it true?" β†’ final_answer("Yes") or final_answer("No")
604
+ - "What's the name?" β†’ final_answer("John Smith")
605
 
606
  **TOOLS:**
607
  {tool_descriptions}
608
 
609
+ **REMEMBER:** One tool per turn. Base everything on tool outputs. Match the format exactly.
 
 
 
 
610
  """
611
 
612
+ print("Initializing Groq LLM...")
613
  try:
614
  chat_llm = ChatGroq(
615
+ temperature=0, # Maximum determinism
616
  groq_api_key=GROQ_API_KEY,
617
+ model_name="llama-3.3-70b-versatile", # Best reasoning model
618
+ max_tokens=4096,
619
+ timeout=60
620
  )
621
+ print("βœ… Groq LLM initialized with llama-3.3-70b-versatile")
622
+ except Exception as e:
623
+ print(f"❌ Error initializing Groq: {e}")
624
  raise
625
 
626
  self.llm_with_tools = chat_llm.bind_tools(self.tools)
627
+ print("βœ… Tools bound to LLM")
628
+
629
+ # --- Agent Node ---
630
+ def agent_node(state: AgentState):
631
+ current_turn = state.get('turn', 0) + 1
632
+ print(f"\n{'='*60}")
633
+ print(f"AGENT TURN {current_turn}/{MAX_TURNS}")
634
+ print('='*60)
635
+
636
+ messages_to_send = state["messages"]
637
+
638
+ # Retry logic with exponential backoff
639
+ max_retries = 3
640
+ ai_message = None
641
+
642
+ for attempt in range(max_retries):
 
 
 
 
 
643
  try:
644
+ ai_message = self.llm_with_tools.invoke(messages_to_send)
645
+ break
646
+ except Exception as e:
647
+ print(f"⚠️ LLM attempt {attempt+1}/{max_retries} failed: {e}")
648
+ if attempt == max_retries - 1:
649
+ error_msg = AIMessage(
650
+ content=f"Error: LLM failed after {max_retries} attempts: {str(e)}"
651
+ )
652
+ return {"messages": [error_msg], "turn": current_turn}
653
+ time.sleep(2 ** attempt) # Exponential backoff
654
+
655
+ # --- Fallback JSON parsing ---
656
+ if not ai_message.tool_calls and isinstance(ai_message.content, str) and ai_message.content.strip():
657
+ json_match = re.search(
658
+ r"```(?:json)?\s*(\{.*?\})\s*```|(\{.*?\})",
659
+ ai_message.content,
660
+ re.DOTALL | re.IGNORECASE
661
+ )
662
+
663
+ if json_match:
664
+ json_str = json_match.group(1) or json_match.group(2)
665
+ try:
666
+ parsed_json = json.loads(json_str)
667
+ if isinstance(parsed_json, dict) and "tool" in parsed_json and "tool_input" in parsed_json:
668
+ tool_name = parsed_json.get("tool")
669
+ tool_input = parsed_json.get("tool_input", {})
670
+
671
+ if any(t.name == tool_name for t in self.tools):
672
+ print(f"πŸ”§ Fallback: Parsed tool call for '{tool_name}' from JSON in content")
673
+ tool_call = ToolCall(
674
+ name=tool_name,
675
+ args=tool_input,
676
+ id=str(uuid.uuid4())
677
+ )
678
+ ai_message.tool_calls = [tool_call]
679
+ ai_message.content = ""
680
+ except json.JSONDecodeError:
681
+ pass
682
+
683
+ # --- Logging ---
684
+ if ai_message.tool_calls:
685
+ for tc in ai_message.tool_calls:
686
+ print(f"πŸ”§ Tool Call: {tc.get('name')}")
687
+ print(f" Args: {tc.get('args', {})}")
688
+ elif ai_message.content:
689
+ content_preview = ai_message.content[:300]
690
+ if len(ai_message.content) > 300:
691
+ content_preview += "..."
692
+ print(f"πŸ’­ Agent Reasoning:\n{content_preview}")
693
+
694
+ return {"messages": [ai_message], "turn": current_turn}
695
+
696
+ # --- Tool Node ---
697
+ tool_node = ToolNode(self.tools)
698
+
699
+ # --- Build Graph ---
700
+ print("Building agent graph...")
701
+ graph_builder = StateGraph(AgentState)
702
+ graph_builder.add_node("agent", agent_node)
703
+ graph_builder.add_node("tools", tool_node)
704
+
705
+ graph_builder.add_edge(START, "agent")
706
+ graph_builder.add_edge("tools", "agent")
707
+
708
+ graph_builder.add_conditional_edges(
709
+ "agent",
710
+ should_continue,
711
+ {
712
+ "tools": "tools",
713
+ "agent": "agent",
714
+ END: END
715
+ }
716
+ )
717
+
718
+ self.graph = graph_builder.compile()
719
+ print("βœ… Graph compiled successfully")
720
  def __call__(self, question: str) -> str:
721
  print(f"\n--- Starting Agent Run for Question ---")
722
  print(f"Agent received question (first 100 chars): {question[:100]}...")