ai newsMi., 25. Nov.
EilmeldungYale’s Sonnenfeld: Nvidia is a ‘detriment’ to U.S. industrial might — not a champion

IP-Lookup-Tool für KI-Agenten: Function Calling mit echten Daten statt Demo-Fakes

Viele Anleitungen zum Function Calling von LLMs nutzenFake-Werkzeuge wie horoskopartige Beispielfunktionen mit erfundenen Ausgaben. Das zeigt die Schleife, aber nicht, was bei echten Werkzeugen schiefgeht.

dev.toMontag 16:10 · 23.11.DE18 Min. Lesezeit
Bild: dev.to

Anleitungen zum Function Calling mit LLMs lieben ein fingiertes Tool. OpenAIs Function-Calling-Guide demonstriert eine Horoskop-Funktion, die verspricht, man werde "einen Baby-Otter zum Freund haben". Anthropics Tool-Use-Übersicht hartcodiert "15 Grad Celsius, teilweise bewölkt". Gut genug, um den Ablauf zu zeigen. Nutzlos, um zu lernen, was schiefgeht, wenn die Funktion hinter dem Tool eine echte, kostenpflichtige API aufruft.

Dieser Beitrag baut ein IP-Lookup-Tool, das ein Agent aufrufen kann: ein striktes Schema, Eingabevalidierung, Fehlerergebnisse, die das Modell lesen kann, eine Antwort, die von 576 auf 84 Tokens reduziert wurde, ein Fünf-Minuten-Cache und dieselbe Funktion, angebunden an OpenAIs Responses API und Claudes Messages API. Python, rund 250 Zeilen verteilt auf drei Dateien.

Das Modell ruft selbst nichts auf. Man schickt ihm eine Liste von Tools, jeweils mit einem Namen, einer Beschreibung und einem JSON Schema für die Argumente. Wenn das Modell entscheidet, dass ein Tool helfen würde, stoppt es und gibt statt Text einen strukturierten Aufruf zurück: lookup_ip mit {"ip": "8.8.8.8"}. Der eigene Code führt den Lookup aus, hängt das Ergebnis an die Konversation an und ruft das Modell erneut auf. Dieser Roundtrip wiederholt sich, bis das Modell in normalem Text antwortet.

Wie wählt es den richtigen Zeitpunkt? Vor allem über die Beschreibung. Anthropics Dokumentation sagt, Claude "entscheidet anhand der Anfrage des Nutzers und der Beschreibung des Tools, wann ein Tool aufgerufen wird", und OpenAis Best Practices verlangen, den Zweck der Funktion, jeden Parameter und die Bedeutung der Ausgabe zu erklären. Die Beschreibung ist der eigentliche Prompt. Der Code dahinter ist nur Verrohrung.

Function Calling und LLM Tool Calling sind derselbe Mechanismus. OpenAis Guide beginnt mit "Function calling (also known as tool calling)"; "Tool" ist das weiter gefasste Wort, weil Modelle zusätzlich eingebaute Tools wie Websuche erhalten. Ich verwende beide Begriffe.

Python 3.10 oder neuer (der Code nutzt str | None Type Hints) und drei Pakete:

pip install openai anthropic requests Enter fullscreen mode Exit fullscreen mode Setze IPGEO_API_KEY sowie OPENAI_API_KEY oder ANTHROPIC_API_KEY für das jeweils aufgerufene Modell.

Hinter dieser Funktion passt jeder IP-Datenanbieter. IPinfo, IPGeolocation, MaxMind GeoIP2, ip-api und IPLocate liefern alle ähnliche Standortfelder zurück. Ich verwende ipgeolocation.io, weil die 1.000 täglichen Credits des kostenlosen Tarifs Standort, ASN und Zeitzone in einem Aufruf abdecken und der fields-Parameter dem Tool erlaubt, nur die benötigten Pfade anzufordern; die Dokumentation der IP Geolocation API listet jeden Pfad auf. Ein späterer Anbieterwechsel bedeutet, einen HTTP-Aufruf und eine Mapping-Funktion zu ändern.

Alles in diesem Abschnitt und den nächsten dreien liegt in einer Datei, ip_tool.py. Die Blöcke sind in Dateireihenfolge.

