APILayer Blog – All About APIs: AI, ML, Finance, & More APIs

Build an AI Agent for Fraud Detection Using Python, Langchain, and IPstack

Fake accounts flood your signup forms every day. Attackers use VPNs to hide their real locations, disposable phone numbers to bypass verification, and synthetic identities that look legitimate on the surface. Traditional rule-based validation falls short because it can’t adapt to new fraud patterns fast enough. You end up either blocking real users or letting fake ones slip through.​

The solution is simpler than you think. Build an AI agent that combines IPstack’s location intelligence with Numverify’s phone verification to validate users and flag fraud risks in real-time. This approach analyzes IP geolocation data, detects proxy usage, validates phone numbers, and checks carrier information all at once.​

You’ll build a Python-based AI agent using LangChain that queries these APIs, processes the responses, and makes intelligent fraud risk decisions without complex ML models. The agent evaluates user data, cross-references location and phone information, and returns a clear fraud risk score.​

This guide is for developers building fintech apps, signup flows, KYC systems, or any security workflow that needs smart fraud detection. You’ll learn how to set up the agent, integrate both APIs, and deploy a working fraud detection system.

Key Takeaways

  • Use IPstack and Numverify APIs with LangChain to detect fake accounts and VPN abuse in real-time.​
  • Use IPstack for location intelligence, Numverify for phone validation, and LangChain for agent orchestration without needing ML expertise.​
  • The agent provides detailed reasoning for each fraud decision, which is critical for compliance and manual reviews.​
  • Test the complete system using the free API tiers from IPstack and Numverify, which offer 100 requests each per month.​
  • Identify advanced threats like location mismatches, VOIP numbers paired with VPNs, and other synthetic identity indicators.

The Tech Stack: IPStack, Numverify, and LangChain 

This tutorial combines three powerful tools: IPstack for location intelligence, Numverify for phone verification, and LangChain for agent orchestration. Each handles a specific part of the fraud detection workflow, and together they create a system that’s smarter than traditional rule-based validation.​

IPstack: Location Intelligence and Threat Detection

IP geolocation API

IPstack is a real-time IP geolocation API that provides accurate location data and security threat assessment for any IP address. It offers 100+ data points, 99.9% uptime, and global coverage with over 2 million unique locations in more than 200,000 cities around the world. It’s built specifically for fraud detection use cases where you need to verify user location and detect suspicious connection patterns.​

Key Features for Fraud Detection

  • VPN/Proxy Detection: Identifies when users hide their real location using VPNs, proxies (CGI, web), or Tor networks.​
  • Connection Type Analysis: Distinguishes between residential IPs and datacenter/hosting IPs commonly used by bots.​
  • Threat Level Assessment: Provides security scores for IPs based on known malicious activity and fraud patterns.​
  • Geolocation Accuracy: Returns country, region, city, and timezone data to cross-verify against user-provided information.​
  • Security Module: Delivers comprehensive threat intelligence including proxy types and risk indicators via the &security=1 parameter.​

Why It Matters?

Location mismatches (IP country ≠ claimed country) and VPN usage are among the top fraud indicators in fintech and e-commerce. IPStack catches these discrepancies instantly by comparing geolocation data with user-provided billing addresses or account information.​

Numverify: Phone Number Validation and Carrier Intelligence

Numverify is a phone number validation API that verifies phone formats, identifies carriers, and detects disposable phone services. The API supports international phone number validation for 232 countries with real-time carrier detection and cross-checking against the latest international numbering plan databases. You can identify any national and international phone numbers simply by passing them into the API’s request URL and receiving detailed validation results in JSON format. It’s essential for catching fraudsters who use temporary VOIP numbers to create throwaway accounts.​

Key Features for Fraud Detection

  • Format Validation: Confirms phone numbers are legitimate and properly formatted with correct country codes.​
  • Carrier Detection: Identifies the mobile carrier or service provider associated with the number.​
  • Line Type Identification: Distinguishes between mobile, landline, and VOIP/virtual numbers.​
  • Country Code Verification: Returns the country associated with the phone number for cross-checking against IP location.​
  • Disposable Number Detection: Flags temporary phone services commonly used for fraud or spam.​

Why It Matters?

VOIP numbers and disposable phones are red flags because fraudsters use them to bypass SMS verification and create multiple accounts without real phone numbers. Numverify catches these patterns by analyzing carrier data and line type information in real-time.​

LangChain: Intelligent Agent Orchestration

LangChain is a framework for building AI applications that can reason, make decisions, and use external tools autonomously. Instead of hardcoding rules, LangChain agents analyze data patterns and explain their reasoning. This approach adapts to new fraud techniques without requiring manual rule updates.​

