Spaces:
Sleeping
Sleeping
naclfish Claude Sonnet 4.6 commited on
Commit ·
2628a0b
1
Parent(s): 81917a3
Add tools/ folder, fix agent answer format and Wikipedia proxy
Browse files- Add tools/ with web_search (Serper), wikipedia_search, python_repl, file_handler
- Fix Wikipedia 403 by adding User-Agent header
- Fix answer format: enforce ENTIRE response = only final answer
- Fix list output: comma-separated, no Python brackets
- Add [Task ID] prefix to questions so agent uses correct task_id
- Increase max iterations from 10 to 15
- Add .gitignore to protect .env, data/, __pycache__
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (10)
- .gitignoreAdded+6
- app.py+140-7
- requirements.txt+4-1
- test_agent.pyAdded+30
- tools/__init__.pyAdded+6
- tools/_session.pyAdded+5
- tools/calculator.pyAdded+26
- tools/file_handler.pyAdded+90
- tools/search.pyAdded+40
- tools/wikipedia.pyAdded+51
123456.env__pycache__/*.pyc*.pyodata/记忆.md123456789101112131415161718192021222327 unmodified lines5152535455565722 unmodified lines8081828384858612 unmodified lines99100101102103104105import osimport gradio as grimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""27 unmodified lines# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:22 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:12 unmodified lines# 5. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()result_data = response.json()final_status = (12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915027 unmodified lines17817918018118218318422 unmodified lines20720820921021121221321421521621721821912 unmodified lines232233234235236237238import osimport jsonfrom dotenv import load_dotenvload_dotenv()import gradio as grimport requestsimport inspectimport pandas as pdfrom tools import web_search, wikipedia_search, python_repl, download_and_read_filefrom tools.file_handler import prefetch_file# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"TOOL_FUNCTIONS = {"web_search": web_search,"wikipedia_search": wikipedia_search,"python_repl": python_repl,"download_and_read_file": download_and_read_file,}TOOL_SCHEMAS = [{"type": "function","function": {"name": "web_search","description": "Search Google for current information. Use for factual questions, recent events, or any topic requiring web search.","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "Search query"}},"required": ["query"],},},},{"type": "function","function": {"name": "wikipedia_search","description": "Search Wikipedia for encyclopedic or historical information about a topic.","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "Topic to search"}},"required": ["query"],},},},{"type": "function","function": {"name": "python_repl","description": "Execute Python code for math, calculations, data analysis, or logic. Use print() to output results.","parameters": {"type": "object","properties": {"code": {"type": "string", "description": "Python code to execute"}},"required": ["code"],},},},{"type": "function","function": {"name": "download_and_read_file","description": "Download and read a file attachment (CSV, Excel, text) for a given task_id from the question.","parameters": {"type": "object","properties": {"task_id": {"type": "string", "description": "The task_id of the question"}},"required": ["task_id"],},},},]SYSTEM_PROMPT = ("You are a precise research assistant. Solve each question step by step using tools.\n\n""STRICT RULES:\n""1. NEVER search for 'GAIA benchmark', 'GAIA answer', 'HuggingFace discussion', or any meta-search for pre-solved answers. Solve the problem yourself.\n""2. For ANY text manipulation (reversing, encoding, counting characters, etc.), ALWAYS use python_repl — never guess by eye.\n""3. Keep search queries SHORT and targeted (under 8 words). Never enumerate values (e.g. years) in one query.\n""4. If you have an [Attached file content] section, read it directly — do NOT call download_and_read_file again.\n""5. OUTPUT FORMAT: Your ENTIRE response must be ONLY the final answer — no explanation, no reasoning, no 'The answer is', no preamble. A single word, number, or comma-separated list. Nothing else.\n""6. Numbers: digits only (e.g. '42', not 'forty-two'). Names: as they appear in the source.\n""7. If a question involves reversing or encoding text, use python_repl to decode it first before reasoning.\n""8. Lists: output as plain comma-separated values (e.g. 'apple, banana, cherry') — NO brackets, NO quotes, NO Python syntax.\n""9. If the question has a [Task ID: xxx] prefix, use that exact value when calling download_and_read_file.\n""10. If an attached file is audio/image/video (marked [UNSUPPORTED]), do NOT call download_and_read_file — use web_search to find the answer instead.\n")# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):self.api_key = os.getenv("DEEPSEEK_API_KEY")self.model = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")self.api_url = "https://www.ggwk1.online/v1/chat/completions"print("BasicAgent initialized with DeepSeek (native HTTP).")def _call_llm(self, messages: list) -> dict:headers = {"Authorization": f"Bearer {self.api_key}","Content-Type": "application/json",}payload = {"model": self.model,"messages": messages,"tools": TOOL_SCHEMAS,"tool_choice": "auto","temperature": 0,}response = requests.post(self.api_url, headers=headers, json=payload, timeout=60,proxies={"http": None, "https": None})response.raise_for_status()return response.json()def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": question},]for _ in range(15): # max iterationsresult = self._call_llm(messages)choice = result["choices"][0]message = choice["message"]messages.append(message)if choice["finish_reason"] == "tool_calls":for tool_call in message.get("tool_calls", []):fn_name = tool_call["function"]["name"]fn_args = json.loads(tool_call["function"]["arguments"])print(f" -> Tool: {fn_name}({fn_args})")tool_result = TOOL_FUNCTIONS[fn_name](**fn_args)print(f" <- Result (first 200): {str(tool_result)[:200]}")messages.append({"role": "tool","tool_call_id": tool_call["id"],"content": str(tool_result),})else:answer = message.get("content", "")print(f"Agent answer: {answer}")return answerreturn "Max iterations reached without a final answer."def run_and_submit_all( profile: gr.OAuthProfile | None):"""27 unmodified lines# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15, proxies={"http": None, "https": None})response.raise_for_status()questions_data = response.json()if not questions_data:22 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:# Pre-fetch file attachment and embed content directly in questionfile_content = prefetch_file(task_id)if file_content:full_question = f"[Task ID: {task_id}]\n{question_text}\n\n[Attached file content]:\n{file_content}"else:full_question = f"[Task ID: {task_id}]\n{question_text}"submitted_answer = agent(full_question)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:12 unmodified lines# 5. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60, proxies={"http": None, "https": None})response.raise_for_status()result_data = response.json()final_status = (
12gradiorequests12345gradiorequestspython-dotenvpandasopenpyxl
123456789101112131415161718192021222324252627282930"""Quick test script to debug a single question without launching Gradio.Usage: python test_agent.py"""import osimport jsonfrom dotenv import load_dotenvload_dotenv()
from app import BasicAgentfrom tools.file_handler import prefetch_file
agent = BasicAgent()
# --- Edit these to test any question ---task_id = "test-task-id" # replace with real task_id if neededquestion = 'If we reverse the word "tfel", what is the antonym of the result?'# ----------------------------------------
file_content = prefetch_file(task_id)if file_content: full_question = f"{question}\n\n[Attached file content]:\n{file_content}" print(f"[File found and attached, length={len(file_content)}]")else: full_question = question print("[No file attachment]")
print(f"\nQuestion: {full_question[:200]}\n")answer = agent(full_question)print(f"\n=== Final Answer ===\n{answer}")123456from .search import web_searchfrom .wikipedia import wikipedia_searchfrom .calculator import python_replfrom .file_handler import download_and_read_file
__all__ = ["web_search", "wikipedia_search", "python_repl", "download_and_read_file"]12345import requests
# Shared session that ignores ALL system proxy environment variables_session = requests.Session()_session.trust_env = False1234567891011121314151617181920212223242526import sysimport ioimport traceback
def python_repl(code: str) -> str: """Execute Python code for calculations or data processing.""" stdout_capture = io.StringIO() stderr_capture = io.StringIO() local_vars = {} try: sys.stdout = stdout_capture sys.stderr = stderr_capture exec(compile(code, "<string>", "exec"), {"__builtins__": __builtins__}, local_vars) except Exception: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return f"Error:\n{traceback.format_exc()}" finally: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ output = stdout_capture.getvalue() err = stderr_capture.getvalue() if err: return f"Stderr:\n{err}\nStdout:\n{output}" return output if output else "Code executed successfully (no output)."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import osimport requestsimport pandas as pdfrom tools._session import _session
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")os.makedirs(DATA_DIR, exist_ok=True)
def _parse_file(file_path: str, content_bytes: bytes, ext: str) -> str: """Parse file content based on extension and return as string.""" try: if ext == ".csv": df = pd.read_csv(file_path) return f"CSV file ({len(df)} rows, {len(df.columns)} columns):\n{df.to_string(index=False)}" elif ext in (".xlsx", ".xls"): # Read all sheets xl = pd.ExcelFile(file_path) parts = [] for sheet in xl.sheet_names: df = xl.parse(sheet) parts.append(f"Sheet '{sheet}' ({len(df)} rows, {len(df.columns)} columns):\n{df.to_string(index=False)}") return "\n\n".join(parts) elif ext in (".py", ".txt", ".md", ".json", ".xml", ".html", ""): return f"File contents:\n{content_bytes.decode('utf-8', errors='replace')[:5000]}" else: try: return f"File contents:\n{content_bytes.decode('utf-8', errors='replace')[:5000]}" except Exception: return f"Binary file, cannot display as text. Size: {len(content_bytes)} bytes." except Exception as e: return f"Failed to parse file: {e}"
def prefetch_file(task_id: str) -> str | None: """ Try to download the file for a task_id. Returns parsed file content string if found, None if no attachment exists. Caches file to data/ directory. """ # Check cache first cached = [f for f in os.listdir(DATA_DIR) if f.startswith(task_id)] if cached: file_path = os.path.join(DATA_DIR, cached[0]) ext = os.path.splitext(cached[0])[-1].lower() with open(file_path, "rb") as f: content_bytes = f.read() return _parse_file(file_path, content_bytes, ext)
file_url = f"{DEFAULT_API_URL}/files/{task_id}" try: response = _session.get(file_url, timeout=30) if response.status_code == 404: return None response.raise_for_status() except Exception: return None
# Determine extension ext = "" cd = response.headers.get("content-disposition", "") if "filename=" in cd: fname = cd.split("filename=")[-1].strip().strip('"') ext = os.path.splitext(fname)[-1].lower() content_type = response.headers.get("content-type", "") if not ext: if "csv" in content_type: ext = ".csv" elif "excel" in content_type or "spreadsheet" in content_type or "openxmlformats" in content_type: ext = ".xlsx" elif "text" in content_type: ext = ".txt"
# Save to data/ file_path = os.path.join(DATA_DIR, f"{task_id}{ext}") with open(file_path, "wb") as f: f.write(response.content)
return _parse_file(file_path, response.content, ext)
def download_and_read_file(task_id: str) -> str: """Download and read a file attachment for a given task_id. Supports CSV, Excel (.xlsx/.xls), and plain text files. """ result = prefetch_file(task_id) if result is None: return "No file attachment found for this task." return result12345678910111213141516171819202122232425262728293031323334353637383940import osimport jsonfrom tools._session import _session
def web_search(query: str) -> str: """Search Google via Serper API for current information. Use this for factual questions, recent events, or anything requiring web search. """ api_key = os.getenv("SERPER_API_KEY") if not api_key: return "SERPER_API_KEY not set." try: response = _session.post( "https://google.serper.dev/search", headers={"X-API-KEY": api_key, "Content-Type": "application/json"}, data=json.dumps({"q": query, "num": 5}), timeout=15, ) response.raise_for_status() data = response.json()
parts = [] # Answer box (direct answer) if "answerBox" in data: ab = data["answerBox"] answer = ab.get("answer") or ab.get("snippet") or "" if answer: parts.append(f"Direct answer: {answer}")
# Organic results for r in data.get("organic", [])[:5]: title = r.get("title", "") link = r.get("link", "") snippet = r.get("snippet", "") parts.append(f"Title: {title}\nURL: {link}\nSnippet: {snippet}")
return "\n---\n".join(parts) if parts else "No results found." except Exception as e: return f"Search error: {e}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import osimport requests
# Wikipedia needs the local proxy to be accessible from China_PROXY = os.getenv("LOCAL_PROXY", "http://127.0.0.1:7890")_wiki_session = requests.Session()_wiki_session.proxies = {"http": _PROXY, "https": _PROXY}_wiki_session.trust_env = False_wiki_session.headers.update({ "User-Agent": "Mozilla/5.0 (compatible; ResearchAgent/1.0; educational use)"})
def wikipedia_search(query: str) -> str: """Search Wikipedia for encyclopedic information.""" # Use Wikipedia REST API directly search_url = "https://en.wikipedia.org/w/api.php" try: # Step 1: search for page title search_resp = _wiki_session.get(search_url, timeout=15, params={ "action": "query", "list": "search", "srsearch": query, "srlimit": 3, "format": "json", }) search_resp.raise_for_status() results = search_resp.json().get("query", {}).get("search", []) if not results: return "No Wikipedia articles found."
# Step 2: fetch content of top result title = results[0]["title"] content_resp = _wiki_session.get(search_url, timeout=15, params={ "action": "query", "titles": title, "prop": "extracts", "exintro": False, "explaintext": True, "format": "json", }) content_resp.raise_for_status() pages = content_resp.json().get("query", {}).get("pages", {}) page = next(iter(pages.values())) text = page.get("extract", "") if not text: return f"Wikipedia article '{title}' has no extractable content." url = f"https://en.wikipedia.org/wiki/{title.replace(' ', '_')}" return f"Wikipedia: {title}\nURL: {url}\n\n{text[:3000]}" except Exception as e: return f"Wikipedia search failed: {e}".gitignoreAdded+6
app.py+140-7
requirements.txt+4-1
test_agent.pyAdded+30
tools/__init__.pyAdded+6
tools/_session.pyAdded+5
tools/calculator.pyAdded+26
tools/file_handler.pyAdded+90
tools/search.pyAdded+40
tools/wikipedia.pyAdded+51