Skip to content
ahang0712Public

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

🔍 AI Search - Intelligent Merchant Search System

Python Version License RAG System

An intelligent multi-agent merchant data generation and search system powered by LLM and RAG (Retrieval-Augmented Generation). Generate high-fidelity synthetic merchant data with privacy protection, and search through it using natural language queries.

🌟 Key Features

🤖 Multi-Agent Data Generation

  • 6 Specialized Agents: Collaborative workflow for data generation, privacy protection, and quality assurance
  • High-Fidelity Data: 15+ detailed merchant fields with realistic business distributions
  • Privacy Protection: Automated desensitization ensuring >97% differentiation from source data
  • Scalable Architecture: Generate 10,000+ merchant records with quality control
  • Intelligent Deduplication: Built-in quality checks and duplicate detection

🔎 Advanced Search Capabilities

  • Natural Language Queries: Search merchants using conversational language
  • Semantic Understanding: Powered by RAG system with embedding models
  • Multi-Dimensional Filters: Location, category, price range, ratings, and more
  • Real-Time Results: Fast similarity search with FAISS/Milvus backends
  • Interactive Mode: Continuous conversation-style search interface

📊 Benchmark & Evaluation

  • AI Search Benchmark Evaluator: Comprehensive evaluation framework
  • Quality Metrics: Automated scoring for data enhancement and rewriting
  • High-Concurrency Processing: Multi-threaded evaluation with token statistics
  • Human-AI Consistency: Calculate agreement between human and LLM annotations

📋 Table of Contents

🏗️ Architecture

Multi-Agent System

┌─────────────────────────────────────────────────────────────┐
│                   Coordinator Agent                          │
│              (Orchestrates entire workflow)                  │
└────────────┬────────────────────────────────────────────────┘
             │
    ┌────────┴────────┬──────────┬──────────┬──────────┐
    │                 │          │          │          │
┌───▼────┐  ┌────────▼──┐  ┌────▼───┐  ┌──▼─────┐  ┌─▼──────┐
│Distrib.│  │Data Gen   │  │Privacy │  │Quality │  │  API   │
│Agent   │  │Agent      │  │Agent   │  │Agent   │  │ Agent  │
└────────┘  └───────────┘  └────────┘  └────────┘  └────────┘

Data Processing Pipeline

Real Data (30 samples)
         ↓
Distribution Analysis (LLM)
         ↓
Data Generation (1:1) ← Based on real patterns
         ↓
Privacy Desensitization (1:1) ← Protect sensitive info
         ↓
Quality Check (1:1) ← Ensure quality
         ↓
Final Dataset (10,000+ merchants)

RAG Search System

┌──────────────┐      ┌─────────────────┐      ┌──────────┐
│ User Query   │ ───► │  Qwen3/BGE-M3   │ ───► │  Vector  │
│ "火锅店推荐"  │      │  Embedding      │      │ Database │
└──────────────┘      └─────────────────┘      │ (FAISS/  │
                                                │ Milvus)  │
       ▲                                        └────┬─────┘
       │                                             │
       │              ┌─────────────────┐            │
       └──────────────┤  LLM Generator  │◄───────────┘
                      │  (GPT/Claude)   │
                      └─────────────────┘
                       Similarity Search
                       + Answer Generation

🚀 Installation

Prerequisites

  • Python 3.8 or higher
  • 4GB+ RAM (8GB+ recommended)
  • 2-3GB disk space for models

Basic Installation

# Clone the repository
git clone https://github.com/ahang0712/ai-search.git
cd ai-search

# Install dependencies
pip install -r requirements.txt

Download Embedding Models (Optional for Local Deployment)

# Download Qwen3-Embedding-0.6B model
# Place in ./rag/Qwen3-Embedding-0.6B/

# Or use API-based embeddings (OpenAI, etc.)

Configuration

# Copy configuration template
cp config/config.example.yaml config/config.yaml

# Edit configuration file
vim config/config.yaml

# Set environment variables
export OPENAI_API_KEY=your_key_here

⚡ Quick Start

1. Generate Merchant Data

