File size: 1,571 Bytes
88ce352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests

def fetch_wikipedia_article(query: str) -> str:
    """
    Fetch the plain text of a Wikipedia article using the Wikipedia API.
    """
    url = "https://en.wikipedia.org/w/api.php"
    params = {
        "action": "query",
        "prop": "extracts",
        "explaintext": True,
        "format": "json",
        "titles": query,
    }
    response = requests.get(url, params=params)
    data = response.json()
    pages = data.get("query", {}).get("pages", {})
    page = next(iter(pages.values()))
    return page.get("extract", "No content found for this query.")


def search_wikipedia(query: str) -> str:
    """
    Search for a Wikipedia article title using the Wikipedia API.
    """
    url = "https://en.wikipedia.org/w/api.php"
    params = {
        "action": "query",
        "list": "search",
        "srsearch": query,
        "format": "json",
    }
    response = requests.get(url, params=params)
    data = response.json()
    results = data.get("query", {}).get("search", [])
    if results:
        return "\n".join([f"{r['title']}" for r in results])
    return "No search results found."


class WikipediaTool:
    description = "Fetches plain text from a Wikipedia article. Input should be the article title."

    def __call__(self, query: str) -> str:
        return fetch_wikipedia_article(query)


class WikipediaSearchTool:
    description = "Searches Wikipedia for article titles related to a query. Input should be a question or topic."

    def __call__(self, query: str) -> str:
        return search_wikipedia(query)