Ask your agent “How much is 500 EUR in JPY right now?” and watch it fail. It either invents a rate that looks plausible and is wrong, or it tells you it can’t access live data. Neither is useful when a user is waiting on the answer.
The fix is small. Give the agent a tool that fetches the rate for itself. This post walks through building that tool with the ExchangeRatesData API: the function schema, a working Python implementation, and the agent loop that ties them together. You’ll have something runnable by the end.
Table of Contents
Why can’t my agent just answer this?
A language model only knows what it saw in training. Exchange rates move by the second, so the model has no current number to give you. Worse, it doesn’t always know that it doesn’t know, so instead of refusing, it guesses. For a travel app or a checkout flow, a confident wrong number is the last thing you want.
Function calling solves this. You hand the model a set of tools, each described by a schema. When a request needs live data, the model stops, emits a structured call to the right tool, and waits for your code to return real data. The model reasons; your code fetches. That separation is what makes AI agent currency conversion reliable instead of a gamble.
If you want the deeper background on designing tools that agents can actually use, APILayer has a full guide to OpenAI function calling.
Why the ExchangeRatesData API fits
You want a currency API for AI agent use that is fast, predictable, and easy to parse. The ExchangeRatesData API is a clean match:
- It’s a plain REST endpoint. One GET request, no SDK.
- Auth is a single apikey HTTP header. No OAuth dance.
- It returns flat JSON that maps straight into a tool’s output.
- It covers 168 world currencies and precious metals, drawn from over 15 data sources.
- The free tier is enough to build and test before you pay anything.
Agents break on inconsistency. An API that returns the same shape on every call is exactly what you want feeding a model. Get a free API key and you can run every snippet below.
What does the tool definition look like?
Start with the schema. This is the contract the model reads to decide when and how to call your function. Here it is in OpenAI’s function-calling format:
currency_tool = {
"type": "function",
"function": {
"name": "convert_currency",
"description": (
"Convert an amount from one currency to another using "
"real-time exchange rates. Use this whenever the user asks "
"to convert money or about current exchange rates."
),
"parameters": {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "The amount of money to convert.",
},
"from_currency": {
"type": "string",
"description": "Three-letter ISO code to convert from, e.g. 'EUR'.",
},
"to_currency": {
"type": "string",
"description": "Three-letter ISO code to convert to, e.g. 'JPY'.",
},
},
"required": ["amount", "from_currency", "to_currency"],
},
},
}
Write the description for the model, not for yourself. “Use this whenever the user asks to convert money” tells the model precisely when to reach for the tool. A vague description is the most common reason an exchange rate tool function-calling setup misfires.
Building the tool
Now the implementation. The /convert endpoint does the math for you. Pass from, to, and amount, and it returns the converted figure directly. No fetching raw rates and multiplying by hand.
import os
import requests
API_KEY = os.environ["EXCHANGERATES_API_KEY"]
CONVERT_URL = "https://api.apilayer.com/exchangerates_data/convert"
def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict:
"""Convert `amount` from one currency to another using live rates."""
response = requests.get(
CONVERT_URL,
headers={"apikey": API_KEY},
params={"from": from_currency, "to": to_currency, "amount": amount},
timeout=10,
)
response.raise_for_status()
data = response.json()
if not data.get("success", False):
raise RuntimeError(f"Conversion failed: {data}")
return {
"result": data["result"],
"rate": data["info"]["rate"],
"from": data["query"]["from"],
"to": data["query"]["to"],
"amount": data["query"]["amount"],
}
Swap in your key and it runs. A call to convert_currency(500, “EUR”, “JPY”) hits the API and returns a response in this shape. Your rate, timestamp, and result will reflect the live market at the moment you call it:
{
"success": true,
"query": {
"from": "EUR",
"to": "JPY",
"amount": 500
},
"info": {
"timestamp": 1781913600,
"rate": 168.42
},
"date": "2026-06-20",
"result": 84210
}
The converted amount sits in result. The info.rate field is the per-unit rate, useful if you want to show your work. That’s the whole payload: flat, predictable, and ready to hand back to the model.
How do I connect the tool into my agent loop?
Register the tool, let the model call it, run the function, and feed the result back. The model handles the rest. Here’s the full round trip with OpenAI:
import json
from openai import OpenAI
client = OpenAI()
messages = [{"role": "user", "content": "How much is 500 EUR in JPY right now?"}]
# 1. The model sees the tool and decides to call it
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=[currency_tool],
)
message = response.choices[0].message
messages.append(message)
# 2. Run the tool and return its output to the model
for call in message.tool_calls or []:
if call.function.name == "convert_currency":
args = json.loads(call.function.arguments)
output = convert_currency(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(output),
})
# 3. The model turns the raw numbers into a plain-language answer
final = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=[currency_tool],
)
print(final.choices[0].message.content)
The pattern is the same in LangChain or a custom loop: expose the schema, catch the tool call, execute it, return JSON. Your agent now answers currency questions with real numbers instead of guesses. For more on shaping responses that agents can consume cleanly, see APILayer’s notes on making your API agent-ready.
What are the limits?
Be honest with yourself about the free tier before you ship.
- Requests. The free plan gives you 100 requests per month. That’s plenty for this ExchangeRatesData API tutorial and early testing, not for production traffic. Exceed your quota and the API returns HTTP 429.
- Latency. Every tool call is a network round trip. A few hundred milliseconds is fine for a chat reply, but it adds up if your agent converts dozens of values in a loop.
- Freshness. On the free plan, rates refresh once a day. If you need by-the-minute rates, that’s a paid tier (up to every 60 seconds on Business).
Caching covers most of this. If your agent converts EUR to JPY three times in one session, call the API once and reuse the rate for the rest of the turn. It cuts latency and protects your quota. For patterns on combining live API data with LLM workflows, APILayer’s walkthrough on real-time AI data pipelines is a useful next read.
Put it to work
You now have a currency tool your agent can call on its own: a schema, a tested function, and the loop that connects them. The free tier gives you 100 requests a month, enough to prototype and test the whole thing end to end. Grab your API key and wire it into your agent today.
Frequently asked questions
How do I give an AI agent live currency conversion?
Define a function-calling tool that wraps a currency API, then register it with your model. When a user asks to convert money, the model emits a structured call to the tool, your code fetches the live rate from the ExchangeRatesData API, and the model phrases the answer. The model decides when to call; your code returns the real number.
Which endpoint converts one currency to another?
Use the ExchangeRatesData /convert endpoint: https://api.apilayer.com/exchangerates_data/convert with from, to, and amount query parameters. It returns the converted figure in the result field, so you do not fetch raw rates and multiply by hand.
How many requests does the free tier allow?
The free plan includes 100 requests per month with daily rate updates. That is enough to build and test the tool. Paid tiers raise the quota and refresh more often.
How current are the exchange rates?
On the free plan, rates refresh once per day. Paid plans update hourly, every 10 minutes, or every 60 seconds depending on the tier. Spot rates are collected within the 60-second market window.
How many currencies does the ExchangeRatesData API support?
It covers 168 world currencies and precious metals such as gold and silver, drawn from over 15 exchange rate data sources.
How do I keep tool calls from slowing my agent down?
Cache rates within a session. If the agent converts the same pair several times in one turn, call the API once and reuse the rate. That cuts latency and protects your monthly quota.
Full API reference: ExchangeRatesData API documentation.

