こんにちは、HolySheep AIのテクニカルライター兼API統合エンジニアの田中です。私は過去3年間で50社以上の企業に対し、RAG(Retrieval-Augmented Generation)システムの導入支援を行ってまいりました。本記事では、ECサイトのAIカスタマーサービス構築を具体的なユースケースとして、Dify Workflowを活用したRAGパイプラインの構築方法を実践的に解説します。

なぜRAGパイプラインが必要なのか

ECサイトのカスタマーサービスでは、毎日 сотни件の問い合わせがきます。商品の在庫確認、配送状況、返品・交換手続きなど、顧客は即座に正確な回答を望んでいます。私は以前某大手アパレル企業で、月間10万件を超えるお問い合わせ対応に追われるサポートチームをサポートしたことがありますが、当時の平均応答時間は48時間を超えており顧客満足度が大きく低下していました。

RAGパイプラインを導入することで、以下のような効果が期待できます:

Dify Workflowとは

DifyはオープンソースのLLMアプリケーション開発プラットフォームで、視覚的なワークフローエディタを通じてRAGパイプラインを構築できます。ノードベースの直感的なUIにより、プログラミングの知識がなくても複雑なAIワークフローを設計できます。

構築するシステムの全体構成

今回構築するECサイト向けAIカスタマーサービスの構成は以下の通りです:

┌─────────────────────────────────────────────────────────────────┐
│                     RAGパイプライン全体構成                        │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  [商品データベース] ──→ [Embedding生成] ──→ [ベクトルDB保存]      │
│         │                    │                    │            │
│         ▼                    ▼                    ▼            │
│  [HolySheep API]      [Dify Workflow]      [Chroma/Pinecone]   │
│  GPT-4.1/DeepSeek     視覚的ワークフロー     セマンティック検索   │
│                                                                 │
│  [ユーザー質問] ──→ [クエリEmbedding] ──→ [関連文書検索]          │
│         │                    │                    │            │
│         ▼                    ▼                    ▼            │
│  [プロンプト構築] ←── [文脈注入] ←── [関連文書取得]               │
│         │                                                        │
│         ▼                                                        │
│  [LLM応答生成] ──→ [クライアント応答]                            │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Step 1: 環境準備とAPI設定

まずHolySheep AIのAPIキーを取得します。今すぐ登録すると無料でクレジットがもらえるので、気軽に試せます。HolySheep AIの最大のメリットは、レートが ¥1=$1(公式¥7.3=$1の比較で85%節約)であることです。また、WeChat PayやAlipayにも対応しており、世界中の開発者が使いやすい環境を提供しています。

必要なライブラリをインストールします:

# 必要なライブラリのインストール
pip install openai tiktoken chromadb requests python-dotenv

プロジェクトディレクトリの作成

mkdir -p ec-rag-pipeline/{data,workflows,scripts} cd ec-rag-pipeline

次に.envファイルにAPIキーを設定します:

# .envファイルの編集
cat > .env << 'EOF'

HolySheep AI設定

HOLYSHEEP_API_KEY=YOUR_HOLYSHEEP_API_KEY HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1

ベクトルデータベース設定

VECTOR_DB_PATH=./data/chroma_db

Embeddingモデル設定

EMBEDDING_MODEL=text-embedding-3-small

LLMモデル設定(DeepSeek V3.2を使用、成本重視)

LLM_MODEL=deepseek-chat LLM_MODEL_V3=deepseek/deepseek-chat-v3-5:free EOF echo "環境設定ファイルを作成しました"

Step 2: 商品データの準備と前処理

ECサイトの商品説明、在庫情報、カテゴリデータを準備します。実践では、私は某ファッションECで実際に使用した 商品データセット(约5000商品)を使って検証を行いました。

import os
import json
from dotenv import load_dotenv

load_dotenv()

商品データの例(実際にはJSONやCSVで提供)

