Download agent.py from bhanuprakashg/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 8.69 kB
-
https://huggingface.co/spaces/bhanuprakashg/Final_Assignment_Template/resolve/main/agent.py
- Command line
-
hf download hf://spaces/bhanuprakashg/Final_Assignment_Template/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/bhanuprakashg/Final_Assignment_Template/resolve/main/agent.py
8.69 kB
| """LangGraph ReAct agent for the GAIA final assignment (Gemini + tools).""" | |
| import base64 | |
| import io | |
| import mimetypes | |
| import os | |
| import re | |
| import contextlib | |
| import traceback | |
| from dotenv import load_dotenv | |
| from langchain_core.messages import HumanMessage, SystemMessage | |
| from langchain_core.tools import tool | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| from langgraph.graph import START, MessagesState, StateGraph | |
| from langgraph.prebuilt import ToolNode, tools_condition | |
| load_dotenv(override=True) | |
| GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY") | |
| MODEL_NAME = os.getenv("GEMINI_MODEL", "gemini-3.8-flash") | |
| MAX_TOOL_OUTPUT = 8000 | |
| with open(os.path.join(os.path.dirname(__file__), "system_prompt.txt"), encoding="utf-8") as f: | |
| SYSTEM_PROMPT = f.read() | |
| def _clip(text: str) -> str: | |
| text = str(text) | |
| return text if len(text) <= MAX_TOOL_OUTPUT else text[:MAX_TOOL_OUTPUT] + "\n...[truncated]" | |
| def _llm(**kwargs): | |
| return ChatGoogleGenerativeAI( | |
| model=MODEL_NAME, google_api_key=GEMINI_API_KEY, temperature=0, **kwargs | |
| ) | |
| # ---------------------------------------------------------------- search tools | |
| def web_search(query: str) -> str: | |
| """Search the web (Tavily) and return up to 5 results with content. | |
| Args: | |
| query: The search query. | |
| """ | |
| from langchain_tavily import TavilySearch | |
| res = TavilySearch(max_results=5).invoke({"query": query}) | |
| items = res.get("results", []) if isinstance(res, dict) else res | |
| return _clip( | |
| "\n\n---\n\n".join( | |
| f"[{r.get('title', '')}]({r.get('url', '')})\n{r.get('content', '')}" for r in items | |
| ) | |
| ) | |
| def wiki_search(query: str) -> str: | |
| """Search Wikipedia and return the top 2 pages (long content). | |
| Args: | |
| query: The search query. | |
| """ | |
| from langchain_community.document_loaders import WikipediaLoader | |
| docs = WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=6000).load() | |
| return _clip( | |
| "\n\n---\n\n".join(f"[{d.metadata.get('source', '')}]\n{d.page_content}" for d in docs) | |
| ) | |
| def arxiv_search(query: str) -> str: | |
| """Search arXiv and return the top 3 paper abstracts. | |
| Args: | |
| query: The search query. | |
| """ | |
| from langchain_community.document_loaders import ArxivLoader | |
| docs = ArxivLoader(query=query, load_max_docs=3).load() | |
| return _clip("\n\n---\n\n".join(d.page_content[:1500] for d in docs)) | |
| def fetch_webpage(url: str) -> str: | |
| """Download a web page and return its readable text. | |
| Args: | |
| url: Full URL of the page. | |
| """ | |
| import requests | |
| from bs4 import BeautifulSoup | |
| r = requests.get(url, timeout=30, headers={"User-Agent": "Mozilla/5.0"}) | |
| r.raise_for_status() | |
| soup = BeautifulSoup(r.text, "html.parser") | |
| for t in soup(["script", "style", "nav", "footer"]): | |
| t.decompose() | |
| return _clip(re.sub(r"\n{3,}", "\n\n", soup.get_text("\n"))) | |
| def youtube_transcript(url: str) -> str: | |
| """Get the transcript of a YouTube video. | |
| Args: | |
| url: The YouTube video URL. | |
| """ | |
| from youtube_transcript_api import YouTubeTranscriptApi | |
| m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url) | |
| if not m: | |
| return "Could not parse video id." | |
| try: | |
| segs = YouTubeTranscriptApi().fetch(m.group(1)) | |
| return _clip(" ".join(s.text for s in segs)) | |
| except Exception as e: | |
| return ( | |
| f"Transcript unavailable ({type(e).__name__}); YouTube may be blocked from this server. " | |
| "Do NOT retry this tool. Use web_search for the video title, description or discussions of it; " | |
| "if that fails, give your best-guess answer." | |
| ) | |
| # ------------------------------------------------------------------ file tools | |
| def read_file(file_path: str) -> str: | |
| """Read a local file: txt/py/json/md, csv, xlsx/xls, or pdf. Returns its contents. | |
| Args: | |
| file_path: Local path to the file. | |
| """ | |
| ext = os.path.splitext(file_path)[1].lower() | |
| try: | |
| if ext in (".csv",): | |
| import pandas as pd | |
| return _clip(pd.read_csv(file_path).to_string()) | |
| if ext in (".xlsx", ".xls"): | |
| import pandas as pd | |
| sheets = pd.read_excel(file_path, sheet_name=None) | |
| return _clip("\n\n".join(f"## sheet: {n}\n{df.to_string()}" for n, df in sheets.items())) | |
| if ext == ".pdf": | |
| import fitz # pymupdf | |
| with fitz.open(file_path) as doc: | |
| return _clip("\n".join(p.get_text() for p in doc)) | |
| with open(file_path, encoding="utf-8", errors="replace") as f: | |
| return _clip(f.read()) | |
| except Exception as e: | |
| return f"Error reading file: {e}" | |
| def python_executor(code: str) -> str: | |
| """Execute Python code and return what it prints. Use print() for results. | |
| pandas, numpy, math, re, json, datetime are available. Use it for calculations and file processing. | |
| Args: | |
| code: Python source code. | |
| """ | |
| buf = io.StringIO() | |
| try: | |
| with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): | |
| exec(code, {"__name__": "__main__"}) | |
| except Exception: | |
| buf.write(traceback.format_exc(limit=3)) | |
| return _clip(buf.getvalue() or "(no output; use print())") | |
| def _media_message(file_path: str, prompt: str, default_mime: str) -> str: | |
| mime = mimetypes.guess_type(file_path)[0] or default_mime | |
| with open(file_path, "rb") as f: | |
| data = base64.b64encode(f.read()).decode() | |
| kind = "image_url" if mime.startswith("image") else "media" | |
| block = ( | |
| {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}} | |
| if kind == "image_url" | |
| else {"type": "media", "mime_type": mime, "data": data} | |
| ) | |
| msg = HumanMessage(content=[{"type": "text", "text": prompt}, block]) | |
| return _clip(_llm().invoke([msg]).content) | |
| def analyze_image(file_path: str, question: str) -> str: | |
| """Look at a local image file (png/jpg) and answer a question about it (chess boards, charts, etc.). | |
| Args: | |
| file_path: Local path to the image. | |
| question: What to find out about the image. | |
| """ | |
| try: | |
| return _media_message(file_path, question, "image/png") | |
| except Exception as e: | |
| return f"Error analyzing image: {e}" | |
| def transcribe_audio(file_path: str) -> str: | |
| """Transcribe a local audio file (mp3/wav) word for word. | |
| Args: | |
| file_path: Local path to the audio file. | |
| """ | |
| try: | |
| return _media_message(file_path, "Transcribe this audio verbatim. Output only the transcript.", "audio/mpeg") | |
| except Exception as e: | |
| return f"Error transcribing audio: {e}" | |
| TOOLS = [ | |
| web_search, | |
| wiki_search, | |
| arxiv_search, | |
| fetch_webpage, | |
| youtube_transcript, | |
| read_file, | |
| python_executor, | |
| analyze_image, | |
| transcribe_audio, | |
| ] | |
| def build_graph(): | |
| llm_with_tools = _llm().bind_tools(TOOLS) | |
| sys_msg = SystemMessage(content=SYSTEM_PROMPT) | |
| def assistant(state: MessagesState): | |
| return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]} | |
| builder = StateGraph(MessagesState) | |
| builder.add_node("assistant", assistant) | |
| builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=True)) | |
| builder.add_edge(START, "assistant") | |
| builder.add_conditional_edges("assistant", tools_condition) | |
| builder.add_edge("tools", "assistant") | |
| return builder.compile() | |
| def direct_answer(question: str) -> str: | |
| """Last-resort: answer without tools (used when the tool loop fails or runs out of steps).""" | |
| msgs = [ | |
| SystemMessage(content=SYSTEM_PROMPT), | |
| HumanMessage(content=question + "\n\nTools are unavailable. Give your best-guess answer from your own knowledge now."), | |
| ] | |
| return extract_final_answer(_llm().invoke(msgs).content) | |
| def extract_final_answer(text) -> str: | |
| """Return only what follows 'FINAL ANSWER:' (GAIA uses exact match).""" | |
| if isinstance(text, list): # Gemini may return content blocks | |
| text = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in text) | |
| text = str(text) | |
| m = re.search(r"FINAL ANSWER:\s*(.*)", text, re.IGNORECASE | re.DOTALL) | |
| ans = (m.group(1) if m else text).strip().splitlines()[0] if (m or text.strip()) else "" | |
| return ans.strip().rstrip(".").strip() | |
| if __name__ == "__main__": | |
| g = build_graph() | |
| out = g.invoke({"messages": [HumanMessage(content="What is 12 * 7 plus the number of planets in the solar system?")]}) | |
| print(extract_final_answer(out["messages"][-1].content)) | |