# Generate 1000 merchants for Beijing
python mcp_data_generator_beijing.py

# Generate with custom parameters
python scripts/run_generation.py --count 1000 --city 北京 --output data/merchants.json

2. Build Search Index

# Build FAISS index
python rag/build_merchant_vector_db.py --input data/merchants.json

# Or build Milvus index
python build_merchant_rag_system.py --input data/merchants.json

3. Start Interactive Search

# Launch interactive search
python rag/interactive_merchant_search.py

# Or single query mode
python rag/interactive_merchant_search.py --query "黄浦区有哪些美容美发店?"

Example Search Session

🌟 欢迎使用商户智能搜索系统!
📍 数据库: ./merchant_final_fixed_milvus.db
💡 输入 'quit' 或 'exit' 退出程序
------------------------------------------------------------

🔍 请输入您的查询: 外滩附近评分高的餐厅

🔎 正在搜索...

============================================================
🔍 查询: 外滩附近评分高的餐厅
============================================================
💡 回答:
根据检索结果,推荐以下外滩附近的高评分餐厅:

1. 外滩源餐厅
   📍 地址: 黄浦区中山东一路外滩源
   ⭐ 评分: 4.8/5.0
   💰 人均: ¥280
   🕐 营业时间: 11:00-22:00

⏱️ 查询耗时: 0.083秒
📚 找到 3 个相关文档

🤖 Data Generation

Multi-Agent Workflow

The system uses 6 specialized agents working collaboratively:

  1. Coordinator Agent: Orchestrates the entire workflow
  2. Distribution Agent: Analyzes data distribution patterns
  3. Data Generation Agent: Creates realistic merchant data
  4. Privacy Agent: Desensitizes sensitive information
  5. Quality Agent: Validates data quality
  6. API Agent: Manages external API calls

Data Fields

Generated merchants include 15+ fields:

{
  "id": "unique_merchant_id",
  "name": "商家名称",
  "category": "餐饮美食/火锅",
  "location": {
    "city": "北京",
    "district": "朝阳区",
    "address": "三里屯路19号",
    "latitude": 39.9042,
    "longitude": 116.4074
  },
  "business_hours": "11:00-22:00",
  "price_range": "¥100-200",
  "rating": 4.5,
  "avg_price": 150,
  "products": ["特色菜品列表"],
  "group_deals": ["团购信息"],
  "contact": {
    "phone": "010-****1234",
    "wechat": "merchant_wechat"
  },
  "delivery_info": {
    "available": true,
    "fee": 5,
    "min_order": 30
  },
  "specialties": ["招牌特色"],
  "tags": ["环境优雅", "停车方便"]
}

Usage Examples

# Basic generation
python main.py

# Custom city and count
python mcp_data_generator_shanghai.py  # Shanghai
python mcp_data_generator_guangzhou.py  # Guangzhou

# Batch generation with quality control
python scripts/run_generation.py \
  --count 10000 \
  --batch_size 100 \
  --workflow-type high_quality \
  --formats json csv excel \
  --include-report

Privacy Protection

The system automatically desensitizes:

  • Merchant names (with creative variations)
  • Detailed addresses (keeping district-level info)
  • Phone numbers (masking middle digits)
  • Personal contact information

Differentiation Rate: >97% from source data

🔍 Search System

Natural Language Queries

The RAG-powered search system understands complex queries:

Search by Location

"黄浦区有哪些美容美发店?"
"外滩附近的餐厅"
"徐汇区的咖啡厅推荐"

Search by Category

"评分高的火锅店"
"日式料理推荐"
"24小时营业的便利店"

Search by Price

"人均消费100元左右的火锅店"
"便宜的快餐店"
"价格在50-200元的餐厅"

Composite Queries

"外滩附近评分4.5以上的高端餐厅"
"徐汇区100元以内的亲子友好餐厅"
"黄浦区提供外卖的网红咖啡店"

Search Backends

FAISS (Lightweight, Recommended)

from rag.faiss_rag_system import FAISSRAGSystem

rag = FAISSRAGSystem(
    index_path="./faiss_index",
    qwen_model_path="./Qwen3-Embedding-0.6B",
    index_type="flat"  # or "ivf", "hnsw"
)