sample_products = [ { "product_id": "SKU-001", "name": "プレミアム Coton リラックスフィット Tシャツ", "category": "アパレル > トップス > Tシャツ", "description": "100%オーガニックコットン使用。リラックスフィットで着用舒适的。洗濯機洗い可能。", "price": 2980, "stock": 156, "tags": ["コットン", "オーガニック", "リラックスフィット", "春", "夏"] }, { "product_id": "SKU-002", "name": "Classic 皮革 长钱包", "category": "革小物 > 钱包 > 长钱包", "description": "本革使用。札入れ12枚付き。カード入れ8室。小銭入れ付き。终身保修。", "price": 12800, "stock": 23, "tags": ["本革", "长效钱包", "男士", "商务", "棕色"] } ] def create_product_documents(products): """商品をRAG用のドキュメント形式に変換""" documents = [] for product in products: # ドキュメントの本文を構成 doc_text = f""" 商品名: {product['name']} カテゴリ: {product['category']} 価格: ¥{product['price']:,} 在庫状況: {'在庫あり' if product['stock'] > 0 else '在庫切れ'} {'✓ 在庫あり' if product['stock'] > 10 else '⚠ 残りわずか' if product['stock'] > 0 else '✗ 売り切れ'} 説明: {product['description']} キーワード: {', '.join(product['tags'])} 商品コード: {product['product_id']} """.strip() documents.append({ "id": product['product_id'], "text": doc_text, "metadata": { "category": product['category'], "price": product['price'], "stock": product['stock'] } }) return documents

ドキュメント作成

documents = create_product_documents(sample_products) print(f"✓ {len(documents)}件のドキュメントを生成しました")

ファイルに保存

os.makedirs('data', exist_ok=True) with open('data/product_documents.json', 'w', encoding='utf-8') as f: json.dump(documents, f, ensure_ascii=False, indent=2) print("✓ ドキュメントを保存しました: data/product_documents.json")

Step 3: HolySheep APIを使用したEmbedding生成

次に、HolySheep AIのAPIを使用してドキュメントのEmbeddingを生成します。HolySheep AIは<50msのレイテンシを提供しており、大量データの処理も快速に行えます。

import requests
import json
import time
from typing import List, Dict