"""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 } Enter fullscreen mode Exit fullscreen mode strict: True mit additionalProperties: False bedeutet, dass beide Anbieter garantieren, dass die Argumente dem Schema entsprechen; man parst also nie {"ipaddress":...} oder ein fehlendes Feld. Garantiert wird damit nicht, dass der String eine gültige IP ist.

Das ist die Aufgabe des nächsten Abschnitts.

Lies die Beschreibung als Vertrag mit dem Modell. Sie sagt, was zurückkommt, was diese Daten nicht sind, wann nicht aufgerufen werden darf und was mit einem Fehler zu tun ist. Jeder Satz steht dort, weil ohne ihn etwas schiefgeht.

Der mittlere Satz wiegt am meisten. Ohne ihn hält nichts ein Modell davon ab, jemandem zu sagen "du bist in Mountain View". Für 8.8.8.8 ist das besonders falsch: Es ist Googles Anycast-DNS-Adresse, die von vielen Orten aus ausgeliefert wird, und der Lookup liefert den Ort, an dem das Netzwerk registriert ist. IP-Standorte beschreiben Netzwerke. Sag das im Tool, nicht in einem Disclaimer, den das Modell nie liest.

Der Fehler-Satz ist wichtig, weil ein Modell, das eine nackte Fehlermeldung sieht, es einfach erneut versuchen kann. Bei einer kostenpflichtigen API ist jeder Retry ein Credit.

Ein verbreitetes Design unterteilt dies in separate Tools für Standort, ASN, Reputation und "was ist meine IP". Ich würde mit einem beginnen. Das Schema jedes Tools reist bei jeder Anfrage mit, und jedes zusätzliche Tool ist eine weitere falsche Wahl, die das Modell treffen kann. OpenAis Best Practices sagen dasselbe in eigenen Worten: Halte das anfängliche Set an Funktionen klein und kombiniere Funktionen, die immer hintereinander aufgerufen werden.

Teile, wenn sich Berechtigungen unterscheiden. Wenn nur Admins VPN- und Bedrohungsdaten sehen sollen, ist das ein zweites Tool, das man für Admin-Sitzungen registriert und sonst nie mitsendet.

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 ) Enter fullscreen mode Exit fullscreen mode ipaddress behandelt IPv4 und IPv6, normalisiert die Formatierung, und is_global lehnt RFC-1918-Bereiche, Loopback, Link-Local, den CGNAT-Block 100.64.0.0/10 und die Dokumentationsbereiche ab. Eine Überraschung beim Testen: ipaddress.ip_address("224.0.0.1").is_global ist True. Eine Multicast-Gruppe lässt sich nicht geolokalisieren, also bekommt sie eine eigene Prüfung.

Die API würde diese ohnehin ablehnen (eine private Adresse kommt als HTTP 423 mit '10.0.0.1' is a bogon IP address zurück), aber sie lokal abzufangen erspart einen Netzwerk-Roundtrip und gibt dem Modell in Mikrosekunden eine klare Antwort.

Die vollständige Antwort des kostenlosen Tarifs für 8.8.8.8, mit allen Feldern:

{ "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 } } } Enter fullscreen mode Exit fullscreen mode Bezahlte Tarife liefern zusätzlich network-, company- und weitere asn-Felder. Nützliche Daten für eine Log-Pipeline. Für einen Agenten, der "wo ist diese IP?" beantwortet, ist das meiste davon Rauschen: eine Flaggen-URL, vier Sprachcodes, ein Währungssymbol und zwei DST-Übergangsobjekte.

Als kompaktes JSON sind das 576 Tokens (Tokenizer o200k_base), und Tool-Ergebnisse bleiben in der Konversation, werden also mit jeder späteren Anfrage erneut mitgesendet.

IPGEO_URL = "https://api.ipgeolocation.io/v3/ipgeo" # Nur diese Pfade bei der API anfordern. `fields` funktioniert auch im kostenlosen Tarif. 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: # Die API liefert Koordinaten als Strings zurück, z. B.

"37.42240". try: return float ( value ) except ( TypeError, ValueError ): return None def _shape ( data: dict ) -> dict: """Mappt die Antwort des Anbieters auf unser eigenes kleines, stabiles 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" ), } Vollbildmodus öffnen Vollbildmodus beenden Hier passieren zwei Dinge. fields sorgt dafür, dass die API nur neun Pfade zurückschickt (plus ip, das immer mitkommt), sodass weniger über die Leitung geht. _shape bildet anschließend die Namen des Anbieters auf Ihre eigenen ab: Das Modell sieht region, nicht state_prov, und wenn Sie nächsten Jahr den Anbieter wechseln, ändert sich die Struktur, die das Modell gelesen hat, nicht. Was das Modell erhält:

