Skip to content

Tools

any_agent.tools

a2a_tool(url, toolname=None, http_kwargs=None) async

Perform a query using A2A to another agent.

Parameters:

Name Type Description Default
url str

The url in which the A2A agent is located.

required
toolname str

The name for the created tool. Defaults to call_{agent name in card}. Leading and trailing whitespace are removed. Whitespace in the middle is replaced by _.

None
http_kwargs dict

Additional kwargs to pass to the httpx client.

None

Returns:

Type Description
Callable[[str], Coroutine[Any, Any, str]]

An async Callable that takes a query and returns the agent response.

Source code in src/any_agent/tools/a2a.py
async def a2a_tool(
    url: str, toolname: str | None = None, http_kwargs: dict[str, Any] | None = None
) -> Callable[[str], Coroutine[Any, Any, str]]:
    """Perform a query using A2A to another agent.

    Args:
        url (str): The url in which the A2A agent is located.
        toolname (str): The name for the created tool. Defaults to `call_{agent name in card}`.
            Leading and trailing whitespace are removed. Whitespace in the middle is replaced by `_`.
        http_kwargs (dict): Additional kwargs to pass to the httpx client.

    Returns:
        An async `Callable` that takes a query and returns the agent response.

    """
    if not a2a_tool_available:
        msg = "You need to `pip install 'any-agent[a2a]'` to use this tool"
        raise ImportError(msg)

    async with httpx.AsyncClient(follow_redirects=True) as resolver_client:
        a2a_agent_card: AgentCard = await (
            A2ACardResolver(httpx_client=resolver_client, base_url=url)
        ).get_agent_card()

    async def _send_query(query: str) -> str:
        async with httpx.AsyncClient(follow_redirects=True) as query_client:
            client = A2AClient(httpx_client=query_client, agent_card=a2a_agent_card)
            send_message_payload = SendMessageRequest(
                params=MessageSendParams(
                    message=Message(
                        role=Role.user,
                        parts=[Part(root=TextPart(text=query))],
                        # the id is not currently tracked
                        messageId=uuid4().hex,
                    )
                ),
                id=str(uuid4().hex),
            )
            # TODO check how to capture exceptions and pass them on to the enclosing framework
            response = await client.send_message(
                send_message_payload, http_kwargs=http_kwargs
            )
            result: str = response.model_dump_json()
            return result

    new_name = toolname or a2a_agent_card.name
    new_name = re.sub(r"\s+", "_", new_name.strip())
    _send_query.__name__ = f"call_{new_name}"
    _send_query.__doc__ = f"""{a2a_agent_card.description}
        Send a query to the agent named {a2a_agent_card.name}.

        Agent description: {a2a_agent_card.description}

        Args:
            query (str): The query to perform.

        Returns:
            The result from the A2A agent, encoded in json.
    """
    return _send_query

ask_user_verification(query)

Asks user to verify the given query.

Parameters:

Name Type Description Default
query str

The question that requires verification.

required
Source code in src/any_agent/tools/user_interaction.py
def ask_user_verification(query: str) -> str:
    """Asks user to verify the given `query`.

    Args:
        query: The question that requires verification.

    """
    return input(f"{query} => Type your answer here:")

search_tavily(query, include_images=False)

Perform a Tavily web search based on your query and return the top search results.

See https://blog.tavily.com/getting-started-with-the-tavily-search-api for more information.

Parameters:

Name Type Description Default
query str

The search query to perform.

required
include_images bool

Whether to include images in the results.

False

Returns:

Type Description
str

The top search results as a formatted string.

Source code in src/any_agent/tools/web_browsing.py
def search_tavily(query: str, include_images: bool = False) -> str:
    """Perform a Tavily web search based on your query and return the top search results.

    See https://blog.tavily.com/getting-started-with-the-tavily-search-api for more information.

    Args:
        query (str): The search query to perform.
        include_images (bool): Whether to include images in the results.

    Returns:
        The top search results as a formatted string.

    """
    if not tavily_available:
        msg = "You need to `pip install 'tavily-python'` to use this tool"
        raise ImportError(msg)
    api_key = os.getenv("TAVILY_API_KEY")
    if not api_key:
        return "TAVILY_API_KEY environment variable not set."
    try:
        client = TavilyClient(api_key)
        response = client.search(query, include_images=include_images)
        results = response.get("results", [])
        output = []
        for result in results:
            output.append(
                f"[{result.get('title', 'No Title')}]({result.get('url', '#')})\n{result.get('content', '')}"
            )
        if include_images and "images" in response:
            output.append("\nImages:")
            for image in response["images"]:
                output.append(image)
        return "\n\n".join(output) if output else "No results found."
    except Exception as e:
        return f"Error performing Tavily search: {e!s}"

search_web(query)

Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results.

Parameters:

Name Type Description Default
query str

The search query to perform.

required

Returns:

Type Description
str

The top search results.

Source code in src/any_agent/tools/web_browsing.py
def search_web(query: str) -> str:
    """Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results.

    Args:
        query (str): The search query to perform.

    Returns:
        The top search results.

    """
    ddgs = DDGS()
    results = ddgs.text(query, max_results=10)
    return "\n".join(
        f"[{result['title']}]({result['href']})\n{result['body']}" for result in results
    )

send_console_message(user, query)

Send the specified user a message via console and returns their response.

Parameters:

Name Type Description Default
query str

The question to ask the user.

required
user str

The user to ask the question to.

required

Returns:

Name Type Description
str str

The user's response.

Source code in src/any_agent/tools/user_interaction.py
def send_console_message(user: str, query: str) -> str:
    """Send the specified user a message via console and returns their response.

    Args:
        query: The question to ask the user.
        user: The user to ask the question to.

    Returns:
        str: The user's response.

    """
    return Prompt.ask(f"{query}\n{user}")

show_final_output(answer)

Show the final answer to the user.

Parameters:

Name Type Description Default
answer str

The final answer.

required
Source code in src/any_agent/tools/user_interaction.py
def show_final_output(answer: str) -> str:
    """Show the final answer to the user.

    Args:
        answer: The final answer.

    """
    logger.info(f"Final output: {answer}")
    return answer

show_plan(plan)

Show the current plan to the user.

Parameters:

Name Type Description Default
plan str

The current plan.

required
Source code in src/any_agent/tools/user_interaction.py
def show_plan(plan: str) -> str:
    """Show the current plan to the user.

    Args:
        plan: The current plan.

    """
    logger.info(f"Current plan: {plan}")
    return plan

visit_webpage(url)

Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages.

Parameters:

Name Type Description Default
url str

The url of the webpage to visit.

required
Source code in src/any_agent/tools/web_browsing.py
def visit_webpage(url: str) -> str:
    """Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages.

    Args:
        url: The url of the webpage to visit.

    """
    try:
        response = requests.get(url)
        response.raise_for_status()

        markdown_content = markdownify(response.text).strip()  # type: ignore[no-untyped-call]

        markdown_content = re.sub(r"\n{2,}", "\n", markdown_content)

        return _truncate_content(markdown_content, 10000)
    except RequestException as e:
        return f"Error fetching the webpage: {e!s}"
    except Exception as e:
        return f"An unexpected error occurred: {e!s}"