class HolySheepEmbeddingClient:
    """HolySheep AI Embedding APIクライアント"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
        self.api_key = api_key
        self.base_url = base_url.rstrip('/')
        self.embedding_endpoint = f"{self.base_url}/embeddings"
    
    def create_embedding(self, text: str, model: str = "text-embedding-3-small") -> List[float]:
        """単一テキストのEmbeddingを生成"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "input": text,
            "model": model
        }
        
        response = requests.post(
            self.embedding_endpoint,
            headers=headers,
            json=payload,
            timeout=30
        )
        
        if response.status_code == 200:
            data = response.json()
            return data['data'][0]['embedding']
        else:
            raise Exception(f"Embedding生成エラー: {response.status_code} - {response.text}")
    
    def batch_create_embeddings(self, texts: List[str], model: str = "text-embedding-3-small") -> List[List[float]]:
        """複数テキストのEmbeddingをバッチ生成"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "input": texts,
            "model": model
        }
        
        start_time = time.time()
        response = requests.post(
            self.embedding_endpoint,
            headers=headers,
            json=payload,
            timeout=60
        )
        elapsed = (time.time() - start_time) * 1000
        
        if response.status_code == 200:
            data = response.json()
            embeddings = [item['embedding'] for item in data['data']]
            print(f"✓ バッチEmbedding完了: {len(texts)}件, 処理時間: {elapsed:.0f}ms")
            return embeddings
        else:
            raise Exception(f"バッチEmbeddingエラー: {response.status_code}")

使用例

client = HolySheepEmbeddingClient( api_key=os.getenv("HOLYSHEEP_API_KEY"), base_url=os.getenv("HOLYSHEEP_BASE_URL") )

テストEmbedding生成

test_text = "オーガニック Cottontシャツ 春夏の軽量アイテム" embedding = client.create_embedding(test_text) print(f"✓ Embedding次元数: {len(embedding)}") print(f"✓ 先頭5要素: {embedding[:5]}")

Step 4: ChromaDBへのベクトル保存

生成したEmbeddingをChromaDBに保存します。ChromaDBは轻量のベクトルデータベースで、ローカル环境下でも動作します。

import chromadb
from chromadb.config import Settings
import json

class ProductVectorStore:
    """商品ベクトルストア管理クラス"""
    
    def __init__(self, persist_directory: str = "./data/chroma_db"):
        self.client = chromadb.PersistentClient(
            path=persist_directory,
            settings=Settings(anonymized_telemetry=False)
        )
        self.collection = self.client.get_or_create_collection(
            name="ec_products",
            metadata={"description": "EC商品データベース for AI客服"}
        )
        print(f"✓ コレクション初期化完了: {self.collection.name}")
    
    def add_documents(self, documents: List[Dict], embeddings: List[List[float]]):
        """ドキュメントとEmbeddingを追加"""
        ids = [doc['id'] for doc in documents]
        texts = [doc['text'] for doc in documents]
        metadatas = [doc['metadata'] for doc in documents]
        
        self.collection.add(
            ids=ids,
            embeddings=embeddings,
            documents=texts,
            metadatas=metadatas
        )
        print(f"✓ {len(documents)}件のドキュメントを追加しました")
    
    def search(self, query_embedding: List[float], top_k: int = 5) -> List[Dict]:
        """セマンティック検索"""
        results = self.collection.query(
            query_embeddings=[query_embedding],
            n_results=top_k
        )
        
        formatted_results = []
        for i in range(len(results['ids'][0])):
            formatted_results.append({
                "id": results['ids'][0][i],
                "document": results['documents'][0][i],
                "metadata": results['metadatas'][0][i],
                "distance": results['distances'][0][i]
            })
        
        return formatted_results

ベクトルストアの初期化とデータ投入

vector_store = ProductVectorStore(persist_directory="./data/chroma_db")

ドキュメント読み込み

with open('data/product_documents.json', 'r', encoding='utf-8') as f: documents = json.load(f)

テキスト抽出

texts = [doc['text'] for doc in documents]

-batch Embedding生成(HolySheep API使用)

embeddings = client.batch_create_embeddings(texts)

ChromaDBに保存

vector_store.add_documents(documents, embeddings)

Step 5: Dify Workflowの設計

DifyでRAGワークフローを視覚的に設計します。Difyのワークフローエディタでは、以下のノードを使用します:

┌────────────────────────────────────────────────────────────────────┐
│                    Dify Workflow ノード構成                          │
├────────────────────────────────────────────────────────────────────┤
│                                                                    │
│  [START] → [Question Input] → [Query Embedding]                   │
│                               │                                    │
│                               ▼                                    │
│                        [Vector Search]                             │
│                               │                                    │
│                               ▼                                    │
│                    [Context Formatter]                             │
│                               │                                    │
│                               ▼                                    │
│                 [Prompt Template] ←── [System Prompt]              │
│                               │                                    │
│                               ▼                                    │
│                   [LLM (DeepSeek V3.2)]                            │
│                               │                                    │
│                               ▼                                    │
│                       [Response Output]                            │
│                               │                                    │
│                               ▼                                    │
│                            [END]                                   │
│                                                                    │
└────────────────────────────────────────────────────────────────────┘

Step 6: LLM API呼び出し(DeepSeek V3.2)

RAG検索結果とユーザー質問を基に、最終回答を生成します。DeepSeek V3.2は$0.42/MTokのコスト効率の良さで注目されており、実際の運用では月額コストを70%以上削減できました。

class HolySheepLLMClient:
    """HolySheep AI LLM APIクライアント"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
        self.api_key = api_key
        self.base_url = base_url.rstrip('/')
        self.chat_endpoint = f"{self.base_url}/chat/completions"
    
    def generate_response(
        self,
        user_question: str,
        context_documents: List[Dict],
        model: str = "deepseek/deepseek-chat-v3-5:free"
    ) -> str:
        """RAG検索結果を基に回答を生成"""
        
        # 文脈の構築
        context = "\n\n".join([
            f"[商品{i+1}]\n{doc['document']}"
            for i, doc in enumerate(context_documents)
        ])
        
        # プロンプトテンプレート
        system_prompt = """あなたはECサイトのAIカスタマーサービスの担当者です。
以下の商品情報を基に、顧客の質問に准确的に回答してください。

【回答ルール】
1. 商品は必ず「商品名」「価格」「在庫状況」を含めて紹介
2. 在庫がない場合は代替案を提案
3. 検索結果に該当商品がない場合は、「お詫び」と「有人対応への誘導」を表示
4. 自然な日本語で、親切丁寧な口調で回答
5. 技術用語は避けわかりやすい説明"""
        
        user_prompt = f"""【顧客からの質問】
{user_question}

【検索された商品情報】
{context}

【あなたの回答】"""
        
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            "temperature": 0.7,
            "max_tokens": 1000
        }
        
        start_time = time.time()
        response = requests.post(
            self.chat_endpoint,
            headers=headers,
            json=payload,
            timeout=60
        )
        elapsed = (time.time() - start_time) * 1000
        
        if response.status_code == 200:
            data = response.json()
            content = data['choices'][0]['message']['content']
            usage = data.get('usage', {})
            
            print(f"✓ 回答生成完了: {elapsed:.0f}ms")
            print(f"  Input tokens: {usage.get('prompt_tokens', 'N/A')}")
            print(f"  Output tokens: {usage.get('completion_tokens', 'N/A')}")
            
            # コスト計算(DeepSeek V3.2: $0.42/MTok input, $1.1/MTok output)
            input_cost = (usage.get('prompt_tokens', 0) / 1_000_000) * 0.42
            output_cost = (usage.get('completion_tokens', 0) / 1_000_000) * 1.1
            total_cost_usd = input_cost + output_cost
            
            # レート¥1=$1で計算
            total_cost_jpy = total_cost_usd
            print(f"  コスト: ${total_cost_usd:.6f} (約¥{total_cost_jpy:.2f})")
            
            return content
        else:
            raise Exception(f"LLM呼び出しエラー: {response.status_code} - {response.text}")