Key Features for This Use Case

  • Tool Orchestration: Agent automatically decides when to call IPStack vs. Numverify based on available data.​
  • Chain-of-Thought Reasoning: Analyzes multiple data points together (VPN + foreign phone = high risk).​
  • Zero-Shot Learning: Works without training examples by just providing tool descriptions and letting the agent figure it out.​
  • Explainable Decisions: Returns reasoning for every fraud assessment, critical for compliance and dispute resolution.​
  • Easy Extensibility: Add new validation tools without rewriting logic because the agent learns to use them automatically.​

Why Does It Matter?

Traditional rule engines can’t adapt to new fraud patterns fast enough. LangChain agents consider context and combine signals intelligently, catching advanced fraud attempts that slip past rigid rules.

Prerequisites and Setup

What You Need 

  • Python 3.8+ installed
  • Basic understanding of APIs and Python
  • API keys from APILayer (IPstack + Numverify are both APILayer products)
  • OpenAI API key for the LangChain agent

Install Dependencies

				
					pip install --pre -U langchain-openai
				
			

Get Your API Keys

IPstack: Sign up at https://ipstack.com/signup/free and grab your free API key

Numverify: Sign up at https://numverify.com/ for your API key

OpenAI: Get your key from https://platform.openai.com/

Project Structure

				
					fraud-detection-agent/
├── .env
├── agent.py
├── tools.py
└── test.py
				
			

Step 1: Create API Tool Functions

We’re building the foundation here with two Python functions that hit IPStack and Numverify APIs and return clean, structured data. These functions are what the agent will actually call when it needs to verify an IP or phone number, so we’re keeping them simple and focused on one task each.​

Build the IPStack Tool (tools.py)

				
					import requests
import os
from dotenv import load_dotenv

load_dotenv()

def check_ip_location(ip_address):
    """
    Checks IP address for location, VPN/proxy, and connection type
    Returns: dict with location data and risk indicators
    """
    api_key = os.getenv('IPSTACK_API_KEY')
    url = f'http://api.ipstack.com/{ip_address}?access_key={api_key}&security=1'
    
    try:
        response = requests.get(url)
        data = response.json()
        
        return {
            'ip': ip_address,
            'country': data.get('country_name'),
            'region': data.get('region_name'),
            'city': data.get('city'),
            'is_proxy': data.get('security', {}).get('is_proxy', False),
            'is_vpn': data.get('security', {}).get('is_vpn', False),
            'threat_level': data.get('security', {}).get('threat_level', 'unknown'),
            'connection_type': data.get('connection_type')
        }
    except Exception as e:
        return {'error': str(e)}


				
			

Output

				
					{
  "ip": "134.201.250.155",
  "country": "United States",
  "region": "California",
  "city": "Los Angeles",
  "is_proxy": false,
  "is_vpn": false,
  "threat_level": "low",
  "connection_type": "cable/DSL"
}
				
			

Build the Numverify Tool

				
					def validate_phone_number(phone_number):
    """
    Validates phone number format, carrier, and line type
    Returns: dict with validation results
    """
    api_key = os.getenv('NUMVERIFY_API_KEY')
    url = f'http://apilayer.net/api/validate?access_key={api_key}&number={phone_number}'
    
    try:
        response = requests.get(url)
        data = response.json()
        
        return {
            'valid': data.get('valid'),
            'number': data.get('number'),
            'country_code': data.get('country_code'),
            'country_name': data.get('country_name'),
            'carrier': data.get('carrier'),
            'line_type': data.get('line_type')  # mobile, landline, voip
        }
    except Exception as e:
        return {'error': str(e)}
				
			

Output

				
					{
  "valid": true,
  "number": "14158586273",
  "country_code": "US",
  "country_name": "United States",
  "carrier": "AT&T Mobility",
  "line_type": "mobile"
}
				
			

Step 2: Wrap Tools for LangChain

Now we’re telling LangChain about our functions so the agent knows they exist and when to use them. The Tool wrapper is basically metadata that gives the agent a description of what each function does, and LangChain uses that to decide which tool to call during runtime.​

Create LangChain Tool Wrappers (agents.py)

				
					from langchain.tools import Tool
from tools import check_ip_location, validate_phone_number

# Wrap IPStack function as LangChain tool
ip_checker_tool = Tool(
    name="IP_Location_Checker",
    func=check_ip_location,
    description="Useful for checking IP address location, detecting VPNs/proxies, and identifying connection type. Input should be an IP address string."
)

# Wrap Numverify function as LangChain tool
phone_validator_tool = Tool(
    name="Phone_Number_Validator",
    func=validate_phone_number,
    description="Useful for validating phone numbers, checking carrier info, and identifying line type (mobile/VOIP). Input should be a phone number with country code."
)

tools = [ip_checker_tool, phone_validator_tool]
				
			

