ReAct-style agent
This is a simple example of a ReAct-style agent. The functionality is akin to a "traditional" AI agent as offered by the traditional libraries: you can use simple methods and assign them to an agent.
Note here that we use the task construct to define the task
that we want the AI to accomplish.
Dependencies ¶
You will need to install the following dependencies:
Example code ¶
ReAct agent
import ast
from typing import Literal
from currency_converter import CurrencyConverter
from duckduckgo_search import DDGS
from trafilatura import extract, fetch_url
from conatus import task
from conatus.agents.react import ReactAgent
def get_text_from_url(url: str) -> str:
"""Get the text from a URL.
Internally, we use trafilatura to fetch the URL and extract the text.
Args:
url: The URL to get the text from.
Returns:
The text from the URL.
"""
html = fetch_url(url) or "<no text found>"
return extract(html, output_format="markdown") or "<no text found>"
def search_web(query: str) -> list[dict[str, str]]:
"""Search the web for a query.
Internally, we use DuckDuckGo to search for the query.
Args:
query: The query to search for.
Returns:
A list of {"title": str, "url": str, "": str}
"""
return DDGS().text(query, max_results=5)
def calculator(query: str) -> str:
"""A humble, simple calculator.
You can throw simple math expressions at it.
Args:
query: The query to calculate.
Returns:
The result of the query.
"""
try:
result = str(ast.literal_eval(query))
except Exception as e: # noqa: BLE001
return f"Error: {e}"
return f"The result of {query} is {result}"
Currencies = Literal["USD", "EUR", "GBP"]
def currency_conversion(
amount: float | list[float],
from_currency: Currencies,
to_currency: Currencies,
) -> float | list[float]:
"""Convert a currency amount to another currency.
Args:
amount: The amount to convert. If a list, we will convert each amount
in the list.
from_currency: The currency to convert from.
to_currency: The currency to convert to.
Returns:
The converted amount (or a list of converted amounts).
"""
c = CurrencyConverter()
def _convert(amount: float) -> float:
return float(c.convert(amount, from_currency, to_currency))
if isinstance(amount, list):
return [_convert(a) for a in amount]
return _convert(amount)
@task(
actions=[calculator, search_web, get_text_from_url, currency_conversion],
agent_cls=ReactAgent,
)
def find_squad_valuations(team_description: str) -> list[tuple[str, int]]:
"""Find the squad valuations of a team (or multiple teams).
Here, we mean the sum of the market value of the players in the team.
Use Transfermarkt to find the market value of the players.
Returns:
A list of tuples of the form `(team_name, squad_valuation)`. Return
the valuations in millions of dollars.
"""
valuations = find_squad_valuations(
"The semi-finalists in this year's Champions League"
)
print(valuations)