Give Your AI Agent an IP Lookup Tool With Function Calling A developer built a working IP lookup tool for LLM agents, wiring a single validated Python function into both OpenAI's Responses API and Anthropic's Messages API. The implementation adds strict JSON Schema validation, error results the model can read, a five-minute cache, and a trimmed response that cut output from 576 tokens to 84. The writeup stresses that the tool description, not the code, is what drives when the model decides to call the function. LLM function calling guides love a fake tool. OpenAI's function calling guide https://developers.openai.com/api/docs/guides/function-calling demos a horoscope function that promises you'll "befriend a baby otter." Anthropic's tool use overview https://platform.claude.com/docs/en/agents-and-tools/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. ipaddress catches private and reserved ranges, but is global lets multicast through. requests error messages contain the key. parameters and function call output ; Claude wants input schema and tool result . 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. 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 https://ipgeolocation.io/documentation/ip-location-api.html list every path. Switching providers later means changing one HTTP call and one mapping function. 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. 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. 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. php 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. 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": "\ud83c\uddfa\ud83c\uddf8" }, "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. 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 https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-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. php 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 "not public", f"{str ip :45 r} is not a public IP address.", False hit = cache.get clean if hit and time.monotonic - hit 0 < CACHE TTL: return hit 1 api key = os.environ.get "IPGEO API KEY" if not api key: return tool error "not configured", "The IP lookup tool has no API key.", False try: resp = requests.get IPGEO URL, params={"apiKey": api key, "ip": clean, "fields": FIELDS}, timeout= 1.0, 3.0 , connect, read except requests.Timeout: log.warning "ipgeo timeout for %s", clean return tool error "timeout", "The IP lookup timed out.", True except requests.RequestException as exc: Log the type, not str exc : the message contains the URL and the key. log.warning "ipgeo request failed: %s", type exc . name return tool error "network", "The IP lookup service could not be reached.", True if resp.status code = 200: code, message, retryable = HTTP ERRORS.get resp.status code, "upstream", f"The IP lookup failed with HTTP {resp.status code}.", resp.status code = 500 , return tool error code, message, retryable try: data = resp.json if not isinstance data, dict : raise ValueError "Unexpected response shape" if any key in data and not isinstance data key , dict, type None for key in "location", "asn", "time zone" : raise ValueError "Unexpected nested response shape" result = shape data except ValueError, TypeError, AttributeError : return tool error "upstream", "The IP lookup returned an unreadable response.", True, if len cache 1000: crude bound; use Redis if you run several workers cache.clear cache clean = time.monotonic , result return result The contract is in the docstring: it always returns a dict and never raises. An exception that escapes a tool kills the whole agent turn, and the user gets a stack trace instead of "that address is private." That makes the tool fail-open for the conversation: if the IP API is down, the agent says it couldn't look the address up and carries on, instead of the whole request failing. python import json import os import openai from openai import OpenAI from ip tool import OPENAI TOOL, lookup ip, tool error MAX ROUNDS = 4 each round can cost a credit; a confused model can loop def run tool name: str, raw args: str - dict: if name = "lookup ip": return tool error "unknown tool", f"No tool named {name}.", False try: args = json.loads raw args or "{}" except json.JSONDecodeError: return tool error "bad arguments", "Arguments were not valid JSON.", False return lookup ip args.get "ip", "" def ask question: str - str: client = OpenAI timeout=30.0 reads OPENAI API KEY; default read timeout is 600s model = os.environ.get "OPENAI MODEL", "gpt-6.2-astra" names change; check the docs items: list = {"role": "user", "content": question} for in range MAX ROUNDS : try: response = client.responses.create model=model, tools= OPENAI TOOL , input=items except openai.APIError as exc: return f"Model request failed: {type exc . name }" calls = item for item in response.output if item.type == "function call" if not calls: return response.output text Send back everything the model produced reasoning items included , then one function call output per call. The model may call in parallel. items += response.output for call in calls: items.append { "type": "function call output", "call id": call.call id, "output": json.dumps run tool call.name, call.arguments , } return "Stopped after too many tool calls for one question." if name == " main ": print ask "Where is 8.8.8.8, and what time zone is it in?" items += response.output mirrors the OpenAI function calling example in the docs and keeps any reasoning items in the history next to the calls they produced. Every function call gets a function call output with the matching call id . "Compare 8.8.8.8 and 1.1.1.1" can produce two calls in one turn, so the loop handles all of them, not just the first. Even with strict mode on, run tool still guards against unknown tool names and bad JSON; it costs four lines. MAX ROUNDS is cheap insurance. A model stuck retrying a failing lookup spends a credit every round, and four rounds is plenty for any sane question about IPs. Claude's tool use differs in three places: the schema key is input schema , results go back as tool result blocks inside a user turn, and errors carry is error: true . python import json import os import anthropic from ip tool import CLAUDE TOOL, lookup ip, tool error MAX ROUNDS = 4 def ask question: str - str: client = anthropic.Anthropic timeout=30.0 reads ANTHROPIC API KEY model = os.environ.get "ANTHROPIC MODEL", "claude-sonnet-5-5" messages: list = {"role": "user", "content": question} for in range MAX ROUNDS : try: response = client.messages.create model=model, max tokens=1024, tools= CLAUDE TOOL , messages=messages except anthropic.APIError as exc: return f"Model request failed: {type exc . name }" if response.stop reason = "tool use": return "".join b.text for b in response.content if b.type == "text" The assistant turn goes back unchanged; results follow in one user turn. messages.append {"role": "assistant", "content": response.content} results = for block in response.content: if block.type = "tool use": continue if block.name == "lookup ip": result = lookup ip block.input or {} .get "ip", "" else: result = tool error "unknown tool", f"No tool named {block.name}.", False results.append { "type": "tool result", "tool use id": block.id, "content": json.dumps result , "is error": "error" in result, lets Claude explain instead of guess } messages.append {"role": "user", "content": results} return "Stopped after too many tool calls for one question." if name == " main ": print ask "Where is 8.8.8.8, and what time zone is it in?" ip tool.py didn't change at all. That's the payoff of keeping the tool provider-neutral: the adapters are envelopes, and the logic you tested lives in one place. Anthropic's docs note that Claude may call the tool again after an error, so the round cap earns its keep here too. Agents re-ask. A follow-up about the same address can trigger a second identical call, and a parallel turn can request the same IP twice. The dict cache inside lookup ip keys on the normalized address, so " 8.8.8.8 " and 8.8.8.8 share an entry, and a hit costs nothing. Five minutes matches the default the official ipgeolocation.io MCP server uses for lookup results. It's per process, though. Once you run more than one worker, move it to Redis with the same TTL. ASN organization names, hostnames, and WHOIS records are written by whoever registered the network. Nearly all of them are boring Google LLC . They don't have to be, and you don't control them. Keep tool output inside the tool result, never in the system prompt, and don't chain it straight into another tool call without a check. Anthropic's tool-handling guide says it plainly: "Keep untrusted content inside tool result blocks rather than system prompts or plain user text blocks." This is one more reason shape returns ten named fields instead of the raw response. The model sees keys you chose, not whatever the upstream decided to send this week. IPinfo, IP2Location, ipstack, and IPGeolocation all ship MCP servers now; the official ipgeolocation.io server documents 16 tools covering geolocation, security, ASN, time zones, abuse contacts, and more. If your agent lives in Claude Desktop, Cursor, VS Code, Cline, or Codex CLI, install it and skip everything above: { "mcpServers": { "ipgeolocation": { "command": "npx", "args": "-y", "ipgeolocation-io-mcp@latest" , "env": { "IPGEOLOCATION API KEY": "