Spaces:
Build error
Build error
Update langgraph_agent.py
Browse files3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152537 unmodified lines61626364656667686970717273747576777879808182831 unmodified line858687888990913 unmodified lines95969798991001011021031043 unmodified lines1081091101111121131141151161171181191201214 unmodified lines1261271281291301311321331341357 unmodified lines1431441451461471481491501511526 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951967 unmodified lines2042052062072082092102112122135 unmodified lines2192202212222232243 unmodified linesimport 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, ToolNodefrom langchain_openai import ChatOpenAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain_core.messages import SystemMessage, HumanMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.tools import tool@tooldef multiply(a: int, b: int) -> int:"""Multiply two integers."""return a * b@tooldef add(a: int, b: int) -> int:"""Add two integers."""return a + b@tooldef subtract(a: int, b: int) -> int:"""Subtract the second integer from the first."""return a - b@tooldef divide(a: int, b: int) -> float:"""Divide first integer by second; error if divisor is zero."""if b == 0:raise ValueError("Cannot divide by zero.")return a / b@tooldef modulus(a: int, b: int) -> int:"""Return the remainder of dividing first integer by second."""return a % b@tooldef 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:7 unmodified linesprint(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}'for d in docs)return {"web_results": formatted}except Exception as e:print(f"Error in web_search tool: {e}")return {"web_results": f"Error occurred while searching the web for '{query}'. Details: {str(e)}"}@tooldef arvix_search(query: str) -> dict:"""Search arXiv for a query and return up to 3 paper excerpts."""docs = ArxivLoader(query=query, load_max_docs=3).load()formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata["source"]}"/>\n{d.page_content[:1000]}'1 unmodified line)return {"arvix_results": formatted}# Initialize Hugging Face Inference ClientHF_API_TOKEN = os.getenv("HF_API_TOKEN")HF_INFERENCE_CLIENT = Noneif HF_API_TOKEN:3 unmodified lines@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()3 unmodified linescontent = 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 needs to be transcribed by a specific toolreturn {"file_type": "audio", "file_name": file_path, "file_content": f"Audio file '{file_path}' detected. Use 'transcribe_audio' tool to get the text transcription."}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."}4 unmodified lines@tooldef python_interpreter(code: str) -> Dict[str, str]:"""Executes Python code and returns its standard output.If there's an error during execution, it returns the error message."""old_stdout = io.StringIO()with contextlib.redirect_stdout(old_stdout):try:7 unmodified lines@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:6 unmodified linesexcept Exception as e:return {"error": f"Error describing image {image_path}: {str(e)}"}API_KEY = os.getenv("GEMINI_API_KEY")HF_API_TOKEN = os.getenv("HF_SPACE_TOKEN")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")tools = [multiply, add, subtract, divide, modulus,wiki_search, web_search, arvix_search,read_file_content,python_interpreter,describe_image,]with open("prompt.txt", "r", encoding="utf-8") as f:system_prompt = f.read()sys_msg = SystemMessage(content=system_prompt)def build_graph(provider: str = "gemini"):"""Build the LangGraph agent with chosen LLM (default: Gemini)."""if provider == "gemini":llm = ChatGoogleGenerativeAI(model= "gemini-2.5-pro-preview-05-06", # Reverted model to gemini-2.5-pro-preview-05-06temperature=1.0,max_retries=2,api_key=GEMINI_API_KEY,max_tokens=5000)elif provider == "huggingface":llm = ChatHuggingFace(llm=HuggingFaceEndpoint(7 unmodified linesllm_with_tools = llm.bind_tools(tools)def assistant(state: MessagesState):messages_to_send = [sys_msg] + state["messages"]llm_response = llm_with_tools.invoke(messages_to_send)print(f"LLM Raw Response: {llm_response}") # Add this linereturn {"messages": [llm_response]}builder = StateGraph(MessagesState)builder.add_node("assistant", assistant)5 unmodified linesreturn builder.compile()if __name__ == "__main__":# 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.pass3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546477 unmodified lines5556575859606162636465666768697071727374751 unmodified line7778798081823 unmodified lines8687888990913 unmodified lines95969798991001011021031041051064 unmodified lines1111121131141151167 unmodified lines1241251261271281296 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821837 unmodified lines1911921931941951961971981992005 unmodified lines2062072082093 unmodified linesimport pandas as pdfrom typing import Dict, List, Unionfrom PIL import Image as PILImagefrom huggingface_hub import InferenceClientfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_condition, ToolNodefrom langchain_openai import ChatOpenAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain_core.messages import SystemMessage, HumanMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.tools import toolfrom langchain_google_community.tools.Google Search import GoogleSearchResults@tooldef multiply(a: int, b: int) -> int:return a * b@tooldef add(a: int, b: int) -> int:return a + b@tooldef subtract(a: int, b: int) -> int:return a - b@tooldef divide(a: int, b: int) -> float:if b == 0:raise ValueError("Cannot divide by zero.")return a / b@tooldef modulus(a: int, b: int) -> int:return a % b@tooldef wiki_search(query: str) -> dict:try:docs = WikipediaLoader(query=query, load_max_docs=2, lang="en").load()if not docs:7 unmodified linesprint(f"Error in wiki_search tool: {e}")return {"wiki_results": f"Error occurred while searching Wikipedia for '{query}'. Details: {str(e)}"}Google Search_tool = GoogleSearchResults(api_key=os.getenv("GOOGLE_API_KEY"),engine_id=os.getenv("GOOGLE_CSE_ID"))@tooldef google_web_search(query: str) -> dict:try:docs = Google Search_tool.invoke(query)return {"google_web_results": docs}except Exception as e:print(f"Error in google_web_search tool: {e}")return {"google_web_results": f"Error occurred while searching the web for '{query}'. Details: {str(e)}"}@tooldef arvix_search(query: str) -> dict:docs = ArxivLoader(query=query, load_max_docs=3).load()formatted = "\n\n---\n\n".join(f'<Document source="{d.metadata["source"]}"/>\n{d.page_content[:1000]}'1 unmodified line)return {"arvix_results": formatted}HF_API_TOKEN = os.getenv("HF_API_TOKEN")HF_INFERENCE_CLIENT = Noneif HF_API_TOKEN:3 unmodified lines@tooldef read_file_content(file_path: str) -> Dict[str, str]:try:_, file_extension = os.path.splitext(file_path)file_extension = file_extension.lower()3 unmodified linescontent = 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"):return {"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":return {"file_type": "audio", "file_name": file_path, "file_content": f"Audio file '{file_path}' detected. Use 'transcribe_audio' tool to get the text transcription."}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."}4 unmodified lines@tooldef python_interpreter(code: str) -> Dict[str, str]:old_stdout = io.StringIO()with contextlib.redirect_stdout(old_stdout):try:7 unmodified lines@tooldef describe_image(image_path: str) -> Dict[str, str]:if not HF_INFERENCE_CLIENT:return {"error": "Hugging Face API token not configured for image description. Cannot use this tool."}try:6 unmodified linesexcept Exception as e:return {"error": f"Error describing image {image_path}: {str(e)}"}@tooldef transcribe_audio(audio_path: str) -> Dict[str, str]:if not HF_INFERENCE_CLIENT:return {"error": "Hugging Face API token not configured for audio transcription. Cannot use this tool."}try:with open(audio_path, "rb") as f:audio_bytes = f.read()transcription = HF_INFERENCE_CLIENT.automatic_speech_recognition(audio_bytes)return {"audio_transcription": transcription, "audio_path": audio_path}except FileNotFoundError:return {"error": f"Audio file not found: {audio_path}. Please ensure the file exists."}except Exception as e:return {"error": f"Error transcribing audio {audio_path}: {str(e)}"}API_KEY = os.getenv("GEMINI_API_KEY")HF_API_TOKEN = os.getenv("HF_SPACE_TOKEN")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")tools = [multiply, add, subtract, divide, modulus,wiki_search,google_web_search,arvix_search,read_file_content,python_interpreter,describe_image,transcribe_audio,]with open("prompt.txt", "r", encoding="utf-8") as f:system_prompt = f.read()sys_msg = SystemMessage(content=system_prompt)def build_graph(provider: str = "gemini"):if provider == "gemini":llm = ChatGoogleGenerativeAI(model="gemini-2.5-pro-preview-05-06",temperature=1.0,max_retries=2,api_key=GEMINI_API_KEY,max_tokens=5000)elif provider == "huggingface":llm = ChatHuggingFace(llm=HuggingFaceEndpoint(7 unmodified linesllm_with_tools = llm.bind_tools(tools)def assistant(state: MessagesState):messages_to_send = [sys_msg] + state["messages"]llm_response = llm_with_tools.invoke(messages_to_send)print(f"LLM Raw Response: {llm_response}")return {"messages": [llm_response]}builder = StateGraph(MessagesState)builder.add_node("assistant", assistant)5 unmodified linesreturn builder.compile()if __name__ == "__main__":pass
langgraph_agent.py+43-58