{ "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" } Vollbildmodus öffnen Vollbildmodus beenden 84 Tokens. Dieselbe Antwort, etwa ein Siebtel des Kontexts.

ipgeolocation.io nimmt den Schlüssel als apiKey-Query-Parameter entgegen. Das tun viele REST-APIs. Es verträgt sich schlecht mit der Art, wie Agenten Fehler melden. Das hier legt requests in eine Exception, wenn der Aufruf ein 401 zurückgibt:

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 Vollbildmodus öffnen Vollbildmodus beenden Verbindungsfehler verhalten sich genauso: Ein DNS-Fehler gibt Max retries exceeded with url: /v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8 aus. Stellen Sie sich nun ein verbreitetes Agent-Muster vor, return f"Sorry, I encountered an error: {str(e)}", das das Tool-Ergebnis weiterreicht. Ihr Schlüssel landet im Kontext des Modells, in Ihren Konversationsprotokollen und ist nur ein "Was ist schiefgelaufen?" vom Bildschirm des Nutzers entfernt.

# Nur feste Meldungen. Exception-Text niemals weiterreichen: requests legt # die vollständige Request-URL hinein, und diese URL enthält 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 # Sekunden _cache: dict [ str, tuple [ float, dict ] ] = { } def tool_error ( code: str, message: str, retryable: bool ) -> dict: return { "error": code, "message": message, "retryable": retryable } Vollbildmodus öffnen Vollbildmodus beenden Der Fix ist absichtlich unspektakulär: Statuscodes auf selbstgeschriebene Meldungen mappen, ein retryable-Flag hinzufügen, damit das Modell weiß, ob ein erneuter Versuch sinnvoll ist, und Exception-Typen protokollieren, niemals Exception-Strings. Anthrowics Anleitung zur Behandlung von Tool-Aufrufen empfiehlt Fehlermeldungen, die sagen, was schiefgelaufen ist und was man als Nächstes versuchen sollte. Diese tun genau das, ohne etwas von upstream zurückzuwerfen.

Die Absicherung liegt außerhalb des Codes. Sperren Sie den Schlüssel auf die IPs Ihrer Server: IP-Whitelisting ist in jedem Tarif verfügbar, auch im kostenlosen, und eine Anfrage mit diesem Schlüssel von überall sonst erhält ein 403. Ein geleakter Schlüssel, der nur von Ihrem NAT-Gateway aus funktioniert, ist ein viel kleineres Problem.

Die Funktion, die das Modell tatsächlich aufruft, ist der längste Block dieses Beitrags, weil sich alle Entscheidungen von oben in ihr treffen.

def lookup_ip ( ip: str ) -> dict: """Führt das Tool aus. Gibt immer ein dict zurück; wirft niemals in die Agent-Schleife.""" clean = _public_ip ( ip ) if clean is None: # Höchstens 45 Zeichen (die längste IPv6-Textform) an das Modell zurückgeben. 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: # Den Typ protokollieren, nicht str(exc): die Meldung enthält URL und Schlüssel. 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: # grobe Obergrenze; Redis verwenden, wenn mehrere Worker laufen _cache. clear ( ) _cache [ clean ] = ( time. monotonic ( ), result ) return result Vollbildmodus öffnen Vollbildmodus beenden Der Vertrag steht im Docstring: Sie gibt immer ein dict zurück und wirft niemals. Eine Exception, die aus einem Tool entweicht, bringt den gesamten Agent-Durchgang zum Absturz, und der Nutzer erhält einen Stacktrace statt "diese Adresse ist privat". Das macht das Tool für die Konversation fail-open: Wenn die IP-API down ist, sagt der Agent, dass er die Adresse nicht nachschlagen konnte, und macht weiter, statt die gesamte Anfrage scheitern zu lassen.

import json import os import openai from openai import OpenAI from ip_tool import OPENAI_TOOL, lookup_ip, tool_error MAX_ROUNDS = 4 # jede Runde kann ein Credit kosten; ein verwirrtes Modell kann Schleifen bilden 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 ) # liest OPENAI_API_KEY; Standard-Read-Timeout ist 600s model = os. environ. get ( "OPENAI_MODEL", "gpt-6.2-astra" ) # Namen ändern sich; Dokumentation prüfen 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 # Alles zurückschicken, was das Modell produziert hat (einschließlich reasoning items), # dann ein function_call_output pro Aufruf.