Why This Matters

  • LangChain’s Tool wrapper lets the agent understand when and how to use each function by exposing the function’s name, description, and expected arguments.​
  • The description field is critical because it tells the agent what each tool does and when it should be called.​
  • Agent autonomously decides which tools to call based on the user query by analyzing the tool descriptions and matching them to the task at hand.​

Step 3: Build the LangChain Agent

This is where we wire everything together by initializing the LLM, giving it our tools, and creating the agent that orchestrates everything. The agent will receive user data, figure out which APIs to call, analyze the responses, and make a fraud decision all autonomously.​

Initialize the Agent

				
					from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI

# Initialize LLM
llm = ChatOpenAI(
    temperature=0,  # Keep it deterministic for fraud detection
    model_name="gpt-5",
    openai_api_key=os.getenv('OPENAI_API_KEY')
)

# Create the agent
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,  # See agent's reasoning process
    max_iterations=3
)
				
			

Understanding Agent Types

  • ZERO_SHOT_REACT_DESCRIPTION: Agent reasons about which tools to use without examples by reading tool descriptions and deciding which ones match the task.​
  • Perfect for dynamic fraud detection where patterns vary because the agent adapts its reasoning based on the specific data it receives.​
  • Agent creates a “chain of thought” to analyze data by thinking through each step, explaining why it chose specific tools, and how the results connect to fraud risk.​

Create the Fraud Detection Function

				
					def detect_fraud(user_data):
    """
    Main fraud detection function
    Args:
        user_data: dict with 'ip_address', 'phone_number', 'claimed_country'
    Returns:
        Fraud risk assessment with reasoning
    """
    prompt = f"""
    Analyze this user signup data for fraud risk:
    
    IP Address: {user_data['ip_address']}
    Phone Number: {user_data['phone_number']}
    Claimed Country: {user_data['claimed_country']}
    
    Check the following:
    1. Use IP_Location_Checker to verify the IP address location, VPN/proxy status
    2. Use Phone_Number_Validator to verify the phone number and line type
    3. Compare results to identify inconsistencies:
       - Does IP country match phone country?
       - Is IP country different from claimed country?
       - Is the user behind a VPN/proxy?
       - Is the phone a VOIP/disposable line?
    
    Provide a fraud risk score (LOW, MEDIUM, HIGH) and explanation.
    """
    
    result = agent.run(prompt)
    return result
				
			

Step 4: Test the Agent with Real Examples

Time to see this thing work by running three test cases to prove the agent can spot legit users, catch obvious fraud, and flag edge cases like VOIP phones. Each test shows you exactly what the agent thinks and why, so you can see the reasoning process in action and understand how it combines signals from both APIs.

Test Case 1: Legitimate User

				
					# test.py
from agent import detect_fraud

# Normal signup from US user
user_1 = {
    'ip_address': '134.201.250.155',
    'phone_number': '14158586273',
    'claimed_country': 'United States'
}

print("=== Testing Legitimate User ===")
result_1 = detect_fraud(user_1)
print(result_1)
				
			

Output

				
					> Entering new AgentExecutor chain...
I need to check the IP location and validate the phone number.

Action: IP_Location_Checker
Action Input: 134.201.250.155

Observation: {'ip': '134.201.250.155', 'country': 'United States', 'is_proxy': False, 'is_vpn': False, 'threat_level': 'low'}

Action: Phone_Number_Validator
Action Input: 14158586273

Observation: {'valid': True, 'country_code': 'US', 'line_type': 'mobile'}

Thought: All data is consistent. IP and phone both from United States, no VPN detected, mobile line type is legitimate.

Final Answer: 
FRAUD RISK: LOW

Reasoning:
- IP location matches phone country (United States)
- No VPN/proxy detected
- Phone is valid mobile line (not VOIP)
- All data consistent with claimed country
- Recommend: APPROVE signup
				
			

Test Case 2: High-Risk User

				
					# VPN user with mismatched phone
user_2 = {
    'ip_address': '45.95.169.146',  # Known VPN IP
    'phone_number': '2348012345678',  # Nigeria phone
    'claimed_country': 'United Kingdom'
}

print("\n=== Testing High-Risk User ===")
result_2 = detect_fraud(user_2)
print(result_2)
				
			

Output

				
					> Entering new AgentExecutor chain...

Action: IP_Location_Checker
Action Input: 45.95.169.146

Observation: {'ip': '45.95.169.146', 'country': 'Netherlands', 'is_vpn': True, 'threat_level': 'high', 'connection_type': 'hosting'}

Action: Phone_Number_Validator
Action Input: 2348012345678

Observation: {'valid': True, 'country_code': 'NG', 'country_name': 'Nigeria', 'line_type': 'mobile'}

Thought: Multiple red flags detected - VPN usage, country mismatches.

Final Answer:
FRAUD RISK: HIGH

Reasoning:
- User is behind VPN (Netherlands IP but hosting connection)
- Phone country is Nigeria, not matching claimed UK location
- IP shows datacenter/hosting connection type (suspicious)
- High threat level detected on IP
- Recommend: FLAG for manual review or BLOCK
				
			

