Give Your AI Agent an IP Lookup Tool With Function Calling
DEV Community

Give Your AI Agent an IP Lookup Tool With Function Calling

How LLM function calling works

The model doesn't call anything. You send it a list of tools, each with a name, a description, and a JSON Schema for its arguments. When the model decides a tool would help, it stops and returns a structured call instead of text: lookup_ip with {"ip": "8.8.8.8"}.

Your code runs the lookup, appends the result to the conversation, and calls the model again. That round trip repeats until the model answers in plain text.

How does it pick the moment? Mostly from the description. Anthropic's docs say Claude "determines when to call a tool based on the user's request and the tool's description," and OpenAI's best practices ask you to explain the function's purpose, each parameter, and what the output represents. The description is the real prompt. The code behind it is plumbing.

Function calling and LLM tool calling are the same mechanism. OpenAI's guide opens with "Function calling (also known as tool calling)"; "tool" is the broader word because models also get built-in tools like web search. I'll use both.

LLM function calling guides love a fake tool. OpenAI's function calling guide demos a horoscope function that promises you'll "befriend a baby otter." Anthropic's tool use overview hardcodes "15 degrees Celsius, partly cloudy." Fine for showing the loop. Useless for learning what breaks when the function behind the tool calls a real, metered API.

This post builds an IP lookup tool an agent can call: a strict schema, input validation, error results the model can read, a response cut from 576 tokens to 84, a five-minute cache, and the same function wired into OpenAI's Responses API and Claude's Messages API. Python, about 250 lines across three files.

TL;DR:

  • The model never calls your API. It returns a tool name and JSON arguments; your code runs the call and sends the result back.
  • Validate the IP in code before spending a credit. Python's ipaddress catches private and reserved ranges, but is_global lets multicast through.
  • Never hand exception text to the model. When the API key sits in the query string, requests error messages contain the key.
  • Trim the response. The full free-plan response for 8.8.8.8 is 576 tokens; the fields an agent needs fit in 84.
  • Write one provider-neutral function and two thin adapters. OpenAI wants parameters and function_call_output; Claude wants input_schema and tool_result.
  • If your agent runs inside an MCP client like Claude Desktop or Cursor, install an MCP server instead. From your own code calling a model API, one function is usually less work.
  • Treat the tool like an API handed to someone who repeats everything they read. Return small, stable JSON. Turn every failure into a fixed message. Keep secrets and raw upstream text out of anything the model sees, because whatever the model sees, the user can eventually see too.

Setup

Python 3.10 or later (the code uses str | None hints) and three packages:

pip install openai anthropic requests

Set IPGEO_API_KEY, plus OPENAI_API_KEY or ANTHROPIC_API_KEY for whichever model you call.

Any IP data provider fits behind this function. IPinfo, IPGeolocation, MaxMind GeoIP2, ip-api, and IPLocate all return similar location fields. I'm using ipgeolocation.io because its free plan's 1,000 daily credits cover location, ASN, and time zone in one call, and its fields parameter lets the tool request only the paths it needs; the IP Geolocation API docs list every path. Switching providers later means changing one HTTP call and one mapping function.

Write the schema the model reads

Everything in this section and the next three lives in one file, ip_tool.py. The blocks are in file order.

"""lookup_ip: one IP lookup tool, shared by the OpenAI and Claude loops."""
import ipaddress
import logging
import os
import time
import requests
log = logging.getLogger("ip_tool")
DESCRIPTION = (
    "Look up the approximate network location of a public IPv4 or IPv6 address: "
    "country, region, city, coordinates, ASN and network owner, and IANA time zone. "
    "This is where the IP's network is located, not the position of a person or "
    "device, and city-level results can be wrong. Do not call it for private, "
    "loopback, or reserved addresses (10.x, 192.168.x, 127.0.0.1). If the result "
    "has an 'error' field, tell the user what went wrong; retry only when "
    "'retryable' is true."
)
PARAMETERS = {
    "type": "object",
    "properties": {
        "ip": {
            "type": "string",
            "description": "One public IPv4 or IPv6 address, e.g. 8.8.8.8",
        }
    },
    "required": ["ip"],
    "additionalProperties": False,
}
# Same schema, two envelopes.
OPENAI_TOOL = {
    "type": "function",
    "name": "lookup_ip",
    "description": DESCRIPTION,
    "parameters": PARAMETERS,
    "strict": True
}
CLAUDE_TOOL = {
    "name": "lookup_ip",
    "description": DESCRIPTION,
    "input_schema": PARAMETERS,
    "strict": True
}