Das Modell kann parallel aufrufen. 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?" ) ) Vollbildmodus öffnen Vollbildmodus beenden items += response.output spiegelt das Openai-Beispiel für Function Calling in der Dokumentation wider und behält alle reasoning items im Verlauf neben den Aufrufen, die sie erzeugt haben. Jeder function_call erhält ein function_call_output mit der passenden call_id. "Vergleiche 8.8.8.8 und 1.1.1.1" kann zwei Aufrufe in einem Zug erzeugen, deshalb behandelt die Schleife alle davon, nicht nur den ersten.

Selbst mit aktiviertem Strict Mode sichert run_tool weiterhin gegen unbekannte Tool-Namen und fehlerhaftes JSON ab; das kostet vier Zeilen.

MAX_ROUNDS ist eine billige Versicherung. Ein Modell, das in einer Schleife eine fehlschlagende Abfrage wiederholt, verbraucht in jeder Runde ein Credit, und vier Runden reichen für jede vernünftige Frage zu IPs aus.

Claudes Tool-Nutzung unterscheidet sich an drei Stellen: Der Schema-Schlüssel lautet input_schema, Ergebnisse gehen als tool_result-Blöcke innerhalb eines User-Zugs zurück, und Fehler tragen is_error: true.

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?" ) ) Vollbildmodus öffnen Vollbildmodus verlassen Die Datei ip_tool.py musste überhaupt nicht verändert werden.

Das ist der Lohn dafür, das Tool anbieterneutral zu halten: Die Adapter sind nur Briefumschläge, und die Logik, die du getestet hast, liegt an genau einem Ort. Die Dokumentation von Anthropic weist darauf hin, dass Claude ein Tool nach einem Fehler erneut aufrufen kann, weshalb sich auch hier die Begrenzung der Runden bewährt.

Agenten fragen mehrfach nach. Eine Nachfrage zu derselben Adresse kann einen zweiten identischen Aufruf auslösen, und ein paralleler Durchlauf kann dieselbe IP zweimal anfordern. Der dict-Cache innerhalb von lookup_ip basiert auf der normalisierten Adresse, sodass " 8.8.8.8 " und 8.8.8.8 sich einen Eintrag teilen und ein Treffer nichts kostet. Fünf Minuten entsprechen dem Standardwert, den der offizielle ipgeolocation.io-MCP-Server für Lookup-Ergebnisse verwendet. Das gilt allerdings pro Prozess. Sobald du mehr als einen Worker betreibst, solltest du den Cache mit derselben TTL nach Redis verschieben.

ASN-Organisationsnamen, Hostnamen und WHOIS-Einträge werden von whoever geschrieben, der das Netzwerk registriert hat. Fast alle davon sind langweilig ( Google LLC ). Sie müssen es aber nicht sein, und du hast keine Kontrolle darüber.

Halte die Tool-Ausgabe innerhalb des Tool-Ergebnisses, niemals im System-Prompt, und leite sie nicht ohne Prüfung direkt in einen weiteren Tool-Aufruf weiter. Anthropics Anleitung zur Tool-Verarbeitung sagt es klar: "Keep untrusted content inside tool_result blocks rather than system prompts or plain user text blocks." Das ist ein weiterer Grund, warum _shape zehn benannte Felder zurückgibt statt der rohen Antwort. Das Modell sieht Schlüssel, die du ausgewählt hast, und nicht das, was der Upstream-Dienst diese Woche gerade senden möchte.

IPinfo, IP2Location, ipstack und IPGeolocation bieten inzwischen alle MCP-Server an; der offizielle ipgeolocation.io-Server dokumentiert 16 Tools für Geolocation, Sicherheit, ASN, Zeitzonen, Abuse-Kontakte und mehr. Wenn dein Agent in Claude Desktop, Cursor, VS Code, Cline oder Codex CLI lebt, installiere ihn und überspringe alles oben Genannte:

