FinalAgentProject / tools.py
WeByT3's picture
Update tools.py
3e615dc verified
raw
history blame
2.34 kB
from langchain_core.tools import tool
import wikipediaapi
import pandas as pd
@tool
def add(a: int, b: int) -> int:
"""
Sums two values and returns the result of the sum
Args:
a: first number
b: second number
"""
return a + b
@tool
def subtract(a: int, b: int) -> int:
"""
Subtracts one value from another and returns the result of the sum
Args:
a: first number
b: second number
"""
return a - b
@tool
def multiply(a: int, b: int) -> int:
"""
Multiplies two values and returns the result of the sum
Args:
a: first number
b: second number
"""
return a * b
@tool
def divide(a: int, b: int) -> int:
"""
Divides two values and returns the result of the sum
Args:
a: numerator
b: denominator
"""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
@tool
def search_wikipedia(page_title: str, language: str) -> str:
"""
This tool searches Wikipedia for a specific page and returns its text and any HTML tables it contains.
Args:
page_title: Title of the Wikipedia page.
language: Language code (e.g., "en", "es", "fr").
Returns:
A string containing the page title, text, and any extracted tables in markdown format.
"""
try:
wiki_wiki = wikipediaapi.Wikipedia(
user_agent='AIAgent (gabriel_abilleira@tutanota.com)',
language=language,
extract_format=wikipediaapi.ExtractFormat.HTML
)
page = wiki_wiki.page(page_title)
if not page.exists():
return f"Error: Page '{page_title}' not found in language '{language}'."
# Use the URL to read tables
tables = pd.read_html(page.fullurl)
markdown_tables = []
for i, table in enumerate(tables):
if isinstance(table, pd.DataFrame):
markdown = table.to_markdown(index=False)
markdown_tables.append(f"\n---\n**Table {i + 1}:**\n{markdown}")
table_output = "\n".join(markdown_tables) if markdown_tables else "No tables found on this page."
return f"Title: {page.title}\n\nText: {page.summary}\n\n{table_output}"
except Exception as e:
return f"Error retrieving Wikipedia content: {str(e)}"