← Back to InsightsRAG

Building an AI-Powered HS Code Classification & Landed Cost API for Pakistan Customs

· Islam Nabi · HS Code & Landed Cost Estimation

Technologies: Python, FastAPI, OpenAI, GPT-4o-mini, FAISS, RAG, PDF Extraction, Vector Search, E-Commerce APIs

Importing products into Pakistan involves much more than simply knowing a product's price. Businesses need to determine the correct HS Code, understand customs duties, calculate taxes, estimate shipping costs, and ultimately determine the final landed cost of the product.

The challenge is that Pakistan's customs tariff data exists in massive PDF documents containing thousands of tariff codes, nested categories, and complex taxation rules that are extremely difficult to search manually.

To solve this problem, I built an AI-powered HS Code Retrieval and Landed Cost Estimation Platform that combines Retrieval-Augmented Generation (RAG), vector search, and large language models to automate customs classification and import cost calculations.

The Problem

Determining the correct HS Code is a critical step in international trade. A single classification error can result in:

  • Incorrect customs duty calculations
  • Regulatory compliance issues
  • Financial losses due to inaccurate pricing
  • Delayed import clearances
  • Incorrect landed cost estimation

Traditional approaches require manually searching through thousands of pages of Pakistan's FBR Customs Tariff documents, which is slow, error-prone, and difficult to scale for e-commerce applications.

System Objectives

The system was designed with four primary objectives:

  • Automatically classify products into valid FBR HS Codes.
  • Provide highly accurate customs duty calculations.
  • Estimate complete landed costs for imported products.
  • Expose everything through a production-ready API for e-commerce integration.

Building the RAG Pipeline

The first challenge was converting Pakistan's tariff PDFs into a searchable knowledge base.

I implemented a table-aware PDF extraction pipeline capable of understanding complex document layouts and preserving tariff hierarchies.

The extraction engine automatically detects:

  • Chapters
  • Sections
  • Parent categories
  • Subheadings
  • Duty percentages
  • Explanatory notes

More than 7,500 HS Codes were extracted and indexed, with approximately 95% category coverage across the entire tariff database.

Hierarchical Category Enrichment

One of the biggest improvements in classification accuracy came from attaching parent categories and section headings to every HS Code entry.

Instead of retrieving isolated tariff rows, the system understands the complete hierarchy:

  • Section
  • Chapter
  • Category
  • Subheading
  • Final HS Code

This additional context significantly improves retrieval quality and helps the language model make better classification decisions.

Semantic Search Using FAISS

After extraction, all entries are embedded and stored in a FAISS vector database.

The retrieval engine combines:

  • Dense vector similarity search
  • Keyword matching
  • Chapter boosting
  • Category alignment
  • Metadata filtering
  • Confidence scoring

This hybrid retrieval strategy dramatically improved precision when classifying ambiguous product descriptions.

AI-Powered Classification Engine

Retrieval alone is not enough for customs compliance.

I implemented an eight-stage classification pipeline inspired by Pakistan FBR's official classification methodology:

  1. Product name extraction
  2. Attribute extraction
  3. Canonical text generation
  4. Vector retrieval
  5. Chapter boosting
  6. Multi-factor ranking
  7. LLM-based final selection
  8. Safety rule validation

The system extracts structured attributes such as:

  • Material composition
  • Product form
  • Manufacturing process
  • Intended use

Finally, GPT-4o-mini analyzes the retrieved candidates and selects the most appropriate HS Code with confidence scoring and source transparency.

Near 99% Classification Accuracy

Combining structured retrieval, category enrichment, deterministic rules, and LLM reasoning resulted in classification accuracy approaching 99% on real-world product descriptions.

The system consistently produces reliable classifications while remaining fully auditable.

Pakistan Customs Duty Calculation Engine

After classification, the platform calculates complete customs duties according to Pakistan's compound taxation model, including:

  • Custom Duty (CD)
  • Additional Customs Duty (ACD)
  • Regulatory Duty (RD)
  • Sales Tax (ST)
  • Income Tax (IT)
  • GST
  • CESS

The calculation engine follows the exact sequential formulas used by Pakistan Customs, ensuring deterministic and transparent results.

Landed Cost Estimation

The system also performs:

  • AED to PKR currency conversion
  • TCS shipping calculations
  • Fuel surcharges
  • VAT calculations
  • Total landed cost estimation

This allows businesses and e-commerce platforms to instantly determine the true cost of importing a product into Pakistan.

Production Architecture

The platform was built using:

  • Python
  • FastAPI
  • FAISS
  • OpenAI Embeddings
  • GPT-4o-mini
  • PDFPlumber
  • Gunicorn
  • Uvicorn
  • Docker
  • AWS EC2

The API exposes endpoints for:

  • HS Code Retrieval
  • Landed Cost Estimation
  • Tax Rate Information
  • Statistics and Monitoring
  • Health Checks

Real-World Applications

The platform is designed for:

  • E-commerce marketplaces
  • Cross-border commerce platforms
  • Import and export businesses
  • Customs brokers
  • Pricing intelligence systems
  • Supply chain applications

Key Takeaways

This project demonstrates how Retrieval-Augmented Generation can be applied beyond chatbots and document search.

By combining AI, vector databases, domain-specific rules, and traditional software engineering, it is possible to build highly accurate systems that automate complex regulatory workflows.

The result is a production-grade platform capable of transforming thousands of pages of customs documentation into an intelligent API that can classify products, calculate duties, and estimate landed costs in real time.

Related Services

If you're building a similar RAG system or need a Generative AI Engineer to architect a retrieval pipeline over proprietary data, see my Generative AI Engineering and Agentic AI Development services.