assignment_agent / custom_tools.py
Arbnor Tefiki
First commit
94b3868
raw
history blame
2.95 kB
import requests
from duckduckgo_search import DDGS
from langchain_core.tools import tool
@tool
def reverse_text(input: str) -> str:
"""Reverse the characters in a text or string.
Args:
query: The text or string to reverse.
"""
return input[::-1]
@tool
def web_search(query: str) -> str:
"""Perform a web search using DuckDuckGo and return the top 3 summarized results.
Args:
query: The search query to look up.
"""
try:
results = []
with DDGS() as ddgs:
for r in ddgs.text(query, max_results=3):
title = r.get("title", "")
snippet = r.get("body", "")
url = r.get("href", "")
if title and snippet:
results.append(f"{title}: {snippet} (URL: {url})")
if not results:
return "No results found."
return "\n\n---\n\n".join(results)
except Exception as e:
return f"Web search error: {e}"
@tool
def calculate(expression: str) -> str:
"""Evaluate a simple math expression and return the result.
Args:
expression: A string containing the math expression to evaluate.
"""
try:
allowed_names = {
"abs": abs,
"round": round,
"min": min,
"max": max,
"pow": pow,
}
result = eval(expression, {"__builtins__": None}, allowed_names)
return str(result)
except Exception as e:
return f"Calculation error: {e}"
@tool
def wikipedia_summary(query: str) -> str:
"""Retrieve a summary of a topic from Wikipedia.
Args:
query: The subject or topic to summarize.
"""
try:
response = requests.get(
f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}", timeout=10
)
response.raise_for_status()
data = response.json()
return data.get("extract", "No summary found.")
except Exception as e:
return f"Wikipedia error: {e}"
@tool
def define_term(term: str) -> str:
"""Provide a dictionary-style definition of a given term using an online API.
Args:
term: The word or term to define.
"""
try:
response = requests.get(
f"https://api.dictionaryapi.dev/api/v2/entries/en/{term}", timeout=10
)
response.raise_for_status()
data = response.json()
meanings = data[0].get("meanings", [])
if meanings:
defs = meanings[0].get("definitions", [])
if defs:
return defs[0].get("definition", "Definition not found.")
return "Definition not found."
except Exception as e:
return f"Definition error: {e}"
# List of tools to register with your agent
TOOLS = [web_search, calculate, wikipedia_summary, define_term, reverse_text]