The tools module provides utilities for web search and other agent-based capabilities.
WebSearchTool
The WebSearchTool enables real-time web search capabilities for RAG applications.
Usage
fromrankify.tools.ToolsimportWebSearchTool# Initialize the toolsearch_tool=WebSearchTool(search_provider='serper',search_provider_api_key='your-api-key')# Setup (loads necessary components)search_tool.setup()# Perform searchresults=search_tool.forward("What is RAG in NLP?",num_result=10)print(results)
API Reference
rankify.tools.Tools
Tool
A base class for the functions used by the agent. Subclass this and implement the forward method as well as the
following class attributes:
description (str) -- A short description of what your tool does, the inputs it expects and the output(s) it
will return. For instance, 'This is a tool that downloads a file from a url. It takes the url as input, and
returns the text contained in the file'.
name (str) -- A performative name that will be used for your tool in the prompt to the agent. For instance
"text-classifier" or "image_generator".
inputs (Dict[str, Dict[str, Union[str, type, bool]]]) -- The dict of modalities expected for the inputs.
It has one type' key and adescriptionkey.
This is used bylaunch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated
description for your tool.
output_type (type) -- The type of the tool output. This is used by launch_gradio_demo
or to make a nice space from your tool, and also can be used in the generated description for your tool.
classTool:""" A base class for the functions used by the agent. Subclass this and implement the `forward` method as well as the following class attributes: - **description** (`str`) -- A short description of what your tool does, the inputs it expects and the output(s) it will return. For instance, 'This is a tool that downloads a file from a `url`. It takes the `url` as input, and returns the text contained in the file'. - **name** (`str`) -- A performative name that will be used for your tool in the prompt to the agent. For instance `"text-classifier"` or `"image_generator"`. - **inputs** (`Dict[str, Dict[str, Union[str, type, bool]]]`) -- The dict of modalities expected for the inputs. It has one `type' key and a `description`key. This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated description for your tool. - **output_type** (`type`) -- The type of the tool output. This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated description for your tool."""name:strdescription:strinputs:dict[str,dict[str,str|type|bool]]output_type:strdef__init__(self):self.is_initialized=Falsedefvalidate_arguments(self):required_attributes={"description":str,"name":str,"inputs":dict[str,dict[str,str|type|bool]],"output_type":str}forattr,expected_typeinrequired_attributes.items():attr_value=getattr(self,attr,None)ifattr_valueisNone:raiseValueError(f"Attribute {attr} is required for tool {self.name}")ifnotisinstance(attr_value,expected_type):# noqaraiseValueError(f"Attribute {attr} for tool {self.name} must be of type {expected_type}")defforward(self,query:str):returnNotImplementedError("Write this method in your subclass of `Tool`.")defsetup(self):""" Overwrite this method here for any operation that is expensive and needs to be executed before you start using your tool. Such as loading a big model. """self.is_initialized=True
setup()
Overwrite this method here for any operation that is expensive and needs to be executed before you start using
your tool. Such as loading a big model.
defsetup(self):""" Overwrite this method here for any operation that is expensive and needs to be executed before you start using your tool. Such as loading a big model. """self.is_initialized=True
classWebSearchTool(Tool):name="web_search"description="Performs web search using user query and returns the top n results."inputs={'query':{'type':'string','description':'The user search query'}}output_type="string"def__init__(self,model:Optional[str]=None,search_provider:str='serper',search_provider_api_key:Optional[str]=None):super().__init__()self.search_client=Noneself.model=modelself.search_provider=search_providerself.search_provider_api_key=search_provider_api_key# self.validate_arguments()@staticmethoddefcreate_search_api(search_provider:str='SERPER',api_key:Optional[str]=None)->SearchAPIClient:""" Instantiate a search API client to fetch SERP results from a SERP provider e.g., SERPER.dev. Args: search_provider (str): The name of the search provider. Api_key (str): The API key for the search provider. Can be stored and loaded from env vars. Returns: SearchAPIClient: An instance of the search API client. E.g., SerpAPIClient. """ifsearch_provider.lower()=='serper':#print(api_key)returnSerperApiClient(api_key=api_key)else:raiseValueError(f'Invalid search provider{search_provider}')defforward(self,query:str,num_result:int=10):sources=self.search_client.search_web(query=query,num_results=num_result)#print(sources, len(sources.data['organic']), num_result)#asdadsasdadtry:loop=asyncio.get_event_loop()ifloop.is_running():nest_asyncio.apply()exceptRuntimeError:loop=asyncio.new_event_loop()asyncio.set_event_loop(loop)returnloop.run_until_complete(build_search_context(sources))defsetup(self):""" Performs time-consuming setup operations here e.g., model loading. """self.search_client=self.create_search_api(api_key=self.search_provider_api_key)self.is_initialized=True
Instantiate a search API client to fetch SERP results from a SERP provider e.g., SERPER.dev.
Args:
search_provider (str): The name of the search provider.
Api_key (str): The API key for the search provider. Can be stored and loaded from env vars.
Returns:
SearchAPIClient: An instance of the search API client. E.g., SerpAPIClient.
@staticmethoddefcreate_search_api(search_provider:str='SERPER',api_key:Optional[str]=None)->SearchAPIClient:""" Instantiate a search API client to fetch SERP results from a SERP provider e.g., SERPER.dev. Args: search_provider (str): The name of the search provider. Api_key (str): The API key for the search provider. Can be stored and loaded from env vars. Returns: SearchAPIClient: An instance of the search API client. E.g., SerpAPIClient. """ifsearch_provider.lower()=='serper':#print(api_key)returnSerperApiClient(api_key=api_key)else:raiseValueError(f'Invalid search provider{search_provider}')
setup()
Performs time-consuming setup operations here e.g., model loading.
defsetup(self):""" Performs time-consuming setup operations here e.g., model loading. """self.search_client=self.create_search_api(api_key=self.search_provider_api_key)self.is_initialized=True
build_search_context(sources)async
Source code in rankify/tools/websearch/context/build_search_context.py
asyncdefbuild_search_context(sources:T)->T:ifsourcesisNone:return[]stra=['no_extraction']#, 'cosine'# Filter only Wikipedia sourcesfiltered_sources=[(i,source)fori,sourceinenumerate(sources.data['organic'])#if 'wikipedia.org' in source.get('link', '')]urls=[source[1]['link']forsourceinfiltered_sources]print(f"Filtered Wikipedia URLs: {urls}")scraper=WebScraper(strategies=stra)#strategies=['no_extraction']multi_results=awaitscraper.scrape_many(urls)sources_with_html:List[T]=[]for_,sourceinfiltered_sources:url=source['link']ifurlinmulti_results:source['html']=multi_results[url]['no_extraction'].contentsource['fit_markdown']=multi_results[url]['no_extraction'].fit_markdown#print(multi_results[url]['no_extraction'] , source['fit_markdown'])sources_with_html.append(source)returnsources_with_html