Real-World Use Cases 

Let’s talk about where you’d actually deploy this—these are real scenarios where devs need fraud detection that’s smarter than basic rules but simpler than full ML pipelines. Each use case shows how to integrate the agent into your existing flow and where it fits in your current architecture.

Fintech Onboarding

  • Scenario: Digital bank verifying new account signups to prevent synthetic identity fraud and bot attacks.​
  • Check if the user’s IP, phone, and provided address are consistent by comparing geolocation data from IPStack against phone country codes from Numverify.​
  • Flag accounts created from datacenter IPs (bots) because legitimate users connect from residential networks, not hosting providers.​
  • Detects synthetic identities using VOIP + VPN combinations since fraudsters pair disposable numbers with location masking to create fake accounts.​
  • Implementation: Run agent during KYC process before account approval, returning risk scores that your approval workflow can act on immediately.​

E-commerce Fraud Prevention

  • Scenario: Online store detecting fraudulent transactions before payment processing to reduce chargebacks and refund abuse.​
  • Validate shipping address against IP location to catch card testers who use stolen cards with mismatched billing and shipping information.​
  • Check if the phone number country matches the billing address because legitimate customers typically have phone numbers from their home country.​
  • Identify card testing attempts from VPN/proxy IPs since fraudsters test stolen card numbers through anonymous connections.​
  • Implementation: Pre-transaction fraud check before payment processing that blocks high-risk orders or triggers additional verification steps.​

SaaS Trial Abuse Prevention

  • Scenario: SaaS platform preventing free trial abuse from users creating multiple accounts to extend free access periods.
  • Detect users creating multiple accounts with VOIP numbers by flagging line types that indicate disposable or temporary phone services.​
  • Flag VPN users from known abuse networks using IPStack’s threat intelligence to identify connections from high-risk proxy services.​
  • Cross-check IP/phone against existing account database to find users attempting to circumvent trial limits with new identities.​
  • Implementation: Run during trial signup and combine with email verification to create a multi-layered validation system.​

Benefits Across Use Cases

  • Speed: Real-time validation during signup flow (under 3 seconds) keeps the user experience smooth while maintaining security.​
  • Explainability: Clear reasoning for every decision helps your support team understand why accounts were flagged and resolve disputes faster.​
  • Flexibility: Easy to adjust risk thresholds per business needs without rewriting code or retraining models.​
  • Scalability: API-based approach handles high volume because both IPStack and Numverify are built for enterprise-scale traffic.​

Conclusion

You’ve built a production-ready AI agent that detects fraud using location and phone intelligence with no ML training, no complex infrastructure, just smart API orchestration that works. The agent reasons through fraud patterns, explains its decisions, and handles edge cases that would break traditional rule engines. This approach combines IPStack’s geolocation data with Numverify’s phone validation to create a system that adapts to new fraud techniques without manual updates.

Start with APILayer’s free tiers for IPStack and Numverify, run the test cases against your staging environment, and integrate into your signup flow using the code examples provided. Whether you’re building fintech apps, e-commerce platforms, or SaaS products, this AI agent provides an intelligent, scalable fraud detection layer that grows with your business. APILayer provides a wide variety of APIs beyond fraud detection, including Marketstack API for financial market data, Fixer API for currency exchange rates, Weatherstack for weather forecasts, Aviationstack for flight tracking, and many more.

Start protecting your platform from fraud right now by grabbing your free APILayer keys and deploying your first AI agent today.

FAQs

Do IPstack and Numverify offer free tiers for testing?

Yes, both IPStack and Numverify provide free tiers with 100 monthly API requests at no cost and no credit card required, allowing you to test the fraud detection agent before scaling to paid plans.​

Can this agent handle high traffic volumes for production applications?

Yes, the API-based approach scales easily for high-volume production traffic, with IPStack offering 99.9% uptime SLA and both APIs built to handle enterprise-scale requests from companies like Amazon, Apple, and Uber.​

Do I need machine learning experience to build this LangChain agent?

No, LangChain agents use zero-shot learning and work without training examples by simply providing tool descriptions, so you don’t need ML expertise or model training to deploy fraud detection.​

How does the agent explain its fraud risk decisions?

The LangChain agent uses chain-of-thought reasoning to analyze data from both APIs and returns detailed explanations for every fraud assessment, showing which specific factors (like VPN detection or VOIP numbers) contributed to the risk score.​

What other APIs does APILayer offer beyond fraud detection?

APILayer provides a wide variety of APIs including Marketstack API for financial market data, Fixer API for currency exchange rates, Weatherstack for weather forecasts, Aviationstack for flight tracking, and many more tools for developers.

Recommended Resource : 

Stay Connected

Exit mobile version