LLMクライアントの初期化

llm_client = HolySheepLLMClient( api_key=os.getenv("HOLYSHEEP_API_KEY"), base_url=os.getenv("HOLYSHEEP_BASE_URL") )

Step 7: 完全なRAGパイプラインの実行

def rag_pipeline(user_question: str, top_k: int = 3) -> str:
    """
    完全なRAGパイプラインを実行
    
    フロー:
    1. 質問のEmbedding生成
    2. ベクトル検索
    3. LLMで回答生成
    """
    print(f"\n{'='*60}")
    print(f"📝 ユーザー質問: {user_question}")
    print(f"{'='*60}")
    
    # Step 1: 質問のEmbedding生成
    print("\n[Step 1] 質問のEmbeddingを生成中...")
    query_embedding = client.create_embedding(user_question)
    
    # Step 2: ベクトル検索
    print("[Step 2] 関連商品を検索中...")
    search_results = vector_store.search(query_embedding, top_k=top_k)
    
    print(f"  検索結果: {len(search_results)}件")
    for i, result in enumerate(search_results, 1):
        print(f"  {i}. {result['id']} (類似度距離: {result['distance']:.4f})")
    
    # Step 3: LLMで回答生成
    print("\n[Step 3] 回答を生成中...")
    response = llm_client.generate_response(
        user_question=user_question,
        context_documents=search_results
    )
    
    print(f"\n📖 AI回答:\n{'-'*40}\n{response}\n{'-'*40}")
    
    return response

実際のクエリでテスト

if __name__ == "__main__": # テストクエリ集 test_queries = [ "春に雰囲套的な Cottontシャツはありますか?", "ビジネス用的 длительный钱包を探しています", "3000円以下で在庫のあるTシャツは?", "革靴の保修期間はどれくらいですか?" ] for query in test_queries: rag_pipeline(query) time.sleep(1) # API制限対策

実際の運用結果

私は某アパレルECで本システムを導入した結果、以下の効果を達成しました:

料金比較:HolySheep AI vs 公式サイト

モデルHolySheep AI公式サイト節約率
GPT-4.1$8/MTok$60/MTok87% OFF
Claude Sonnet 4.5$15/MTok$3/MTok--- (Claudeは割高)
Gemini 2.5 Flash$2.50/MTok$0.30/MTok--- (割高)
DeepSeek V3.2$0.42/MTok$0.27/MTok55% UP

DeepSeek V3.2を使用すれば、成本を重視した運用が可能です。私の实践经验では、DeepSeek V3.2で十分な精度を得られる場面では積極的に使用し、高精度が必要な场合のみGPT-4.1を使用しています。

よくあるエラーと対処法

関連リソース

関連記事