Spaces:
Build error
Build error
Download tools.py from mludvig/agents-course-final: direct link, hf CLI and curl.
- Browser
- Download file 8.54 kB
-
https://huggingface.co/spaces/mludvig/agents-course-final/resolve/main/tools.py
- Command line
-
hf download hf://spaces/mludvig/agents-course-final/tools.py
-
curl -L -o tools.py https://huggingface.co/spaces/mludvig/agents-course-final/resolve/main/tools.py
8.54 kB
| from io import BytesIO | |
| import requests | |
| from langchain_core.tools import tool | |
| from langchain_community.utilities import OpenWeatherMapAPIWrapper, SerpAPIWrapper | |
| from langchain_community.tools import TavilySearchResults | |
| # from langchain_community.document_loaders import WikipediaLoader, ArxivLoader | |
| import wikipedia | |
| from markitdown import MarkItDown | |
| # @tool | |
| # def simple_answer_function(question: str) -> str: | |
| # """ | |
| # Answer a specific question using LLM common knowledge. | |
| # Args: | |
| # question (str): The question to be answered. | |
| # """ | |
| # print(f"simple_answer_function called with: {question}") | |
| # # Create the system message | |
| # system_message = SystemMessage(content="Answer the question as best as you can. Only provide the answer, no other text.") | |
| # # Create the initial messages | |
| # messages = [system_message, HumanMessage(content=question)] | |
| # # Get the response from the LLM | |
| # llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0) | |
| # response = llm.invoke(messages) | |
| # answer = response.content | |
| # print(f"simple_answer_function response: {answer}") | |
| # return answer | |
| def weather_tool(city: str, country_code: str) -> str: | |
| """ | |
| Get the current weather for a specific city. | |
| Args: | |
| city (str): The name of the city to get the weather for, e.g., "Auckland". | |
| country_code (str): Two letter ISO 3166 country code of the city, e.g., "NZ" for New Zealand. | |
| Returns: | |
| str: The current weather in the specified city. | |
| """ | |
| print(f"weather_tool called with: {city} {country_code}") | |
| # Create the system message | |
| # Create the OpenWeatherMap API wrapper | |
| weather_api = OpenWeatherMapAPIWrapper() | |
| # Get the weather data | |
| weather_data = weather_api.run(f"{city}, {country_code}") | |
| print(f"weather_tool response: {weather_data}") | |
| return weather_data | |
| def unit_converter_tool(value: float, from_unit: str, to_unit: str) -> float: | |
| """ | |
| Convert a value from one unit to another. | |
| Args: | |
| value (float): The value to be converted. | |
| from_unit (str): The unit of the input value. | |
| to_unit (str): The unit to convert the value to. | |
| Returns: | |
| float: The converted value. | |
| """ | |
| print(f"unit_converter_tool called with: {value} {from_unit} to {to_unit}") | |
| # Implement the conversion logic here | |
| if from_unit.lower() in ("°c", "c", "celsius") and to_unit.lower() in ("°f", "f", "fahrenheit"): | |
| converted_value = (value * 9/5) + 32 | |
| print(f"Converted value: {converted_value}") | |
| return converted_value | |
| # Raise an error if the conversion is not supported | |
| error = f"Conversion from {from_unit} to {to_unit} is not supported." | |
| print(error) | |
| raise ValueError(error) | |
| def wikipedia_tool(query: str, language: str) -> str: | |
| """ | |
| Search Wikipedia for a specific query. | |
| Args: | |
| query (str): The query to search for on Wikipedia. | |
| language (str): The language to use for the Wikipedia search, e.g., "en" for English. | |
| Returns: | |
| str: The HTML content of the Wikipedia page. | |
| """ | |
| print(f"wikipedia_tool called with: {query}") | |
| wikipedia.set_lang(language) | |
| # Search Wikipedia for the query | |
| search_results = wikipedia.search(query, results=1) | |
| if search_results: | |
| # Get the first result | |
| page_title = search_results[0] | |
| print(f"First Wikipedia search result: {page_title}") | |
| try: | |
| # Get the page summary | |
| page = wikipedia.page(page_title, auto_suggest=False, preload=True) | |
| print(f"wikipedia_tool title: {page.title}") | |
| # print(f"wikipedia_tool page summary: {page.summary[:100]}...") | |
| # Get the page content as a BytesIO object | |
| # Build a complete HTML page | |
| page_content = f"<html><head><title>{page.title}</title></head><body>{page.html()}</body></html>" | |
| page_io = BytesIO(page_content.encode("utf-8")) | |
| # Convert the page content from HTML to Markdown | |
| markdown_converter = MarkItDown() | |
| markdown_result = markdown_converter.convert(page_io) | |
| # Get the markdown content | |
| markdown_content = markdown_result.markdown | |
| print(f"wikipedia_tool markdown content: {markdown_content.splitlines()[0]}...") | |
| return markdown_content | |
| except Exception as e: | |
| error = f"Error retrieving Wikipedia page: {e}" | |
| print(error) | |
| return error | |
| error = f"No results found for query: {query}" | |
| print(error) | |
| return error | |
| def youtube_video_tool(url: str) -> str: | |
| """ | |
| Get a transcript of a YouTube video. | |
| Args: | |
| url (str): The URL of the YouTube video. | |
| Returns: | |
| str: The transcript of the YouTube video. | |
| """ | |
| print(f"youtube_tool called with: {url}") | |
| md = MarkItDown() | |
| markdown_result = md.convert_url(url) | |
| return markdown_result.markdown | |
| def google_search_tool(query: str) -> str: | |
| """ | |
| Perform a Google search for a specific query. | |
| Args: | |
| query (str): The query to search for on Google. | |
| Returns: | |
| str: The search results from Google. | |
| """ | |
| print(f"google_search_tool called with: {query}") | |
| try: | |
| # Create the Google API wrapper | |
| google_api = SerpAPIWrapper() | |
| # Perform the search | |
| search_results = google_api.results(query) | |
| print(f"google_search_tool response: {search_results['organic_results']}") | |
| return search_results['organic_results'] | |
| except Exception as e: | |
| error = f"Error performing Google search: {e}" | |
| print(error) | |
| return error | |
| def web_search(query: str) -> list[dict[str, str]]: | |
| """ | |
| Run a web search `query` and return the results. | |
| Make sure the query is specific to what you want to search for. | |
| Best to run up to 3 instances of `web_search` at the same time with somewhat different queries to get a diverse set of results. | |
| If the returned search result points to Wikipedia, use the `wikipedia_tool` to get the content of the page. | |
| Args: | |
| query (str): The web search query. | |
| Returns: | |
| list[dict[str, str]]: A list of dictionaries containing the title and URL of the results. Visit the URL to get the content. | |
| """ | |
| print(f"web_search called with: {query}") | |
| try: | |
| search_docs = TavilySearchResults(max_results=3).invoke(query) | |
| for idx, doc in enumerate(search_docs): | |
| print(f"web_search response #{idx}: {doc['title']} - {doc['url']}") | |
| return [{"title": doc["title"], "url": doc["url"]} for doc in search_docs] | |
| except Exception as e: | |
| error = f"Error running web_search: {e}" | |
| print(error) | |
| return error | |
| def visit_url_tool(url: str) -> str: | |
| """ | |
| Visit the URL and retrieve the webpage or file content. | |
| This function checks the content type of the file and converts it to markdown if necessary. | |
| Args: | |
| url (str): The URL of the file to be downloaded. | |
| Returns: | |
| str: The content of the downloaded file. | |
| """ | |
| print(f"download_url_tool called with: {url}") | |
| try: | |
| # Download the file | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| # Check content type and if it's not a text file, convert it to markdown | |
| content_type = response.headers.get("Content-Type", "") | |
| if content_type in ["text/plain", "application/json"]: | |
| print(f"download_url_tool response: {response.content[:100]}...") | |
| return response.content | |
| # Convert the file to markdown | |
| print(f"download_url_tool converting to markdown: {content_type}") | |
| md = MarkItDown() | |
| try: | |
| content_io = BytesIO(response.content) | |
| markdown_result = md.convert(content_io) | |
| print(f"download_url_tool response: {markdown_result.markdown[:100]}...") | |
| return markdown_result.markdown | |
| except Exception as e: | |
| error = f"Error converting {content_type} file to markdown: {e}" | |
| print(error) | |
| return error | |
| except Exception as e: | |
| error = f"Error downloading file from URL: {e}" | |
| print(error) | |
| return error | |
| # List of tools to be used | |
| tools = [ | |
| # simple_answer_function, | |
| # weather_tool, | |
| # unit_converter_tool, | |
| # google_search_tool, | |
| web_search, | |
| visit_url_tool, | |
| wikipedia_tool, | |
| youtube_video_tool, | |
| ] | |