Skip to content

Currency Converter (Multi-Currency, Autonomous, API+SearchTool)#

Open In Colab Open on GitHub

This notebook demonstrates a fully autonomous, multi-currency conversion system built with AG2 (AutoGen). It is inspired by the original USD↔EUR calculator but extended with: - Option to use GoogleSearchTool (inspired on this notebook) or Frankfurter API for real-time exchange rates - Support for any currency pair - Fully autonomous multi-agent orchestration

No human interaction needed once the user submits the initial prompt.

Installation#

To get started with the Google Search integration in AG2, follow these steps:

Install AG2 with the google-search extra. Since our examples also use openai and gemini, install them as well:

pip install -U ag2[openai,gemini,google-search]

Note: If you have been using autogen or ag2, all you need to do is upgrade it using:

pip install -U autogen[openai,gemini,google-search]

or

pip install -U ag2[openai,gemini,google-search]

as autogen, and ag2 are aliases for the same PyPI package.

You’re all set! Now you can start using Google Search with AG2.

Imports#

import os

from dotenv import load_dotenv

import autogen
from autogen import AssistantAgent
from autogen.tools.experimental import GoogleSearchTool

load_dotenv()

from pathlib import Path

from autogen.agentchat import initiate_group_chat
from autogen.agentchat.group.patterns import AutoPattern
from autogen.coding import LocalCommandLineCodeExecutor

GoogleSearchTool with AG2 Google Search implementation#

For all other LLM providers or if you need to combine Google Search with other tools, follow this section to configure AG2’s implementation.

Setup Google Search Engine and API Key#

  1. Create a Google Custom Search Engine (CSE):
    • Go to Google Programmable Search Engine
    • Click Get Started and create a search engine.
    • Under Sites to Search, select Search the entire web if you want global search.
    • Copy the Search Engine ID from the CSE dashboard (cx parameter from the url)
  2. Get a Google API Key:
    • Go to Google Cloud Console
    • Create a new project.
    • Navigate to APIs & Services > Library, search for Custom Search API and enable it.
    • Go to APIs & Services > Credentials, click on Create Credentials > API key and copy it.
  3. Export engine ID and api key bash export GOOGLE_SEARCH_ENGINE_ID="your_engine_id" export GOOGLE_SEARCH_API_KEY="your_api_key"

Agent Configuration#

llm_config = autogen.LLMConfig(
    config_list=[
        {
            "model": "gpt-4o",
            "api_type": "azure",
            "api_key": os.getenv("AZURE_OPENAI_API_KEY"),
            "base_url": os.getenv("BASE_URL"),
            "api_version": os.getenv("API_VERSION"),
        }
    ]
)

assistant = AssistantAgent(
    name="assistant",
    llm_config={"config_list": llm_config.config_list},
)
workdir = Path("exchange_workspace")
workdir.mkdir(exist_ok=True)
code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)
google_tool = GoogleSearchTool()

GoogleSearchTool Initialization#

Create GoogleSearchTool with your search_api_key and search_engine_id.

search_api_key = os.getenv("GOOGLE_SEARCH_API_KEY")
search_engine_id = os.getenv("GOOGLE_SEARCH_ENGINE_ID")

assert search_api_key is not None, "Please set GOOGLE_SEARCH_API_KEY environment variable"
assert search_engine_id is not None, "Please set GOOGLE_SEARCH_ENGINE_ID environment variable"

gs_tool = GoogleSearchTool(
    search_api_key=search_api_key,
    search_engine_id=search_engine_id,
)
# Once initialized, register the tool with the assistant:
gs_tool.register_for_llm(assistant)

Initialize GoogleSearchTool:

google_tool = GoogleSearchTool()

Define the function for Currency Conversion:#

def convert_currency(amount: float, rate: float) -> float:
    return round(amount * rate, 2)

Frankfurter API Fallback Option#

def get_rate_frankfurter(amount: float, from_currency: str, to_currency: str) -> float:
    """
    Fetch the exchange rate from the Frankfurter API and return the converted amount.
    """
    import httpx

    response = httpx.get(
        "https://api.frankfurter.app/latest", params={"amount": amount, "from": from_currency, "to": to_currency}
    )
    response.raise_for_status()
    return response.json()["rates"][to_currency]

Define Work Directory:

workdir = Path("exchange_workspace")
workdir.mkdir(exist_ok=True)
code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)

Define Agents#

parser_agent = AssistantAgent(
    name="ParserAgent",
    system_message=(
        'You are an expert at extracting currency exchange requests. Given an input like "Convert 100 USD to EUR", extract the amount, source currency, and target currency in JSON format as: {"amount": 100, "from": "USD", "to": "EUR"}. '
        "If the user asks about anything other than currency conversion or exchange rates, politely state that you cannot help with that topic and can only assist with currency-related queries. "
        "Do not attempt to answer unrelated questions or use tools for other purposes."
    ),
    llm_config=llm_config,
)

search_agent = AssistantAgent(
    name="SearchAgent",
    system_message="You are a skilled web researcher. Given a source and target currency, search Google to find the most recent exchange rate. Respond with only the exchange rate as a float value.",
    llm_config={"config_list": llm_config.config_list},
)

frankfurter_agent = AssistantAgent(
    name="FrankfurterAgent",
    system_message=(
        "You are a reliable agent that uses the Frankfurter API to return the converted amount. "
        "Given amount, from_currency, and to_currency, call get_rate_frankfurter() and return the result as a float. "
        "Do not perform any further calculations; just return the value from get_rate_frankfurter()."
    ),
    functions=[get_rate_frankfurter],
    code_execution_config={"use_docker": False},  # optionally sandboxed
    llm_config={"config_list": llm_config.config_list},
)

response_agent = AssistantAgent(
    name="ResponseAgent",
    system_message=(
        "You are a helpful assistant responsible for providing the final response to the user. "
        "Given the converted amount, source currency, and target currency, respond in a clear and concise manner. "
        "For example, if the user asks to convert 100 USD to EUR and the result is 92.5, respond with: "
        "'100 USD is approximately 92.5 EUR.' "
        "Once you've generated the summary, append the following marker: "
        "==== FINAL ANSWER ===="
    ),
    llm_config={"config_list": llm_config.config_list},
)

Register GoogleSearchTool to the search_agent:

search_api_key = os.getenv("GOOGLE_SEARCH_API_KEY")
search_engine_id = os.getenv("GOOGLE_SEARCH_ENGINE_ID")

assert search_api_key is not None, "Please set GOOGLE_SEARCH_API_KEY environment variable"
assert search_engine_id is not None, "Please set GOOGLE_SEARCH_ENGINE_ID environment variable"

gs_tool = GoogleSearchTool(
    search_api_key=search_api_key,
    search_engine_id=search_engine_id,
)
# Once initialized, register the tool with the assistant:
gs_tool.register_for_llm(search_agent)

Define Termination Condition#

from typing import Any

def is_termination_msg(msg: dict[str, Any]) -> bool:
    content = msg.get("content", "")
    return (content is not None) and "==== FINAL ANSWER ====" in content

Define Agent Collaboration Pattern#

There are 2 Options in this notebook - either you get the exchange rate calculation using GoogleSearchTool, or you use Frankfurter API. That depends on the value of the USE_API variable:

USE_API = True  # Set to False to use GoogleSearchTool instead
if USE_API:
    agents = [parser_agent, frankfurter_agent, response_agent]
    initial_agent = parser_agent
else:
    agents = [parser_agent, search_agent, response_agent]
    initial_agent = parser_agent
pattern = AutoPattern(
    initial_agent=initial_agent,
    agents=agents,
    user_agent=None,
    group_manager_args={
        "llm_config": llm_config,
        "is_termination_msg": is_termination_msg,  # Ensure termination messages are handled
    },
)

Run the Group Chat:#

# === Run the group chat ===
initial_prompt = input("Enter a currency conversion request (e.g., 'Convert 100 USD to EUR'): ")
result, context, last_agent = initiate_group_chat(
    pattern=pattern,
    messages=initial_prompt,
)