result = rag.query("火锅店推荐", top_k=5)

Features:

  • ✅ No external dependencies
  • ✅ Lightweight deployment (2-3GB)
  • ✅ High-performance search
  • ✅ Local file storage

Milvus (Scalable)

from rag.milvus_rag_system import MilvusRAGSystem

rag = MilvusRAGSystem(
    uri="./merchant_milvus.db",
    collection_name="merchants"
)

result = rag.query("火锅店推荐", top_k=5)

Features:

  • ✅ Distributed support
  • ✅ Real-time updates
  • ✅ Advanced filtering
  • ⚠️ Requires database service

Index Type Comparison

Index Type Use Case Speed Accuracy Memory
Flat <10K docs Slow 100% Low
IVF 10K-1M docs Medium ~98% Medium
HNSW >100K docs Fast ~95% High

API Usage

# Interactive mode
python rag/interactive_merchant_search.py

# Single query
python rag/interactive_merchant_search.py \
  --query "黄浦区美发店" \
  --top_k 5

# Custom database
python rag/interactive_merchant_search.py \
  --db_path "./my_index.db" \
  --collection "my_collection"

📊 Evaluation Tools

AI Search Benchmark Evaluator

Comprehensive evaluation framework for assessing data quality:

1. Rewrite Quality Evaluation

Evaluates desensitization and rewriting quality:

python ai_search_benchmark_evaluator_2/eval_single_metric.py \
  --task rewrite \
  --enhanced_path "data/02_enhanced_data.json" \
  --desensitized_path "data/03_desensitized_data.json" \
  --num 1000

2. Supplement Quality Evaluation

Evaluates data enhancement quality:

python ai_search_benchmark_evaluator_2/eval_single_metric.py \
  --task supplement \
  --original_path "data/01_original_data.json" \
  --enhanced_path "data/02_enhanced_data.json" \
  --num 1000

3. Human-AI Consistency

Calculate agreement between human and AI annotations:

python ai_search_benchmark_evaluator_2/calculate_consistency.py \
  --llm_score "data/llm_scores.json" \
  --human_score "data/human_scores.json"

Evaluation Features

  • 🚀 High Concurrency: Multi-threaded processing with app_id distribution
  • 📊 Token Statistics: Detailed usage tracking and cost analysis
  • 💾 Real-time Saving: Batch intermediate saves to prevent data loss
  • 🔄 Smart Retry: Exponential backoff retry mechanism
  • 📈 Performance Monitoring: Real-time progress and metrics

Evaluation Parameters

# Basic evaluation
python eval_single_metric.py --task rewrite

# Custom concurrency
python eval_single_metric.py \
  --task rewrite \
  --batch_size 60 \
  --max_clients 15 \
  --rpm 30

# Different model
python eval_single_metric.py \
  --task supplement \
  --model_name "deepseek-v31-meituan"

⚙️ Configuration

Model Configuration

Edit config/config.yaml:

# LLM Settings
llm:
  provider: openai  # or anthropic, deepseek
  model: gpt-4
  temperature: 0.7
  max_tokens: 2000

# Embedding Settings
embedding:
  provider: local  # or openai
  model_path: ./Qwen3-Embedding-0.6B
  dimension: 1024

# RAG Settings
rag:
  chunk_size: 1000
  chunk_overlap: 200
  top_k: 5
  index_type: flat  # flat, ivf, hnsw

Environment Variables

# API Keys
export OPENAI_API_KEY=your_openai_key
export ANTHROPIC_API_KEY=your_anthropic_key

# Model Paths
export QWEN_MODEL_PATH=/path/to/Qwen3-Embedding-0.6B
export BGE_MODEL_PATH=/path/to/bge-m3

# Database
export MILVUS_URI=./merchant_milvus.db
export FAISS_INDEX_PATH=./faiss_index

📖 API Reference

FAISSRAGSystem

