Spaces:
Sleeping
Sleeping
File size: 2,949 Bytes
94b3868 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
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]
|