{ "mcpServers": { "ipgeolocation": { "command": "npx", "args": [ "-y", "ipgeolocation-io-mcp@latest" ], "env": { "IPGEOLOCATION_API_KEY": "<YOUR_API_KEY>" } } } } Vollbildmodus öffnen Vollbildmodus verlassen Du erhältst Tools für Sicherheit, ASN, Abuse-Kontakt, Zeitzone und Bulk-Abfragen, ohne sie selbst zu schreiben, und der Server cached Ergebnisse bereits und liefert Hinweise zu Fehlern. Bewahre den echten Schlüssel in der privaten Konfiguration deines Clients auf, nicht in einer eingecheckten Datei.

Wenn du aus eigenem Code eine Modell-API aufrufst, prüfe die Authentifizierungsunterstützung des Konnektors. OpenAIs Responses API unterstützt ein headers-Feld in ihrer MCP-Tool-Konfiguration und kann somit den von https://mcp.ipgeolocation.io/mcp geforderten Header X-IPGeolocation-API-Key senden. Claudes MCP-Konnektor dokumentiert derzeit nur Bearer-Authentifizierung über authorization_token, ohne Option für eigene Header. Diesen Konnektor mit diesem gehosteten Server zu verbinden, erfordert also eine Authentifizierungsbrücke oder einen MCP-Client, den du selbst kontrollierst. Für einen einzelnen, eng umrissenen Lookup gibt dir eine Funktion weiterhin die direkte Kontrolle über Validierung, Caching und die Form der Antwort.

Meine Regel: ein eng begrenztes Tool im eigenen Agenten, dann schreibe die Funktion. Fünf Tools, oder dieselben Tools in mehreren Clients, dann nutze den Server.

Bezahlte Tarife können der Anfrage include=security hinzufügen und erhalten damit Felder für VPN, Proxy, Tor und Threat-Score, zum Preis von 2 zusätzlichen Credits pro Lookup. Ein kostenloser Schlüssel, der dieses Modul anfordert, erhält HTTP 401, was HTTP_ERRORS bereits in einen verständlichen Fehler umwandelt. Falls du es hinzufügst, mach es zu einem separaten Tool und registriere es nur für Sitzungen, die diese Daten sehen dürfen.

IPv6 erfordert keine Änderungen. 2001:4860:4860::8888 durchläuft dieselbe Validierung, Anfrage und Aufbereitung.

Die Anreicherung von 10.000 Logzeilen ist keine Aufgabe für einen Agenten. Nutze das Bulk-Endpunkt aus einem Skript heraus und hebe dir Tool-Aufrufe für Fragen auf, die ein Mensch tatsächlich gestellt hat.

Protokolliere den Tool-Namen, die normalisierte IP, den Fehlercode und die Latenz. Nicht die URL.

Bevor du auslieferst, gib jeder Unterhaltung zusätzlich zu MAX_ROUNDS ein Lookup-Budget und beobachte, welche Fehlercodes in der ersten Woche der Logs auftauchen. Eine Häufung von not_public-Fehlern bedeutet oft, dass Nutzer die Adresse ihres Routers einfügen, was ein Prompt-Problem ist und kein API-Problem.

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

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.

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 Enter fullscreen mode Exit fullscreen mode 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.

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 } Enter fullscreen mode Exit fullscreen mode 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.

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 ) Enter fullscreen mode Exit fullscreen mode 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 } } } Enter fullscreen mode Exit fullscreen mode 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" ), } Enter fullscreen mode Exit fullscreen mode 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" } Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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 } Enter fullscreen mode Exit fullscreen mode 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 ( "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 Enter fullscreen mode Exit fullscreen mode 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.

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?" ) ) Enter fullscreen mode Exit fullscreen mode 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.

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?" ) ) Enter fullscreen mode Exit fullscreen mode 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": "<YOUR_API_KEY>" } } } } Enter fullscreen mode Exit fullscreen mode You 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.

From 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, so it can send the X-IPGeolocation-API-Key header required by https://mcp.ipgeolocation.io/mcp. Claude's 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.

My rule: one narrow tool in your own agent, write the function. Five tools, or the same tools in several clients, use the server.

Paid 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.

IPv6 needs no changes. 2001:4860:4860::8888 goes through the same validation, request, and shape.

Enriching 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.

Log the tool name, the normalized IP, the error code, and the latency. Not the URL.

Before 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.

Originaltitel: Give Your AI Agent an IP Lookup Tool With Function CallingQuelle: dev.to (dev.to). Original öffnen