Create wikipedia_search.py
Browse files- tools/wikipedia_search.py +40 -0
tools/wikipedia_search.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import wikipedia
|
| 2 |
+
from langchain_core.tools import tool
|
| 3 |
+
from loguru import logger
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@tool("wikipedia_search_tool", parse_docstring=True)
|
| 7 |
+
def wikipedia_search(query: str) -> str:
|
| 8 |
+
"""
|
| 9 |
+
Searches Wikipedia for the given query.
|
| 10 |
+
Args:
|
| 11 |
+
query (str): The search query to look up on Wikipedia.
|
| 12 |
+
Returns:
|
| 13 |
+
str: A formatted string with the search results, page title and url.
|
| 14 |
+
"""
|
| 15 |
+
logger.info(f"use wikipedia_search_tool with param: {query}")
|
| 16 |
+
|
| 17 |
+
search_results = wikipedia.search(query, results=5)
|
| 18 |
+
|
| 19 |
+
if not search_results:
|
| 20 |
+
return "No results found for the query."
|
| 21 |
+
|
| 22 |
+
result_text = ""
|
| 23 |
+
try:
|
| 24 |
+
for i, title in enumerate(search_results, 1):
|
| 25 |
+
page = wikipedia.page(search_results[i - 1], auto_suggest=False)
|
| 26 |
+
result_text += f"{i}. [{title}]({page.url})\n"
|
| 27 |
+
|
| 28 |
+
return result_text
|
| 29 |
+
|
| 30 |
+
except wikipedia.DisambiguationError as e:
|
| 31 |
+
return "Disambiguation page found. Possible matches:\n{}".format('\n'.join(e.options))
|
| 32 |
+
except wikipedia.PageError as e:
|
| 33 |
+
return f"Page not found. Try another search term."
|
| 34 |
+
except Exception as e:
|
| 35 |
+
return f"An error occurred: {str(e)}"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
print(wikipedia_search.invoke("Mercedes Sosa discography"))
|
| 40 |
+
|