strict: True with additionalProperties: False means both providers guarantee the arguments match the schema, so you never parse {"ipaddress": ...} or a missing field. It doesn't guarantee the string is a valid IP. That's the next section's job.

The description is the prompt

Read the description as a contract with the model. It says what comes back, what that data is not, when not to call, and what to do with an error. Every sentence is there because something goes wrong without it.

The middle sentence carries the most weight. Without it, nothing stops a model from telling someone "you're in Mountain View." For 8.8.8.8 that's especially wrong: it's Google's anycast DNS address, served from many places, and the lookup returns where the network is registered. IP location describes networks. Say so in the tool, not in a disclaimer the model never reads.

The error sentence matters because a model that sees a bare failure may just try again. With a metered API, every retry is a credit.

One tool, not four

A common design splits this into separate tools for location, ASN, reputation, and "what's my IP." I'd start with one. Every tool's schema rides along on every request, and every extra tool is another wrong choice the model can make. OpenAI's best practices say the same thing in their own words: keep the initial set of functions small, and combine functions that are always called in sequence.

Split when permissions differ. If only admins should see VPN and threat data, that's a second tool you register for admin sessions and never send otherwise.

Validate before you spend a credit

def _public_ip(raw: str) -> str | None:
    """Normalize the model's argument; None if it isn't a public address."""
    try:
        ip = ipaddress.ip_address(str(raw).strip())
    except ValueError:
        return None
    # is_global is True for multicast (224.0.0.0/4), so exclude it explicitly.
    if not ip.is_global or ip.is_multicast:
        return None
    return str(ip)

ipaddress handles IPv4 and IPv6, normalizes formatting, and is_global rejects RFC 1918 ranges, loopback, link-local, the CGNAT block 100.64.0.0/10, and the documentation ranges. One surprise from testing: ipaddress.ip_address("224.0.0.1").is_global is True. You can't geolocate a multicast group, so it gets its own check.

The API would reject these anyway (a private address comes back as HTTP 423 with '10.0.0.1' is a bogon IP address.), but catching them locally skips a network round trip and gives the model a clear answer in microseconds.

Call the API and trim what comes back

The full free-plan response for 8.8.8.8, every field included:

{
  "ip": "8.8.8.8",
  "location": {
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code2": "US",
    "country_code3": "USA",
    "country_name": "United States",
    "country_name_official": "United States of America",
    "country_capital": "Washington, D.C.",
    "state_prov": "California",
    "state_code": "US-CA",
    "district": "Santa Clara",
    "city": "Mountain View",
    "zipcode": "94043-1351",
    "latitude": "37.42240",
    "longitude": "-122.08421",
    "is_eu": false,
    "country_flag": "https://ipgeolocation.io/static/flags/us_64.png",
    "geoname_id": "6301403",
    "country_emoji": "πŸ‡ΊπŸ‡Έ"
  },
  "country_metadata": {
    "calling_code": "+1",
    "tld": ".us",
    "languages": ["en-US", "es-US", "haw", "fr"]
  },
  "currency": {"code": "USD", "name": "US Dollar", "symbol": "$"},
  "asn": {"as_number": "AS15169", "organization": "Google LLC", "country": "US"},
  "time_zone": {
    "name": "America/Los_Angeles",
    "offset": -8,
    "offset_with_dst": -8,
    "current_time": "2026-11-23 06:07:54.725-0800",
    "current_time_unix": 1795442874.725,
    "current_tz_abbreviation": "PST",
    "current_tz_full_name": "Pacific Standard Time",
    "standard_tz_abbreviation": "PST",
    "standard_tz_full_name": "Pacific Standard Time",
    "is_dst": false,
    "dst_savings": 0,
    "dst_exists": true,
    "dst_tz_abbreviation": "PDT",
    "dst_tz_full_name": "Pacific Daylight Time",
    "dst_start": {
      "utc_time": "2027-03-14 TIME 10:00",
      "duration": "+1.00H",
      "gap": true,
      "date_time_after": "2027-03-14 TIME 03:00",
      "date_time_before": "2027-03-14 TIME 02:00",
      "overlap": false
    },
    "dst_end": {
      "utc_time": "2027-11-07 TIME 09:00",
      "duration": "-1.00H",
      "gap": false,
      "date_time_after": "2027-11-07 TIME 01:00",
      "date_time_before": "2027-11-07 TIME 02:00",
      "overlap": true
    }
  }
}

