Lesson 9 of 9 · Project
Project: Agent Connected to External APIs
Build a travel helper agent with real APIs: city lookup, weather and currency conversion, JSON Schema tools, argument checks, error handling and a real LLM.
- 6 min read
- Intermediate
- Reviewed
- Build tools that call real, free web APIs
- Combine tool definitions, validation and error handling in one program
- Handle parallel calls and calls that depend on earlier results
- Connect the same tools to a real LLM with an agent loop
The project
You'll build a travel helper that answers questions like “I'm in Lisbon for 3 days with 300 euros. What's the weather, and how much is that in dollars?” It uses three real, free web APIs that need no key:
| Tool | API | Returns |
|---|---|---|
find_city | Open-Meteo geocoding | Name, country, latitude, longitude |
get_forecast | Open-Meteo forecast | Daily max/min °C and rain chance |
convert_currency | Frankfurter (European Central Bank rates) | Today's rate and the converted amount |
Run it with live data
This program calls the real APIs from your browser, so the numbers are today's. The model is a scripted stand-in that makes the same decisions a real model would, so you can run it without an API key:
import json
import requests
# ---------- 1. Tools that call real, free web APIs (no key needed) ----------
def find_city(name):
r = requests.get("https://geocoding-api.open-meteo.com/v1/search",
params={"name": name, "count": 1}, timeout=10)
r.raise_for_status()
results = r.json().get("results")
if not results:
return {"error": f"No city called {name!r}. Check the spelling or add the country."}
c = results[0]
return {"name": c["name"], "country": c.get("country"), "latitude": c["latitude"], "longitude": c["longitude"]}
def get_forecast(latitude, longitude, days):
r = requests.get("https://api.open-meteo.com/v1/forecast", params={
"latitude": latitude, "longitude": longitude, "forecast_days": days, "timezone": "auto",
"daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_max",
}, timeout=10)
r.raise_for_status()
d = r.json()["daily"]
return [{"date": day, "max_c": hi, "min_c": lo, "rain_chance": rain}
for day, hi, lo, rain in zip(d["time"], d["temperature_2m_max"],
d["temperature_2m_min"], d["precipitation_probability_max"])]
def convert_currency(amount, from_currency, to_currency):
r = requests.get("https://api.frankfurter.dev/v1/latest",
params={"base": from_currency, "symbols": to_currency}, timeout=10)
if r.status_code != 200:
return {"error": f"Can't convert {from_currency} to {to_currency}. Use codes like EUR, USD, GBP."}
rate = r.json()["rates"][to_currency]
return {"amount": amount, "from": from_currency, "to": to_currency, "rate": rate, "result": round(amount * rate, 2)}
TOOLS = [
{"name": "find_city",
"description": "Find a city's coordinates. Use before get_forecast. Returns name, country, latitude and longitude.",
"input_schema": {"type": "object", "properties": {
"name": {"type": "string", "description": "City name, e.g. 'Lisbon' or 'Paris, France'"}},
"required": ["name"], "additionalProperties": False}},
{"name": "get_forecast",
"description": "Daily weather forecast for coordinates. Returns per day: max and min °C and rain chance in %.",
"input_schema": {"type": "object", "properties": {
"latitude": {"type": "number", "minimum": -90, "maximum": 90},
"longitude": {"type": "number", "minimum": -180, "maximum": 180},
"days": {"type": "integer", "minimum": 1, "maximum": 7, "description": "Number of days, starting today"}},
"required": ["latitude", "longitude", "days"], "additionalProperties": False}},
{"name": "convert_currency",
"description": "Convert money using today's exchange rate. Returns the rate and the converted amount.",
"input_schema": {"type": "object", "properties": {
"amount": {"type": "number", "minimum": 0},
"from_currency": {"type": "string", "description": "Three-letter code, e.g. EUR"},
"to_currency": {"type": "string", "description": "Three-letter code, e.g. USD"}},
"required": ["amount", "from_currency", "to_currency"], "additionalProperties": False}},
]
FUNCTIONS = {"find_city": find_city, "get_forecast": get_forecast, "convert_currency": convert_currency}
# ---------- 2. Validate, run, and never crash ----------
TYPES = {"string": str, "number": (int, float), "integer": int}
def run_tool(name, args):
tool = next((t for t in TOOLS if t["name"] == name), None)
if tool is None:
return {"error": f"Unknown tool {name}"}
schema = tool["input_schema"]
for field in schema["required"]:
if field not in args:
return {"error": f"Missing argument {field}"}
for field, value in args.items():
spec = schema["properties"].get(field)
if spec is None or not isinstance(value, TYPES[spec["type"]]):
return {"error": f"Invalid argument {field}={value!r}"}
if value < spec.get("minimum", value) or value > spec.get("maximum", value):
return {"error": f"{field} out of range"}
try:
return FUNCTIONS[name](**args)
except requests.RequestException:
return {"error": f"{name} couldn't reach its service. Try again later."}
# ---------- 3. A scripted stand-in for the model (swap in a real LLM later) ----------
def scripted_model(history):
results = {r["name"]: r["result"] for r in history if r.get("role") == "tool"}
errors = [r["error"] for r in results.values() if isinstance(r, dict) and "error" in r]
if errors: # a real model would explain or retry
return "Sorry, something went wrong: " + errors[0]
if not results: # step 1: two independent calls at once
return [("find_city", {"name": "Lisbon"}), ("convert_currency", {"amount": 300, "from_currency": "EUR", "to_currency": "USD"})]
if "get_forecast" not in results: # step 2: needs the city's coordinates first
city = results["find_city"]
return [("get_forecast", {"latitude": city["latitude"], "longitude": city["longitude"], "days": 3})]
money, days = results["convert_currency"], results["get_forecast"]
lines = [f"{d['date']}: {d['min_c']:.0f}-{d['max_c']:.0f}°C, {d['rain_chance']}% chance of rain" for d in days]
return "Lisbon for the next 3 days:\n" + "\n".join(lines) + (
f"\n300 EUR is about {money['result']:.2f} USD today (rate {money['rate']}).")
# ---------- 4. The agent loop ----------
history = [{"role": "user", "content": "I'm in Lisbon for 3 days with 300 euros. Weather, and how much is that in dollars?"}]
for step in range(1, 6):
decision = scripted_model(history)
if isinstance(decision, str):
print("\nANSWER:\n" + decision)
break
for name, args in decision:
result = run_tool(name, args)
print(f"step {step}: {name}({args})")
history.append({"role": "tool", "name": name, "result": result})Look at what the program does:
- Tools call real APIs, with timeouts, and return compact dictionaries with only the fields the model needs.
- Definitions describe each tool with a purpose, return values and tight schemas (
minimum,maximum,additionalProperties). run_toolchecks the name, required arguments, types and ranges, and turns network failures into readable errors instead of crashes.- Step 1 asks for two independent calls at once: the city and the exchange rate.
- Step 2 needs the city's coordinates, so the forecast comes in a second round.
- The answer uses only numbers that came from tools.
With a real model
On your own computer (pip install anthropic requests, with your API key set), replace the scripted model with a real one. The tools, definitions and run_tool stay exactly the same; only the loop changes:
import json
import requests
# ---------- 1. Tools that call real, free web APIs (no key needed) ----------
def find_city(name):
r = requests.get("https://geocoding-api.open-meteo.com/v1/search",
params={"name": name, "count": 1}, timeout=10)
r.raise_for_status()
results = r.json().get("results")
if not results:
return {"error": f"No city called {name!r}. Check the spelling or add the country."}
c = results[0]
return {"name": c["name"], "country": c.get("country"), "latitude": c["latitude"], "longitude": c["longitude"]}
def get_forecast(latitude, longitude, days):
r = requests.get("https://api.open-meteo.com/v1/forecast", params={
"latitude": latitude, "longitude": longitude, "forecast_days": days, "timezone": "auto",
"daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_max",
}, timeout=10)
r.raise_for_status()
d = r.json()["daily"]
return [{"date": day, "max_c": hi, "min_c": lo, "rain_chance": rain}
for day, hi, lo, rain in zip(d["time"], d["temperature_2m_max"],
d["temperature_2m_min"], d["precipitation_probability_max"])]
def convert_currency(amount, from_currency, to_currency):
r = requests.get("https://api.frankfurter.dev/v1/latest",
params={"base": from_currency, "symbols": to_currency}, timeout=10)
if r.status_code != 200:
return {"error": f"Can't convert {from_currency} to {to_currency}. Use codes like EUR, USD, GBP."}
rate = r.json()["rates"][to_currency]
return {"amount": amount, "from": from_currency, "to": to_currency, "rate": rate, "result": round(amount * rate, 2)}
TOOLS = [
{"name": "find_city",
"description": "Find a city's coordinates. Use before get_forecast. Returns name, country, latitude and longitude.",
"input_schema": {"type": "object", "properties": {
"name": {"type": "string", "description": "City name, e.g. 'Lisbon' or 'Paris, France'"}},
"required": ["name"], "additionalProperties": False}},
{"name": "get_forecast",
"description": "Daily weather forecast for coordinates. Returns per day: max and min °C and rain chance in %.",
"input_schema": {"type": "object", "properties": {
"latitude": {"type": "number", "minimum": -90, "maximum": 90},
"longitude": {"type": "number", "minimum": -180, "maximum": 180},
"days": {"type": "integer", "minimum": 1, "maximum": 7, "description": "Number of days, starting today"}},
"required": ["latitude", "longitude", "days"], "additionalProperties": False}},
{"name": "convert_currency",
"description": "Convert money using today's exchange rate. Returns the rate and the converted amount.",
"input_schema": {"type": "object", "properties": {
"amount": {"type": "number", "minimum": 0},
"from_currency": {"type": "string", "description": "Three-letter code, e.g. EUR"},
"to_currency": {"type": "string", "description": "Three-letter code, e.g. USD"}},
"required": ["amount", "from_currency", "to_currency"], "additionalProperties": False}},
]
FUNCTIONS = {"find_city": find_city, "get_forecast": get_forecast, "convert_currency": convert_currency}
# ---------- 2. Validate, run, and never crash ----------
TYPES = {"string": str, "number": (int, float), "integer": int}
def run_tool(name, args):
tool = next((t for t in TOOLS if t["name"] == name), None)
if tool is None:
return {"error": f"Unknown tool {name}"}
schema = tool["input_schema"]
for field in schema["required"]:
if field not in args:
return {"error": f"Missing argument {field}"}
for field, value in args.items():
spec = schema["properties"].get(field)
if spec is None or not isinstance(value, TYPES[spec["type"]]):
return {"error": f"Invalid argument {field}={value!r}"}
if value < spec.get("minimum", value) or value > spec.get("maximum", value):
return {"error": f"{field} out of range"}
try:
return FUNCTIONS[name](**args)
except requests.RequestException:
return {"error": f"{name} couldn't reach its service. Try again later."}
# ---------- 3. The agent loop with a real model ----------
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
SYSTEM = ("You are a travel helper. Use the tools for weather and money questions; never guess numbers. "
"If a tool returns an error, fix your arguments or explain the problem to the user.")
def run_agent(question, max_steps=8):
messages = [{"role": "user", "content": question}]
for step in range(max_steps):
response = client.messages.create(model="MODEL_NAME", max_tokens=1000, system=SYSTEM,
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
results = []
for block in response.content:
if block.type == "tool_use":
output = run_tool(block.name, block.input)
print(f" {block.name}({block.input}) -> {str(output)[:80]}")
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(output), "is_error": "error" in output})
messages.append({"role": "user", "content": results})
return "Stopped: too many steps."
if __name__ == "__main__":
print(run_agent("I'm in Lisbon for 3 days with 300 euros. Weather, and how much is that in dollars?"))A real model writes its own answer and may phrase things differently, add advice (“pack an umbrella for Wednesday”), or ask a follow-up question. The system prompt tells it to use tools for numbers and never guess them.
Things to try
- Ask about a city with a common name, such as “Springfield”. How should
find_cityhandle several matches? - Ask for 10 days. The schema allows at most 7: what does the model do with the error?
- Add a
best_day_for_outdoorstool (the exercise below gives you its logic). - Ask for a currency code that doesn't exist, like “XYZ”, and check the error message.
Common mistakes
Write the logic for a new tool that the agent could call: pick the best day for being outdoors.
# What get_forecast returned for three days
forecast = [
{"date": "2026-11-18", "max_c": 19.9, "min_c": 16.6, "rain_chance": 78},
{"date": "2026-11-19", "max_c": 17.9, "min_c": 12.5, "rain_chance": 3},
{"date": "2026-11-20", "max_c": 17.3, "min_c": 12.7, "rain_chance": 15},
]
# A new tool, best_day_for_outdoors, should pick the day with the lowest rain chance.
# Print it like: Best day: 2026-01-01 (10% rain, up to 20°C)
Why does the agent call get_forecast in a second round instead of together with find_city?
Summary
- The travel helper connects a model to real APIs through three well-described tools.
- Validation and error handling in
run_toolkeep every call safe and every failure readable. - Independent calls run in parallel; dependent calls happen in later rounds.
- Swapping the scripted model for a real LLM changes only the loop.
Course complete
You can now define tools with JSON Schema, run the full tool call round trip, handle parallel calls, write descriptions models understand, validate arguments, handle errors safely, manage large tool sets, and connect a model to real APIs. Next: the Model Context Protocol (MCP) course shows a standard way to share tools across apps and models.
Finished reading? Tick it off to track your progress.