PerplexitySearchTool - AG2

PerplexitySearchTool

autogen.tools.experimental.perplexity.perplexity_search.PerplexitySearchTool

PerplexitySearchTool(model='sonar', api_key=None, max_tokens=1000, search_domain_filter=None)

Bases: Tool

Tool for interacting with the Perplexity AI search API.

This tool uses the Perplexity API to perform web search, news search, and conversational search, returning concise and precise responses.

ATTRIBUTE DESCRIPTION
url API endpoint URL.
TYPE:str
model Name of the model to be used.
TYPE:str
api_key API key for authenticating with the Perplexity API.
TYPE:str
max_tokens Maximum tokens allowed for the API response.
TYPE:int
search_domain_filters Optional list of domain filters for the search.
TYPE:Optional[list[str]]

Initializes a new instance of the PerplexitySearchTool.

PARAMETER DESCRIPTION
model The model to use. Defaults to "sonar".
TYPE:strDEFAULT:'sonar'
api_key API key for authentication.
TYPE:Optional[str]DEFAULT:None
max_tokens Maximum number of tokens for the response. Defaults to 1000.
TYPE:intDEFAULT:1000
search_domain_filter list of domain filters to restrict search.
TYPE:Optional[list[str]]DEFAULT:None
RAISES DESCRIPTION
ValueError If the API key is missing, the model is empty, max_tokens is not positive, or if search_domain_filter is not a list when provided.

Source code in autogen/tools/experimental/perplexity/perplexity_search.py

    def __init__(  
        self,  
        model: str = "sonar",  
        api_key: str | None = None,  
        max_tokens: int = 1000,  
        search_domain_filter: list[str] | None = None,  
    ):
        """Initializes a new instance of the PerplexitySearchTool.  
        Args:  
            model (str, optional): The model to use. Defaults to "sonar".  
            api_key (Optional[str], optional): API key for authentication.  
            max_tokens (int, optional): Maximum number of tokens for the response. Defaults to 1000.  
            search_domain_filter (Optional[list[str]], optional): list of domain filters to restrict search.  
        Raises:  
            ValueError: If the API key is missing, the model is empty, max_tokens is not positive,  
                        or if search_domain_filter is not a list when provided.  
        """  
        self.api_key = api_key or os.getenv("PERPLEXITY_API_KEY")  
        self._validate_tool_config(model, self.api_key, max_tokens, search_domain_filter)  
        self.url = "https://api.perplexity.ai/chat/completions"  
        self.model = model  
        self.max_tokens = max_tokens  
        self.search_domain_filters = search_domain_filter  
        super().__init__(  
            name="perplexity-search",  
            description="Perplexity AI search tool for web search, news search, and conversational search "  
            "for finding answers to everyday questions, conducting in-depth research and analysis.",  
            func_or_tool=self.search,  
        )  

api_key instance-attribute

api_key = api_key or getenv('PERPLEXITY_API_KEY')

url instance-attribute

url = 'https://api.perplexity.ai/chat/completions'

model instance-attribute

model = model

max_tokens instance-attribute

max_tokens = max_tokens

search_domain_filters instance-attribute

search_domain_filters = search_domain_filter

name property

name

description property

description

func property

func

tool_schema property

tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpenAI and compatible frameworks.

function_schema property

function_schema

Get the schema for the function.

This is the old way of handling function calls with OpenAI and compatible frameworks. It is provided for backward compatibility.

realtime_tool_schema property

realtime_tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpenAI and compatible frameworks.

search

search(query)

Perform a search query using the Perplexity AI API.

Constructs the payload, executes the query, and parses the response to return a concise search result along with any provided citations.

PARAMETER DESCRIPTION
query The search query.
TYPE:str
RETURNS DESCRIPTION
SearchResponse A model containing the search result content and citations.
TYPE:SearchResponse
RAISES DESCRIPTION
ValueError If the search query is invalid.
RuntimeError If there is an error during the search process.

Source code in autogen/tools/experimental/perplexity/perplexity_search.py

    def search(self, query: str) -> "SearchResponse":
        """Perform a search query using the Perplexity AI API.  
        Constructs the payload, executes the query, and parses the response to return  
        a concise search result along with any provided citations.  
        Args:  
            query (str): The search query.  
        Returns:  
            SearchResponse: A model containing the search result content and citations.  
        Raises:  
            ValueError: If the search query is invalid.  
            RuntimeError: If there is an error during the search process.  
        """  
        if not query or not isinstance(query, str):  
            raise ValueError("A valid non-empty query string must be provided.")  
        payload = {  
            "model": self.model,  
            "messages": [{"role": "system", "content": "Be precise and concise."}, {"role": "user", "content": query}],  
            "max_tokens": self.max_tokens,  
            "search_domain_filter": self.search_domain_filters,  
            "web_search_options": {"search_context_size": "high"},  
        }  
        try:  
            perplexity_response = self._execute_query(payload)  
            content = perplexity_response.choices[0].message.content  
            citations = perplexity_response.citations  
            return SearchResponse(content=content, citations=citations, error=None)  
        except Exception as e:  
            return SearchResponse(content=None, citations=None, error=f"{e}")  

register_for_llm

register_for_llm(agent)

Registers the tool for use with a ConversableAgent's language model (LLM).

This method registers the tool so that it can be invoked by the agent during interactions with the language model.

PARAMETER DESCRIPTION
agent The agent to which the tool will be registered.
TYPE:ConversableAgent

Source code in autogen/tools/tool.py

def register_for_llm(self, agent: "ConversableAgent") -> None:
    """Registers the tool for use with a ConversableAgent's language model (LLM).  
    This method registers the tool so that it can be invoked by the agent during  
    interactions with the language model.  
    Args:  
        agent (ConversableAgent): The agent to which the tool will be registered.  
    """  
    if self._func_schema:  
        agent.update_tool_signature(self._func_schema, is_remove=False)  
    else:  
        agent.register_for_llm()(self)  

register_for_execution

register_for_execution(agent)

Registers the tool for direct execution by a ConversableAgent.

This method registers the tool so that it can be executed by the agent, typically outside of the context of an LLM interaction.

PARAMETER DESCRIPTION
agent The agent to which the tool will be registered.
TYPE:ConversableAgent

Source code in autogen/tools/tool.py

def register_for_execution(self, agent: "ConversableAgent") -> None:
    """Registers the tool for direct execution by a ConversableAgent.  
    This method registers the tool so that it can be executed by the agent,  
    typically outside of the context of an LLM interaction.  
    Args:  
        agent (ConversableAgent): The agent to which the tool will be registered.  
    """  
    agent.register_for_execution()(self)  

register_tool

register_tool(agent)

Register a tool to be both proposed and executed by an agent.

Equivalent to calling both register_for_llm and register_for_execution with the same agent.

Note: This will not make the agent recommend and execute the call in the one step. If the agent recommends the tool, it will need to be the next agent to speak in order to execute the tool.

PARAMETER DESCRIPTION
agent The agent to which the tool will be registered.
TYPE:ConversableAgent

Source code in autogen/tools/tool.py

def register_tool(self, agent: "ConversableAgent") -> None:
    """Register a tool to be both proposed and executed by an agent.  
    Equivalent to calling both `register_for_llm` and `register_for_execution` with the same agent.  
    Note: This will not make the agent recommend and execute the call in the one step. If the agent  
    recommends the tool, it will need to be the next agent to speak in order to execute the tool.  
    Args:  
        agent (ConversableAgent): The agent to which the tool will be registered.  
    """  
    self.register_for_llm(agent)  
    self.register_for_execution(agent)