Spaces:
Build error
Build error
Update langgraph_agent.py
Browse files1234567836 unmodified lines454647484950515253545556575859606162636465666714 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101116 unmodified lines1181191201211221231241251261272 unmodified lines1301311321331341353 unmodified lines1391401411421431441451466 unmodified lines1531541551561571581598 unmodified lines16816917017117217317414 unmodified lines189190191192import osimport ioimport contextlibimport pandas as pd # Added for Excel file handlingfrom typing import Dict, List, Union # Added for type hintingfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_condition, ToolNode36 unmodified linesdef wiki_search(query: str) -> dict:"""Search Wikipedia for a query and return up to 2 documents."""try:docs = WikipediaLoader(query=query, load_max_docs=2, lang="en").load() # Added lang="en" for clarityif not docs:return {"wiki_results": f"No documents found on Wikipedia for '{query}'."}formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata.get("source", "N/A")}"/>\n{d.page_content}' # Added .get for safetyfor d in docs)return {"wiki_results": formatted}except Exception as e:# Log the full error for debugging if possibleprint(f"Error in wiki_search tool: {e}")return {"wiki_results": f"Error occurred while searching Wikipedia for '{query}'. Details: {str(e)}"}@tooldef web_search(query: str) -> dict:"""Perform a web search (via Tavily) and return up to 3 results."""try: # Added try-except block for robustnessdocs = TavilySearchResults(max_results=3).invoke(query=query)formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata["source"]}"/>\n{d.page_content}'14 unmodified lines)return {"arvix_results": formatted}@tooldef read_file_content(file_path: str) -> Dict[str, str]:"""Reads the content of a file and returns it.Supports text (.txt), Python (.py), and Excel (.xlsx) files.For other file types, returns a message indicating limited support."""try:_, file_extension = os.path.splitext(file_path)content = ""if file_extension.lower() in (".txt", ".py"):with open(file_path, "r", encoding="utf-8") as f:content = f.read()elif file_extension.lower() == ".xlsx":# Ensure pandas is installed for this.df = pd.read_excel(file_path)content = df.to_string() # Convert Excel to string representationelif file_extension.lower() == ".mp3":content = "Audio file provided. Unable to directly process audio. Consider using a transcription service if available."elif file_extension.lower() == ".png":content = "Image file provided. Unable to directly process images. Consider using an OCR or image analysis service if available."else:content = f"Unsupported file type: {file_extension}. Only .txt, .py, and .xlsx files are fully supported for reading content."return {"file_content": content, "file_name": file_path}except FileNotFoundError:return {"file_error": f"File not found: {file_path}. Please ensure the file exists in the environment."}except Exception as e:6 unmodified linesIf there's an error during execution, it returns the error message."""old_stdout = io.StringIO()# Redirect stdout to capture print statementswith contextlib.redirect_stdout(old_stdout):try:# Create a dictionary to hold the execution scope for execexec_globals = {}exec_locals = {}exec(code, exec_globals, exec_locals)2 unmodified linesexcept Exception as e:return {"execution_error": str(e)}API_KEY = os.getenv("GEMINI_API_KEY")HF_SPACE_TOKEN = os.getenv("HF_SPACE_TOKEN")3 unmodified linestools = [multiply, add, subtract, divide, modulus,wiki_search, web_search, arvix_search,read_file_content, # Added new toolpython_interpreter, # Added new tool]6 unmodified lines"""Build the LangGraph agent with chosen LLM (default: Gemini)."""if provider == "gemini":llm = ChatGoogleGenerativeAI(model= "gemini-2.5-flash-preview-05-20",temperature=1.0,max_retries=2,api_key=GEMINI_API_KEY,8 unmodified linestemperature=0,)else:raise ValueError("Invalid provider. Choose 'openai' or 'huggingface'.")llm_with_tools = llm.bind_tools(tools)14 unmodified lines# This block is intentionally left empty as per user request to remove examples.# Your agent will interact with the graph by invoking it with messages.pass12345678910111236 unmodified lines4950515253545556575859606162636465666768697014 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231246 unmodified lines1311321331341351361371382 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631643 unmodified lines1681691701711721731741751761776 unmodified lines1841851861871881891908 unmodified lines19920020120220320420514 unmodified lines220221222import osimport ioimport contextlibimport pandas as pdfrom typing import Dict, List, Union# New imports for image and audio processingfrom PIL import Image as PILImage # Used for type checking/potential future local processingfrom huggingface_hub import InferenceClientfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_condition, ToolNode36 unmodified linesdef wiki_search(query: str) -> dict:"""Search Wikipedia for a query and return up to 2 documents."""try:docs = WikipediaLoader(query=query, load_max_docs=2, lang="en").load()if not docs:return {"wiki_results": f"No documents found on Wikipedia for '{query}'."}formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata.get("source", "N/A")}"/>\n{d.page_content}'for d in docs)return {"wiki_results": formatted}except Exception as e:print(f"Error in wiki_search tool: {e}")return {"wiki_results": f"Error occurred while searching Wikipedia for '{query}'. Details: {str(e)}"}@tooldef web_search(query: str) -> dict:"""Perform a web search (via Tavily) and return up to 3 results."""try:docs = TavilySearchResults(max_results=3).invoke(query=query)formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata["source"]}"/>\n{d.page_content}'14 unmodified lines)return {"arvix_results": formatted}# Initialize Hugging Face Inference ClientHF_API_TOKEN = os.getenv("HF_API_TOKEN")HF_INFERENCE_CLIENT = Noneif HF_API_TOKEN:HF_INFERENCE_CLIENT = InferenceClient(token=HF_API_TOKEN)else:print("WARNING: HF_API_TOKEN not set. Image tools will not function.")@tooldef read_file_content(file_path: str) -> Dict[str, str]:"""Reads the content of a file and returns its primary information.For text/code/excel, returns content. For media, returns a prompt to use specific tools."""try:_, file_extension = os.path.splitext(file_path)file_extension = file_extension.lower()if file_extension in (".txt", ".py"):with open(file_path, "r", encoding="utf-8") as f:content = f.read()return {"file_type": "text/code", "file_name": file_path, "file_content": content}elif file_extension == ".xlsx":df = pd.read_excel(file_path)content = df.to_string()return {"file_type": "excel", "file_name": file_path, "file_content": content}elif file_extension in (".jpeg", ".jpg", ".png"):# Indicate that it's an image and needs to be described by a specific toolreturn {"file_type": "image", "file_name": file_path, "file_content": f"Image file '{file_path}' detected. Use 'describe_image' tool to get a textual description."}elif file_extension == ".mp3":# Indicate that it's an audio file and the LLM should process it nativelyreturn {"file_type": "audio", "file_name": file_path, "file_content": f"Audio file '{file_path}' detected. The LLM should process this natively."}else:return {"file_type": "unsupported", "file_name": file_path, "file_content": f"Unsupported file type: {file_extension}. Only .txt, .py, .xlsx, .jpeg, .jpg, .png, .mp3 files are recognized."}except FileNotFoundError:return {"file_error": f"File not found: {file_path}. Please ensure the file exists in the environment."}except Exception as e:6 unmodified linesIf there's an error during execution, it returns the error message."""old_stdout = io.StringIO()with contextlib.redirect_stdout(old_stdout):try:exec_globals = {}exec_locals = {}exec(code, exec_globals, exec_locals)2 unmodified linesexcept Exception as e:return {"execution_error": str(e)}@tooldef describe_image(image_path: str) -> Dict[str, str]:"""Generates a textual description for an image file (JPEG, JPG, PNG) using an image-to-text modelfrom the Hugging Face Inference API. Requires HF_API_TOKEN environment variable to be set."""if not HF_INFERENCE_CLIENT:return {"error": "Hugging Face API token not configured for image description. Cannot use this tool."}try:with open(image_path, "rb") as f:image_bytes = f.read()description = HF_INFERENCE_CLIENT.image_to_text(image_bytes)return {"image_description": description, "image_path": image_path}except FileNotFoundError:return {"error": f"Image file not found: {image_path}. Please ensure the file exists."}except Exception as e:return {"error": f"Error describing image {image_path}: {str(e)}"}API_KEY = os.getenv("GEMINI_API_KEY")HF_SPACE_TOKEN = os.getenv("HF_SPACE_TOKEN")3 unmodified linestools = [multiply, add, subtract, divide, modulus,wiki_search, web_search, arvix_search,read_file_content,python_interpreter,describe_image, # Added new tool# transcribe_audio, # Removed as per user request]6 unmodified lines"""Build the LangGraph agent with chosen LLM (default: Gemini)."""if provider == "gemini":llm = ChatGoogleGenerativeAI(model= "gemini-1.5-flash-preview-05-20", # This model is capable of native audio processingtemperature=1.0,max_retries=2,api_key=GEMINI_API_KEY,8 unmodified linestemperature=0,)else:raise ValueError("Invalid provider. Choose 'gemini' or 'huggingface'.")llm_with_tools = llm.bind_tools(tools)14 unmodified lines# This block is intentionally left empty as per user request to remove examples.# Your agent will interact with the graph by invoking it with messages.pass
langgraph_agent.py+57-27