Spaces:
Sleeping
Sleeping
mchinea commited on
Commit ·
a92d3ed
1
Parent(s): 81917a3
add my agent and tools
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""LangGraph Agent"""import osfrom dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import START, StateGraphfrom langgraph.prebuilt import tools_condition, ToolNodefrom langgraph.graph import START, StateGraph, MessagesStatefrom langchain_core.messages import SystemMessage, HumanMessage
from tools import level1_tools
load_dotenv()
# Build graph functiondef build_agent_graph(): """Build the graph""" # Load environment variables from .env file llm = ChatOpenAI(model="gpt-4o-mini") # Bind tools to LLM llm_with_tools = llm.bind_tools(level1_tools)
# Node def assistant(state: MessagesState): """Assistant node""" return {"messages": [llm_with_tools.invoke(state["messages"])]} builder = StateGraph(MessagesState) builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(level1_tools)) builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", tools_condition, ) builder.add_edge("tools", "assistant")
# Compile graph return builder.compile()
# testif __name__ == "__main__": question1 = "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)?" question2 = "Convert 10 miles to kilometers." # Build the graph graph = build_agent_graph() # Run the graph messages = [HumanMessage(content=question1)] messages = graph.invoke({"messages": messages}) for m in messages["messages"]: m.pretty_print()3 unmodified lines45678910111213141516171821 unmodified lines404142434445463 unmodified linesimport 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."21 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None3 unmodified lines456789101112131415161718192021 unmodified lines424344454647483 unmodified linesimport inspectimport pandas as pdfrom agent import build_agent_graph# (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 MyAgent:def __init__(self):print("MyAgent initialized.")self.graph = build_agent_graph()def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."21 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = MyAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import osimport random
from typing import Dictfrom pathlib import Path
from langchain_core.tools import tool
from langchain_core.messages import ToolMessagefrom langchain_tavily import TavilySearchfrom langchain_community.document_loaders import WikipediaLoaderfrom langchain_community.document_loaders import ArxivLoader
@tooldef web_search(query: str) -> ToolMessage: """Search in the web with Tavily for a query and return maximum 5 results. Args: query: The search query. Returns: Tavily output, and snippet for the top 5 results """ return TavilySearch(max_results=5, include_images=False).invoke({"query": query})
@tooldef wikipedia_search(query: str) -> Dict[str, list]: """Search Wikipedia for a given query and return the first 5 results. Args: query: The search term or topic. Returns: A dictionary containing the formatted Wikipedia results. """ search_docs = WikipediaLoader(query=query, load_max_docs=5).load() formatted_search_docs = "\n\n---\n\n".join( [ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>' for doc in search_docs ] ) return {"wiki_results": formatted_search_docs}
#Mathematical tools@tooldef multiply(a: float, b: float) -> float: """Multiply two numbers. Args: a: first number b: second number Returns: Multiplication result """ return a * b
@tooldef add(a: float, b: float) -> float: """Add two numbers. Args: a: first number b: second number Returns: Addition result """ return a + b
@tooldef subtract(a: float, b: float) -> float: """Subtract two numbers. Args: a: first number b: second number Returns: Subtraction result """ return a - b
@tooldef divide(a: float, b: float) -> float: """Divide two numbers. Args: a: first number b: second number Returns: Division result """ if b == 0: raise ValueError("Cannot divide by zero.") return a / b
@tooldef modulus(a: int, b: int) -> int: """Get the modulus of two numbers. Args: a: first number b: second number Returns: Modulus result """ return a % b
from langchain_core.tools import tool
@tooldef convert_units(value: float, from_unit: str, to_unit: str) -> float: """ Converts a value from one unit to another.
Args: value: The numerical value to convert. from_unit: The original unit (e.g. 'miles', 'kg', 'celsius'). to_unit: The target unit (e.g. 'kilometers', 'lb', 'fahrenheit').
Supported conversions: - miles <-> kilometers - kilograms <-> pounds - celsius <-> fahrenheit
Returns: The converted value result. """ conversions = { ("miles", "kilometers"): lambda v: v * 1.60934, ("kilometers", "miles"): lambda v: v / 1.60934, ("kilograms", "pounds"): lambda v: v * 2.20462, ("pounds", "kilograms"): lambda v: v / 2.20462, ("celsius", "fahrenheit"): lambda v: (v * 9/5) + 32, ("fahrenheit", "celsius"): lambda v: (v - 32) * 5/9, }
key = (from_unit.lower(), to_unit.lower()) if key not in conversions: raise ValueError(f"Conversion from {from_unit} to {to_unit} not supported.")
return conversions[key](value)
@tooldef query_table_data(file_path: str, query: str, sheet_name: str = None) -> str: """ Loads a table from CSV or Excel and filters it using a pandas query.
Args: file_path: Path to the table file (.xlsx, .xls). query: A pandas-compatible query string, e.g., "Age > 30 and Country == 'USA'". sheet_name: Optional sheet name if the file is Excel.
Returns: A string representation (markdown) of the filtered table (max 10 rows). """ try: import pandas as pd path = Path(file_path) if not path.exists(): raise FileNotFoundError(f"File not found: {file_path}") ext = path.suffix.lower() if ext == ".csv": df = pd.read_csv(path) elif ext in [".xlsx", ".xls"]: df = pd.read_excel(path, sheet_name=sheet_name) else: raise ValueError(f"Unsupported file extension: {ext}") try: filtered_df = df.query(query) return filtered_df.head(10).to_markdown(index=False) except Exception as e: raise ValueError(f"Invalid query: {query}. Error: {e}") except ImportError: return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
@tooldef arvix_search(query: str) -> str: """Search Arxiv for a query and return maximum 5 result. Args: query: The search query. Returns: A dictionary containing the formatted Arvix results, and snippet for the top 5 results. """ search_docs = ArxivLoader(query=query, load_max_docs=5).load() formatted_search_docs = "\n\n---\n\n".join( [ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>' for doc in search_docs ]) return {"arvix_results": formatted_search_docs}
level1_tools = [ multiply, add, subtract, divide, modulus, wikipedia_search, web_search, arvix_search, convert_units, query_table_data]agent.pyAdded+55
app.py+5-3
tools.pyAdded+203