class FAISSRAGSystem:
    def __init__(
        self,
        index_path: str = "./faiss_index",
        qwen_model_path: str = "./Qwen3-Embedding-0.6B",
        dimension: int = None,
        chunk_size: int = 1000,
        chunk_overlap: int = 200,
        device: str = None,
        batch_size: int = 32,
        index_type: str = "flat"
    ):
        """Initialize FAISS RAG system"""
        
    def add_document(self, content: str, metadata: dict) -> bool:
        """Add single document"""
        
    def add_documents_batch(self, documents: List[dict]) -> bool:
        """Add multiple documents"""
        
    def search(self, query: str, top_k: int = 5) -> List[dict]:
        """Search similar documents"""
        
    def query(self, question: str, top_k: int = 5) -> dict:
        """Query with LLM-generated answer"""

MilvusRAGSystem

class MilvusRAGSystem:
    def __init__(
        self,
        uri: str = "./milvus.db",
        collection_name: str = "merchants",
        dimension: int = 1024
    ):
        """Initialize Milvus RAG system"""
        
    def insert(self, data: List[dict]) -> bool:
        """Insert documents"""
        
    def search(self, query: str, limit: int = 5) -> List[dict]:
        """Search documents"""
        
    def query(self, question: str, top_k: int = 5) -> dict:
        """Query with answer generation"""

📁 Project Structure

ai-search/
├── agents/                          # Multi-agent system
│   ├── coordinator_agent.py        # Workflow coordinator
│   ├── distribution_agent.py       # Distribution analysis
│   ├── data_generation_agent.py    # Data generation
│   ├── privacy_agent.py            # Privacy protection
│   └── api_agent.py                # API management
├── ai_search_benchmark_evaluator_2/ # Evaluation framework
│   ├── eval_single_metric.py       # Main evaluator
│   ├── calculate_consistency.py    # Consistency calculator
│   ├── prompt/                     # Evaluation prompts
│   └── config/                     # Evaluation configs
├── rag/                            # RAG search system
│   ├── faiss_rag_system.py        # FAISS backend
│   ├── milvus_rag_system.py       # Milvus backend
│   ├── qwen_embedding.py          # Qwen embeddings
│   ├── interactive_merchant_search.py  # Search interface
│   └── Qwen3-Embedding-0.6B/      # Local model
├── core/                          # Core utilities
├── config/                        # Configuration files
├── data/                          # Data directory
├── output/                        # Generated data
├── scripts/                       # Utility scripts
├── docs/                          # Documentation
├── main.py                        # Main entry point
├── requirements.txt               # Dependencies
└── README.md                      # This file

🎯 Use Cases

1. Synthetic Data Generation

  • Generate realistic test data for applications
  • Create diverse merchant datasets for ML training
  • Privacy-safe data sharing and testing

2. Intelligent Search

  • Build merchant discovery platforms
  • Natural language business search
  • Location-based recommendations

3. Data Augmentation

  • Enhance limited real-world data
  • Create balanced category distributions
  • Generate edge cases for testing

4. Quality Assessment

  • Evaluate LLM data generation quality
  • Compare human vs AI annotations
  • Benchmark search performance

📊 Performance Metrics

Data Generation

  • Generation Rate: 10,000+ merchants in batch mode
  • Quality Pass Rate: 100% (with validation)
  • Privacy Differentiation: >97%
  • LLM Efficiency: 0.4 calls per merchant

Search Performance

Dataset Size Index Type Search Time Memory
1K docs Flat ~10ms 100MB
10K docs IVF ~50ms 500MB
100K docs HNSW ~20ms 2GB

🛠️ Development

Running Tests

# Run all tests
pytest tests/

# Run specific test
pytest tests/test_agents.py -v

# Run with coverage
pytest --cov=agents tests/

Code Quality

# Format code
black .

# Lint
flake8 .

# Type checking
mypy agents/

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

📞 Contact & Support

🗺️ Roadmap

  • Multi-language support (English, Chinese, etc.)
  • Web UI for search interface
  • API service deployment
  • Distributed data generation
  • Advanced filtering and faceted search
  • Export to multiple formats (CSV, Excel, Parquet)
  • Integration with popular data platforms

Star ⭐ this repo if you find it helpful!

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors