{"slug": "give-your-ai-agent-an-ip-lookup-tool-with-function-calling", "title": "Give Your AI Agent an IP Lookup Tool With Function Calling", "summary": "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.", "body_md": "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.\n\nThis 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.\n\n`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`.\nThe 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.\n\nHow 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.\n\nFunction 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.\n\nPython 3.10 or later (the code uses `str | None` hints) and three packages:\n\n```\npip install openai anthropic requests\n```\n\nSet `IPGEO_API_KEY`, plus `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` for whichever model you call.\n\nAny 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.\n\nEverything in this section and the next three lives in one file, `ip_tool.py`. The blocks are in file order.\n\n```\n\"\"\"lookup_ip: one IP lookup tool, shared by the OpenAI and Claude loops.\"\"\"\nimport ipaddress\nimport logging\nimport os\nimport time\n\nimport requests\n\nlog = logging.getLogger(\"ip_tool\")\n\nDESCRIPTION = (\n    \"Look up the approximate network location of a public IPv4 or IPv6 address: \"\n    \"country, region, city, coordinates, ASN and network owner, and IANA time zone. \"\n    \"This is where the IP's network is located, not the position of a person or \"\n    \"device, and city-level results can be wrong. Do not call it for private, \"\n    \"loopback, or reserved addresses (10.x, 192.168.x, 127.0.0.1). If the result \"\n    \"has an 'error' field, tell the user what went wrong; retry only when \"\n    \"'retryable' is true.\"\n)\n\nPARAMETERS = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"ip\": {\n            \"type\": \"string\",\n            \"description\": \"One public IPv4 or IPv6 address, e.g. 8.8.8.8\",\n        }\n    },\n    \"required\": [\"ip\"],\n    \"additionalProperties\": False,\n}\n\n# Same schema, two envelopes.\nOPENAI_TOOL = {\"type\": \"function\", \"name\": \"lookup_ip\", \"description\": DESCRIPTION,\n               \"parameters\": PARAMETERS, \"strict\": True}\nCLAUDE_TOOL = {\"name\": \"lookup_ip\", \"description\": DESCRIPTION,\n               \"input_schema\": PARAMETERS, \"strict\": True}\n```\n\n`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.\n\nRead 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.\n\nThe 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.\n\nThe error sentence matters because a model that sees a bare failure may just try again. With a metered API, every retry is a credit.\n\nA 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.\n\nSplit 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.\n\n``` php\ndef _public_ip(raw: str) -> str | None:\n    \"\"\"Normalize the model's argument; None if it isn't a public address.\"\"\"\n    try:\n        ip = ipaddress.ip_address(str(raw).strip())\n    except ValueError:\n        return None\n    # is_global is True for multicast (224.0.0.0/4), so exclude it explicitly.\n    if not ip.is_global or ip.is_multicast:\n        return None\n    return str(ip)\n```\n\n`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.\n\nThe 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.\n\nThe full free-plan response for 8.8.8.8, every field included:\n\n```\n{\n  \"ip\": \"8.8.8.8\",\n  \"location\": {\n    \"continent_code\": \"NA\",\n    \"continent_name\": \"North America\",\n    \"country_code2\": \"US\",\n    \"country_code3\": \"USA\",\n    \"country_name\": \"United States\",\n    \"country_name_official\": \"United States of America\",\n    \"country_capital\": \"Washington, D.C.\",\n    \"state_prov\": \"California\",\n    \"state_code\": \"US-CA\",\n    \"district\": \"Santa Clara\",\n    \"city\": \"Mountain View\",\n    \"zipcode\": \"94043-1351\",\n    \"latitude\": \"37.42240\",\n    \"longitude\": \"-122.08421\",\n    \"is_eu\": false,\n    \"country_flag\": \"https://ipgeolocation.io/static/flags/us_64.png\",\n    \"geoname_id\": \"6301403\",\n    \"country_emoji\": \"\\ud83c\\uddfa\\ud83c\\uddf8\"\n  },\n  \"country_metadata\": {\n    \"calling_code\": \"+1\",\n    \"tld\": \".us\",\n    \"languages\": [\"en-US\", \"es-US\", \"haw\", \"fr\"]\n  },\n  \"currency\": { \"code\": \"USD\", \"name\": \"US Dollar\", \"symbol\": \"$\" },\n  \"asn\": { \"as_number\": \"AS15169\", \"organization\": \"Google LLC\", \"country\": \"US\" },\n  \"time_zone\": {\n    \"name\": \"America/Los_Angeles\",\n    \"offset\": -8,\n    \"offset_with_dst\": -8,\n    \"current_time\": \"2026-11-23 06:07:54.725-0800\",\n    \"current_time_unix\": 1795442874.725,\n    \"current_tz_abbreviation\": \"PST\",\n    \"current_tz_full_name\": \"Pacific Standard Time\",\n    \"standard_tz_abbreviation\": \"PST\",\n    \"standard_tz_full_name\": \"Pacific Standard Time\",\n    \"is_dst\": false,\n    \"dst_savings\": 0,\n    \"dst_exists\": true,\n    \"dst_tz_abbreviation\": \"PDT\",\n    \"dst_tz_full_name\": \"Pacific Daylight Time\",\n    \"dst_start\": {\n      \"utc_time\": \"2027-03-14 TIME 10:00\",\n      \"duration\": \"+1.00H\",\n      \"gap\": true,\n      \"date_time_after\": \"2027-03-14 TIME 03:00\",\n      \"date_time_before\": \"2027-03-14 TIME 02:00\",\n      \"overlap\": false\n    },\n    \"dst_end\": {\n      \"utc_time\": \"2027-11-07 TIME 09:00\",\n      \"duration\": \"-1.00H\",\n      \"gap\": false,\n      \"date_time_after\": \"2027-11-07 TIME 01:00\",\n      \"date_time_before\": \"2027-11-07 TIME 02:00\",\n      \"overlap\": true\n    }\n  }\n}\n```\n\nPaid 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.\n\n```\nIPGEO_URL = \"https://api.ipgeolocation.io/v3/ipgeo\"\n# Ask the API for these paths only. `fields` works on the free plan too.\nFIELDS = \",\".join([\n    \"location.country_name\", \"location.country_code2\", \"location.state_prov\",\n    \"location.city\", \"location.latitude\", \"location.longitude\",\n    \"asn.as_number\", \"asn.organization\", \"time_zone.name\",\n])\n\ndef _to_float(value) -> float | None:\n    # The API returns coordinates as strings, e.g. \"37.42240\".\n    try:\n        return float(value)\n    except (TypeError, ValueError):\n        return None\n\ndef _shape(data: dict) -> dict:\n    \"\"\"Map the vendor's response onto our own small, stable schema.\"\"\"\n    loc = data.get(\"location\") or {}\n    asn = data.get(\"asn\") or {}\n    tz = data.get(\"time_zone\") or {}\n    return {\n        \"ip\": data.get(\"ip\"),\n        \"country\": loc.get(\"country_name\"),\n        \"country_code\": loc.get(\"country_code2\"),\n        \"region\": loc.get(\"state_prov\"),\n        \"city\": loc.get(\"city\"),\n        \"latitude\": _to_float(loc.get(\"latitude\")),\n        \"longitude\": _to_float(loc.get(\"longitude\")),\n        \"asn\": asn.get(\"as_number\"),\n        \"network_owner\": asn.get(\"organization\"),\n        \"time_zone\": tz.get(\"name\"),\n    }\n```\n\nTwo 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:\n\n```\n{\"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\"}\n```\n\n84 tokens. Same answer, about a seventh of the context.\n\nipgeolocation.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:\n\n```\nrequests.exceptions.HTTPError: 401 Client Error: Unauthorized for url:\nhttps://api.ipgeolocation.io/v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8&fields=location.city\n```\n\nConnection 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.\n\n```\n# Fixed messages only. Never forward exception text: requests puts the full\n# request URL in it, and this URL carries apiKey.\nHTTP_ERRORS = {\n    401: (\"rejected\", \"The IP data API rejected the key or this plan lacks the data.\", False),\n    403: (\"forbidden\", \"This server's IP is not allowed to use the API key.\", False),\n    423: (\"not_public\", \"That address is private or reserved and has no location.\", False),\n    429: (\"out_of_credits\", \"The IP lookup quota is used up. Try again later.\", False),\n}\n\nCACHE_TTL = 300  # seconds\n_cache: dict[str, tuple[float, dict]] = {}\n\ndef tool_error(code: str, message: str, retryable: bool) -> dict:\n    return {\"error\": code, \"message\": message, \"retryable\": retryable}\n```\n\nThe 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.\n\nThe 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.\n\nThe function the model actually calls is the longest block in the post, because every decision above meets in it.\n\n``` php\ndef lookup_ip(ip: str) -> dict:\n    \"\"\"Run the tool. Always returns a dict; never raises into the agent loop.\"\"\"\n    clean = _public_ip(ip)\n    if clean is None:\n        # Echo at most 45 chars (the longest IPv6 text form) back to the model.\n        return tool_error(\"not_public\", f\"{str(ip)[:45]!r} is not a public IP address.\", False)\n\n    hit = _cache.get(clean)\n    if hit and time.monotonic() - hit[0] < CACHE_TTL:\n        return hit[1]\n\n    api_key = os.environ.get(\"IPGEO_API_KEY\")\n    if not api_key:\n        return tool_error(\"not_configured\", \"The IP lookup tool has no API key.\", False)\n\n    try:\n        resp = requests.get(\n            IPGEO_URL,\n            params={\"apiKey\": api_key, \"ip\": clean, \"fields\": FIELDS},\n            timeout=(1.0, 3.0),  # connect, read\n        )\n    except requests.Timeout:\n        log.warning(\"ipgeo timeout for %s\", clean)\n        return tool_error(\"timeout\", \"The IP lookup timed out.\", True)\n    except requests.RequestException as exc:\n        # Log the type, not str(exc): the message contains the URL and the key.\n        log.warning(\"ipgeo request failed: %s\", type(exc).__name__)\n        return tool_error(\"network\", \"The IP lookup service could not be reached.\", True)\n\n    if resp.status_code != 200:\n        code, message, retryable = HTTP_ERRORS.get(\n            resp.status_code,\n            (\"upstream\", f\"The IP lookup failed with HTTP {resp.status_code}.\",\n             resp.status_code >= 500),\n        )\n        return tool_error(code, message, retryable)\n\n    try:\n        data = resp.json()\n        if not isinstance(data, dict):\n            raise ValueError(\"Unexpected response shape\")\n\n        if any(\n            key in data and not isinstance(data[key], (dict, type(None)))\n            for key in (\"location\", \"asn\", \"time_zone\")\n        ):\n            raise ValueError(\"Unexpected nested response shape\")\n\n        result = _shape(data)\n    except (ValueError, TypeError, AttributeError):\n        return tool_error(\n            \"upstream\",\n            \"The IP lookup returned an unreadable response.\",\n            True,\n        )\n\n    if len(_cache) > 1000:  # crude bound; use Redis if you run several workers\n        _cache.clear()\n    _cache[clean] = (time.monotonic(), result)\n    return result\n```\n\nThe 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.\n\n``` python\nimport json\nimport os\n\nimport openai\nfrom openai import OpenAI\n\nfrom ip_tool import OPENAI_TOOL, lookup_ip, tool_error\n\nMAX_ROUNDS = 4  # each round can cost a credit; a confused model can loop\n\ndef run_tool(name: str, raw_args: str) -> dict:\n    if name != \"lookup_ip\":\n        return tool_error(\"unknown_tool\", f\"No tool named {name}.\", False)\n    try:\n        args = json.loads(raw_args or \"{}\")\n    except json.JSONDecodeError:\n        return tool_error(\"bad_arguments\", \"Arguments were not valid JSON.\", False)\n    return lookup_ip(args.get(\"ip\", \"\"))\n\ndef ask(question: str) -> str:\n    client = OpenAI(timeout=30.0)  # reads OPENAI_API_KEY; default read timeout is 600s\n    model = os.environ.get(\"OPENAI_MODEL\", \"gpt-6.2-astra\")  # names change; check the docs\n    items: list = [{\"role\": \"user\", \"content\": question}]\n\n    for _ in range(MAX_ROUNDS):\n        try:\n            response = client.responses.create(model=model, tools=[OPENAI_TOOL], input=items)\n        except openai.APIError as exc:\n            return f\"Model request failed: {type(exc).__name__}\"\n\n        calls = [item for item in response.output if item.type == \"function_call\"]\n        if not calls:\n            return response.output_text\n\n        # Send back everything the model produced (reasoning items included),\n        # then one function_call_output per call. The model may call in parallel.\n        items += response.output\n        for call in calls:\n            items.append({\n                \"type\": \"function_call_output\",\n                \"call_id\": call.call_id,\n                \"output\": json.dumps(run_tool(call.name, call.arguments)),\n            })\n\n    return \"Stopped after too many tool calls for one question.\"\n\nif __name__ == \"__main__\":\n    print(ask(\"Where is 8.8.8.8, and what time zone is it in?\"))\n```\n\n`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.\n\n`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.\n\nClaude'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`.\n\n``` python\nimport json\nimport os\n\nimport anthropic\n\nfrom ip_tool import CLAUDE_TOOL, lookup_ip, tool_error\n\nMAX_ROUNDS = 4\n\ndef ask(question: str) -> str:\n    client = anthropic.Anthropic(timeout=30.0)  # reads ANTHROPIC_API_KEY\n    model = os.environ.get(\"ANTHROPIC_MODEL\", \"claude-sonnet-5-5\")\n    messages: list = [{\"role\": \"user\", \"content\": question}]\n\n    for _ in range(MAX_ROUNDS):\n        try:\n            response = client.messages.create(\n                model=model, max_tokens=1024, tools=[CLAUDE_TOOL], messages=messages\n            )\n        except anthropic.APIError as exc:\n            return f\"Model request failed: {type(exc).__name__}\"\n\n        if response.stop_reason != \"tool_use\":\n            return \"\".join(b.text for b in response.content if b.type == \"text\")\n\n        # The assistant turn goes back unchanged; results follow in one user turn.\n        messages.append({\"role\": \"assistant\", \"content\": response.content})\n        results = []\n        for block in response.content:\n            if block.type != \"tool_use\":\n                continue\n            if block.name == \"lookup_ip\":\n                result = lookup_ip((block.input or {}).get(\"ip\", \"\"))\n            else:\n                result = tool_error(\"unknown_tool\", f\"No tool named {block.name}.\", False)\n            results.append({\n                \"type\": \"tool_result\",\n                \"tool_use_id\": block.id,\n                \"content\": json.dumps(result),\n                \"is_error\": \"error\" in result,  # lets Claude explain instead of guess\n            })\n        messages.append({\"role\": \"user\", \"content\": results})\n\n    return \"Stopped after too many tool calls for one question.\"\n\nif __name__ == \"__main__\":\n    print(ask(\"Where is 8.8.8.8, and what time zone is it in?\"))\n```\n\n`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.\n\nAgents 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.\n\nASN 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.\n\nKeep 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.\n\nIPinfo, 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:\n\n```\n{\n  \"mcpServers\": {\n    \"ipgeolocation\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"ipgeolocation-io-mcp@latest\"],\n      \"env\": { \"IPGEOLOCATION_API_KEY\": \"<YOUR_API_KEY>\" }\n    }\n  }\n}\n```\n\nYou get security, ASN, abuse contact, time zone, and bulk tools without writing them, and the server already caches results and returns error guidance. Keep the real key in your client's private config, not a committed file.\n\nFrom your own code calling a model API, check the connector's authentication support. OpenAI's Responses API supports a `headers` field in its [MCP tool configuration](https://developers.openai.com/api/reference/resources/responses/methods/create), so it can send the `X-IPGeolocation-API-Key` header required by `https://mcp.ipgeolocation.io/mcp`. Claude's [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) currently documents bearer authentication through `authorization_token`, without a custom-header option. Connecting that connector to this hosted server therefore requires an authentication bridge or an MCP client you control. For one narrow lookup, a function still gives you direct control over validation, caching, and the response shape.\n\nMy rule: one narrow tool in your own agent, write the function. Five tools, or the same tools in several clients, use the server.\n\nPaid plans can add `include=security` to the request for VPN, proxy, Tor, and threat-score fields, at 2 extra credits per lookup. A free key that names the module gets HTTP 401, which `HTTP_ERRORS` already turns into a readable error. If you add it, make it a separate tool and register it only for sessions allowed to see that data.\n\nIPv6 needs no changes. `2001:4860:4860::8888` goes through the same validation, request, and shape.\n\nEnriching 10,000 log lines isn't an agent job. Use the bulk endpoint from a script and keep tool calls for questions a person actually asked.\n\nLog the tool name, the normalized IP, the error code, and the latency. Not the URL.\n\nBefore you ship, give each conversation a lookup budget on top of `MAX_ROUNDS`, and watch which error codes show up in the first week of logs. A pile of `not_public` errors often means users are pasting their router's address, which is a prompt problem, not an API one.", "url": "https://wpnews.pro/news/give-your-ai-agent-an-ip-lookup-tool-with-function-calling", "canonical_source": "https://dev.to/abdullah_afzal/give-your-ai-agent-an-ip-lookup-tool-with-function-calling-4pdl", "published_at": "2026-11-23 15:10:17+00:00", "updated_at": "2026-11-23 15:15:11.726485+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["OpenAI", "Anthropic", "ipgeolocation.io", "IPinfo", "MaxMind", "Claude", "Python"], "also_reported_by": [], "takeaway": "Writing a precise tool description and returning structured, model-readable error results matters more than the plumbing, and trimming the response payload cut token use from 576 to 84.", "recommendation": {"advice": "Write detailed tool descriptions covering purpose, parameters and output meaning, validate inputs, and return readable error objects with a retryable flag so the agent can recover.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/give-your-ai-agent-an-ip-lookup-tool-with-function-calling", "markdown": "https://wpnews.pro/news/give-your-ai-agent-an-ip-lookup-tool-with-function-calling.md", "text": "https://wpnews.pro/news/give-your-ai-agent-an-ip-lookup-tool-with-function-calling.txt", "jsonld": "https://wpnews.pro/news/give-your-ai-agent-an-ip-lookup-tool-with-function-calling.jsonld"}}