Paid plans add network, company, and extra asn fields on top. Useful data for a log pipeline. For an agent answering "where is this IP?", most of it is noise: a flag URL, four language codes, a currency symbol, and two DST transition objects. As compact JSON that's 576 tokens (o200k_base tokenizer), and tool results stay in the conversation, so they get re-sent with every later request.

IPGEO_URL = "https://api.ipgeolocation.io/v3/ipgeo"
# Ask the API for these paths only. `fields` works on the free plan too.
FIELDS = ",".join(
    [
        "location.country_name",
        "location.country_code2",
        "location.state_prov",
        "location.city",
        "location.latitude",
        "location.longitude",
        "asn.as_number",
        "asn.organization",
        "time_zone.name",
    ]
)
def _to_float(value) -> float | None:
    # The API returns coordinates as strings, e.g. "37.42240".
    try:
        return float(value)
    except (TypeError, ValueError):
        return None
def _shape(data: dict) -> dict:
    """Map the vendor's response onto our own small, stable schema."""
    loc = data.get("location") or {}
    asn = data.get("asn") or {}
    tz = data.get("time_zone") or {}
    return {
        "ip": data.get("ip"),
        "country": loc.get("country_name"),
        "country_code": loc.get("country_code2"),
        "region": loc.get("state_prov"),
        "city": loc.get("city"),
        "latitude": _to_float(loc.get("latitude")),
        "longitude": _to_float(loc.get("longitude")),
        "asn": asn.get("as_number"),
        "network_owner": asn.get("organization"),
        "time_zone": tz.get("name"),
    }

Two things happen here. fields makes the API send only nine paths (plus ip, which always comes back), so less crosses the wire. _shape then maps the vendor's names onto yours: the model sees region, not state_prov, and if you swap providers next year, the shape the model has been reading doesn't change.

What the model gets:

{
  "ip": "8.8.8.8",
  "country": "United States",
  "country_code": "US",
  "region": "California",
  "city": "Mountain View",
  "latitude": 37.4224,
  "longitude": -122.08421,
  "asn": "AS15169",
  "network_owner": "Google LLC",
  "time_zone": "America/Los_Angeles"
}

84 tokens. Same answer, about a seventh of the context.

The error message that leaks your API key

ipgeolocation.io takes the key as an apiKey query parameter. Plenty of REST APIs do. It interacts badly with the way agents report errors. Here's what requests puts in an exception when that call returns 401:

requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.ipgeolocation.io/v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8&fields=location.city

Connection failures do the same thing: a DNS error prints Max retries exceeded with url: /v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8.

Now picture a common agent pattern, return f"Sorry, I encountered an error: {str(e)}", feeding the tool result. Your key is in the model's context, in your conversation logs, and one "what went wrong?" away from the user's screen.

# Fixed messages only. Never forward exception text: requests puts the full
# request URL in it, and this URL carries apiKey.
HTTP_ERRORS = {
    401: ("rejected", "The IP data API rejected the key or this plan lacks the data.", False),
    403: ("forbidden", "This server's IP is not allowed to use the API key.", False),
    423: ("not_public", "That address is private or reserved and has no location.", False),
    429: ("out_of_credits", "The IP lookup quota is used up. Try again later.", False),
}
CACHE_TTL = 300  # seconds
_cache: dict[str, tuple[float, dict]] = {}
def tool_error(code: str, message: str, retryable: bool) -> dict:
    return {"error": code, "message": message, "retryable": retryable}

The fix is boring on purpose: map status codes to messages you wrote, add a retryable flag so the model knows whether trying again makes sense, and log exception types, never exception strings. Anthropic's guide to handling tool calls recommends error messages that say what went wrong and what to try next. These do, without echoing anything from upstream.

The backstop is outside the code. Lock the key to your servers' IPs: IP whitelisting is available on every plan, including free, and a request with that key from anywhere else gets a 403. A leaked key that only works from your NAT gateway is a much smaller problem.

The function the model actually calls is the longest block in the post, because every decision above meets in it.

def lookup_ip(ip: str) -> dict:
    """Run the tool. Always returns a dict; never raises into the agent loop."""
    clean = _public_ip(ip)
    if clean is None:
        # Echo at most 45 chars (the longest IPv6 text form) back to the model.
        return tool_error(
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.