Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,33 +5,34 @@ import inspect
|
|
| 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 |
|
| 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
|
| 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 =
|
|
|
|
| 33 |
|
| 34 |
-
# --- Initialize ASR Pipeline
|
| 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
|
|
|
|
| 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 |
-
|
| 62 |
print(f"--- Calling Search Tool with query: {query} ---")
|
| 63 |
try:
|
| 64 |
search = DuckDuckGoSearchRun()
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)}
|
|
|
|
| 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()
|
| 79 |
-
2. Write simple,
|
| 80 |
-
3.
|
| 81 |
-
|
| 82 |
"""
|
| 83 |
-
|
| 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 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
| 106 |
|
| 107 |
@tool
|
| 108 |
def read_file(path: str) -> str:
|
| 109 |
-
"""Reads the content of a file at the specified path
|
| 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 |
-
|
| 114 |
-
print(f"--- Calling Read File Tool
|
|
|
|
| 115 |
try:
|
| 116 |
-
# --- Path Finding Logic ---
|
| 117 |
script_dir = os.getcwd()
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
print(f"Reading file: {full_path}")
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
| 142 |
try:
|
| 143 |
with open(full_path, 'r', encoding='utf-8') as f:
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
except PermissionError:
|
| 149 |
-
return f"Error: Permission denied
|
| 150 |
except IsADirectoryError:
|
| 151 |
-
|
| 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
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
-
# --- 2c. Fallback for Unexpected Errors ---
|
| 159 |
tb_str = traceback.format_exc()
|
| 160 |
-
print(f"--- Read File Tool FAILED
|
| 161 |
-
return f"Unexpected error
|
|
|
|
| 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
|
| 168 |
-
if not isinstance(path, str) or not path.strip():
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
try:
|
| 172 |
-
base_dir = os.getcwd()
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
@tool
|
| 180 |
def list_directory(path: str = ".") -> str:
|
| 181 |
-
"""Lists the contents
|
| 182 |
-
if not isinstance(path, str):
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
-
base_dir = os.getcwd()
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
@tool
|
| 194 |
def audio_transcription_tool(file_path: str) -> str:
|
| 195 |
-
"""Transcribes an audio file (
|
| 196 |
-
if not isinstance(file_path, str) or not file_path.strip():
|
|
|
|
|
|
|
| 197 |
print(f"--- Calling Audio Transcription: {file_path} ---")
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
try:
|
| 200 |
-
#
|
| 201 |
-
script_dir = os.getcwd()
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
print(f"Transcribing file: {full_path}")
|
| 210 |
transcription = asr_pipeline(full_path)
|
| 211 |
result_text = transcription.get("text", "")
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
@tool
|
| 217 |
def get_youtube_transcript(video_url: str) -> str:
|
| 218 |
-
"""Fetches
|
| 219 |
-
if not isinstance(video_url, str) or not video_url.strip():
|
|
|
|
|
|
|
| 220 |
print(f"--- Calling YouTube Transcript: {video_url} ---")
|
|
|
|
| 221 |
try:
|
|
|
|
| 222 |
video_id = None
|
| 223 |
-
if "watch?v=" in video_url:
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
full_transcript = " ".join([item["text"] for item in transcript_list])
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
@tool
|
| 233 |
def scrape_web_page(url: str) -> str:
|
| 234 |
-
"""Fetches
|
| 235 |
-
if not isinstance(url, str) or not url.strip():
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
| 238 |
print(f"--- Calling Web Scraper: {url} ---")
|
|
|
|
| 239 |
try:
|
| 240 |
-
headers = {
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
content_type = response.headers.get('Content-Type', '').lower()
|
| 243 |
-
if 'html' not in content_type:
|
|
|
|
|
|
|
| 244 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
text = main_content.get_text(separator='\n', strip=True)
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
text = '\n'.join(chunk for chunk in chunks if chunk)
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
except requests.exceptions.RequestException as req_e:
|
| 255 |
return f"Error fetching URL {url}: {str(req_e)}"
|
| 256 |
-
except Exception as e:
|
|
|
|
|
|
|
| 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'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
"""
|
| 265 |
-
# --- Input Validation ---
|
| 266 |
if not isinstance(answer, str):
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
except:
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
| 275 |
def remove_fences_simple(text):
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
| 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 |
-
]
|
|
|
|
| 298 |
|
| 299 |
# --- LangGraph Agent State ---
|
| 300 |
class AgentState(TypedDict):
|
| 301 |
messages: Annotated[List[AnyMessage], add_messages]
|
| 302 |
-
turn: int
|
| 303 |
|
| 304 |
-
|
|
|
|
| 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
|
| 313 |
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
| 317 |
|
| 318 |
-
# 2. Check turn limit
|
| 319 |
if current_turn >= MAX_TURNS:
|
| 320 |
-
print(f"--- Condition:
|
| 321 |
-
|
| 322 |
-
|
|
|
|
| 323 |
return END
|
| 324 |
|
| 325 |
-
# 3.
|
| 326 |
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
| 327 |
-
print("--- Condition:
|
| 328 |
return "tools"
|
| 329 |
|
| 330 |
-
# 4.
|
| 331 |
-
print(f"--- Condition: No tool call (Turn {current_turn}).
|
| 332 |
return "agent"
|
| 333 |
|
| 334 |
-
|
|
|
|
|
|
|
| 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:
|
|
|
|
| 340 |
|
| 341 |
self.tools = defined_tools
|
| 342 |
|
| 343 |
-
# Build tool descriptions
|
| 344 |
tool_desc_list = []
|
| 345 |
for tool in self.tools:
|
| 346 |
if tool.name == 'code_interpreter':
|
| 347 |
-
desc = (
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
|
|
|
| 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
|
| 361 |
-
self.system_prompt = f"""You are a highly intelligent
|
| 362 |
-
Your goal
|
| 363 |
|
| 364 |
-
**
|
| 365 |
|
| 366 |
-
1.
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
| 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
|
| 407 |
try:
|
| 408 |
chat_llm = ChatGroq(
|
| 409 |
-
temperature=0,
|
| 410 |
groq_api_key=GROQ_API_KEY,
|
| 411 |
-
model_name="llama-3.3-70b-versatile",
|
| 412 |
-
max_tokens=4096,
|
| 413 |
-
timeout=60
|
| 414 |
)
|
| 415 |
-
print("β
Groq LLM
|
| 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
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 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 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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]}...")
|