-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
66 lines (52 loc) · 1.73 KB
/
Copy pathtools.py
File metadata and controls
66 lines (52 loc) · 1.73 KB
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
import json
from urllib.parse import quote_plus
from urllib.request import Request, urlopen
from crewai.tools import tool
def _fetch_json(url: str) -> dict:
request = Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urlopen(request, timeout=12) as response:
return json.loads(response.read().decode("utf-8"))
@tool("wikipedia_summary")
def wikipedia_summary(topic: str) -> str:
"""Return a short Wikipedia summary for a topic."""
if not topic.strip():
return "No topic provided."
url = (
"https://en.wikipedia.org/api/rest_v1/page/summary/"
f"{quote_plus(topic.strip())}"
)
try:
data = _fetch_json(url)
summary = data.get("extract") or "No summary found on Wikipedia."
title = data.get("title", topic)
return f"{title}: {summary}"
except Exception as exc:
return f"Wikipedia lookup failed: {exc}"
@tool("duckduckgo_instant_answer")
def duckduckgo_instant_answer(query: str) -> str:
"""Return quick facts/snippets from DuckDuckGo instant answer API."""
if not query.strip():
return "No query provided."
url = (
"https://api.duckduckgo.com/?format=json&no_html=1&skip_disambig=1&q="
f"{quote_plus(query.strip())}"
)
try:
data = _fetch_json(url)
abstract = data.get("AbstractText", "").strip()
heading = data.get("Heading", "").strip()
if abstract:
if heading:
return f"{heading}: {abstract}"
return abstract
related = data.get("RelatedTopics", [])
snippets = []
for item in related[:5]:
text = item.get("Text") if isinstance(item, dict) else None
if text:
snippets.append(f"- {text}")
if snippets:
return "No direct abstract. Related snippets:\n" + "\n".join(snippets)
return "No instant answer found."
except Exception as exc:
return f"DuckDuckGo lookup failed: {exc}"