AIアプリケーション開発において、単一のプロンプトで全てを処理することは困難です。本稿では、HolySheep AIを活用した多段Prompt Pipelineの設計パターンと堅牢なエラー処理の実装方法を、私が実際に直面した課題と共に解説します。

なぜ多段Pipelineが必要なのか

私は以前たった1つの超级プロンプトで商品を推薦するシステムを作ったことがあります。しかし、プロンプトが複雑化するほど出力の品質が不安定になり、レイテンシも増加しました。多段Pipelineを導入することで、各責務を分離し、パイプライン全体の制御性と保守性が剧的に向上します。

典型的なユースケース:ECのAIカスタマーサービス

ECサイトのAIカスタマーサービスを例に説明します。客户からの問い合わせは以下のステップで處理されます:

基本アーキテクチャ:Pipeline制御クラス

まず、Pipeline全体を管理する基盤クラスを作成します。私のプロジェクトではこのパターンを广泛应用しています:

"""
HolySheep AI 多段Prompt Pipeline
EC AIカスタマーサービスシステム
"""
import httpx
import json
import time
from typing import Any, Optional
from dataclasses import dataclass
from enum import Enum

class IntentType(Enum):
    COMPLAINT = "complaint"
    RETURN = "return"
    PRODUCT_INQUIRY = "product_inquiry"
    OTHER = "other"

@dataclass
class PipelineStep:
    name: str
    model: str
    system_prompt: str
    max_tokens: int = 1000
    temperature: float = 0.7

@dataclass
class PipelineResult:
    step_name: str
    input_data: Any
    output_data: Any
    latency_ms: float
    tokens_used: int
    success: bool
    error: Optional[str] = None

class HolySheepPipeline:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.client = httpx.Client(timeout=30.0)
        
    def _call_llm(self, step: PipelineStep, user_message: str) -> tuple[str, int, float]:
        """HolySheep API调用 - レイテンシ <50ms"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": step.model,
            "messages": [
                {"role": "system", "content": step.system_prompt},
                {"role": "user", "content": user_message}
            ],
            "max_tokens": step.max_tokens,
            "temperature": step.temperature
        }
        
        start = time.perf_counter()
        response = self.client.post(
            f"{self.base_url}/chat/completions",
            headers=headers,
            json=payload
        )
        latency = (time.perf_counter() - start) * 1000
        
        if response.status_code != 200:
            raise Exception(f"API Error: {response.status_code} - {response.text}")
        
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        tokens = result.get("usage", {}).get("total_tokens", 0)
        
        return content, tokens, latency

利用例

pipeline = HolySheepPipeline(api_key="YOUR_HOLYSHEEP_API_KEY")

ステップ1:意図分類の実装

初段では、客户の問い合わせ意図を分類します。HolySheep AIのDeepSeek V3.2モデルは$$0.42/MTokと低コストながら十分な精度を提供します:

"""
Intent Classification Step - Step 1
"""
import json

ステップ1:意図分類の定義

INTENT_CLASSIFICATION_STEP = PipelineStep( name="intent_classification", model="deepseek-v3.2", system_prompt="""あなたはECサイトの問い合わせを分類する специалист です。 以下のいずれかの意図に分類してください: - complaint: 商品やサービスへの怨念や不满 - return: 退货·交換の依頼 - product_inquiry: 商品詳細·仕様·在庫の問い合わせ - other: 上記以外 出力は必ず以下のJSON形式のみで返してください: {"intent": "意图名", "confidence": 0.0-1.0, "reasoning": "简短な理由"}""", max_tokens=200, temperature=0.3 # 一貫性のため低温度 ) def classify_intent(pipeline: HolySheepPipeline, user_message: str) -> PipelineResult: """客户問い合わせの意図を分類""" try: output, tokens, latency = pipeline._call_llm( INTENT_CLASSIFICATION_STEP, user_message ) # JSON解析 classification = json.loads(output) intent = IntentType(classification["intent"]) print(f"分類結果: {intent.value} (信頼度: {classification['confidence']:.2%})") print(f"レイテンシ: {latency:.1f}ms | トークン: {tokens}") return PipelineResult( step_name="intent_classification", input_data=user_message, output_data={"intent": intent, **classification}, latency_ms=latency, tokens_used=tokens, success=True ) except json.JSONDecodeError as e: return PipelineResult( step_name="intent_classification", input_data=user_message, output_data=None, latency_ms=0, tokens_used=0, success=False, error=f"JSON解析エラー: {str(e)}" ) except Exception as e: return PipelineResult( step_name="intent_classification", input_data=user_message, output_data=None, latency_ms=0, tokens_used=0, success=False, error=str(e) )

利用テスト

test_message = "注文した靴的质量很差,鞋底才穿一周就开胶了,这怎么处理?" result = classify_intent(pipeline, test_message)

ステップ2:分類別回答生成

分類結果に応じて、異なるプロンプトで回答を生成します。各意図に最適化されたシステムプロンプトを使用します:

"""
Response Generation Step - Step 2
意図別の専用プロンプトテンプレート
"""
from typing import Dict

RESPONSE_PROMPTS: Dict[IntentType, str] = {
    IntentType.COMPLAINT: """あなたは優しいECサイトの客服担当です。
客户の怨念辛勤に耳を傾け、解决方案を提示してください。

対応ポリシー:
- 首先道歉,共感を示す
- 具体的な补偿方案を提示(退货/退款/替换品)
- 解決期限を約束
- 担当者名を明記

回复格式:
1. 道歉と共感
2. 原因の説明(推测)
3. 解决方案(2つ以上提示)
4. 今後の連絡先""",
    
    IntentType.RETURN: """你是EC商城退货专员。请根据以下政策处理退货请求:

退货政策:
- 商品到着后7日内可申请退货
- 商品需保持原包装、未经使用
- 运费:质量问题→当社負担 / 客人理由→客人負担
- 退款:收货确认后3工作日内处理

必须包含:
- 退货申请链接
- 需要准备的材料清单
- 预计退款日程""",
    
    IntentType.PRODUCT_INQUIRY: """あなたは商品の 전문 판매자입니다。
正確で優しい説明を提供してください。

回答原则:
- 明確で简潔な言葉を使用
- 数値や仕様は正確に記載
- 画像やリンクを適切に案内
- 在庫情况和発送予定日を明示"""
}

def generate_response(
    pipeline: HolySheepPipeline,
    intent: IntentType,
    original_message: str,
    context: Optional[Dict] = None
) -> PipelineResult:
    """分類に応じた回答を生成"""
    
    system_prompt = RESPONSE_PROMPTS.get(intent, RESPONSE_PROMPTS[IntentType.OTHER])
    
    # コンテキスト信息を结合
    user_content = original_message
    if context:
        user_content = f"""【客户情報】
- 注文番号: {context.get('order_id', 'N/A')}
- 購入日: {context.get('order_date', 'N/A')}
- 会员等级: {context.get('member_tier', '一般')}

【問い合わせ内容】
{original_message}"""
    
    step = PipelineStep(
        name="response_generation",
        model="deepseek-v3.2",  # コスト効率重视
        system_prompt=system_prompt,
        max_tokens=800,
        temperature=0.7
    )
    
    try:
        output, tokens, latency = pipeline._call_llm(step, user_content)
        
        return PipelineResult(
            step_name="response_generation",
            input_data={"intent": intent, "original": original_message},
            output_data={"response": output, "model": step.model},
            latency_ms=latency,
            tokens_used=tokens,
            success=True
        )
    except Exception as e:
        return PipelineResult(
            step_name="response_generation",
            input_data={"intent": intent},
            output_data=None,
            latency_ms=0,
            tokens_used=0,
            success=False,
            error=str(e)
        )

ステップ3:品質チェックと後処理

生成された回答を検証し、必要に応じて修正します。これにより、プロンプトの不安定さを補完できます:

"""
Quality Check Step - Step 3
回答の品質検証と格式化
"""
from typing import List

QUALITY_CHECK_STEP = PipelineStep(
    name="quality_check",
    model="gpt-4.1",  # 高品質检查用
    system_prompt="""あなたは回答品质审核员です。
提供されたAI回答を以下 기준으로チェックしてください:

チェック項目:
1. 不適切な表現や誤情報の有無
2. 回答の完全性(主要質問に全て回答しているか)
3. フォーマットの一貫性
4. ブランドトーン是否符合

を出力形式:
{
  "approved": true/false,
  "issues": ["问题点リスト"、または空リスト],
  "suggestions": ["改善提案"、または空リスト],
  "final_score": 1-10
}

approvedがfalseの場合のみ、修正案をsuggestionsに含めてください。""",
    max_tokens=500,
    temperature=0.2
)

def quality_check(
    pipeline: HolySheepPipeline,
    response: str,
    original_query: str
) -> PipelineResult:
    """回答の品質検証"""
    
    check_content = f"""【原始問い合わせ】
{original_query}

【生成回答】
{response}"""
    
    try:
        output, tokens, latency = pipeline._call_llm(
            QUALITY_CHECK_STEP, 
            check_content
        )
        
        result = json.loads(output)
        
        # スコアが6以下、またはapprovedがfalseの場合はフラグ
        needs_revision = not result["approved"] or result["final_score"] < 6
        
        return PipelineResult(
            step_name="quality_check",
            input_data=response,
            output_data=result,
            latency_ms=latency,
            tokens_used=tokens,
            success=True
        )
        
    except Exception as e:
        return PipelineResult(
            step_name="quality_check",
            input_data=response,
            output_data=None,
            latency_ms=0,
            tokens_used=0,
            success=False,
            error=f"品質チェック失敗: {str(e)}"
        )

Pipeline実行エンジン:完全な业务流程

最後に、すべてのステップを統合したPipeline実行クラスを実装します:

"""
Complete Pipeline Orchestrator
HolySheep AI - 完整客服Pipeline
"""
import asyncio
from typing import List
from datetime import datetime

class CustomerServicePipeline:
    def __init__(self, api_key: str):
        self.pipeline = HolySheepPipeline(api_key)
        self.total_cost_tokens = 0
        self.execution_log: List[PipelineResult] = []
        
    def estimate_cost(self, tokens: int, model: str) -> float:
        """コスト估算 - HolySheep ¥1=$1"""
        prices_per_mtok = {
            "gpt-4.1": 8.0,
            "claude-sonnet-4.5": 15.0,
            "deepseek-v3.2": 0.42,
            "gemini-2.5-flash": 2.50
        }
        price = prices_per_mtok.get(model, 1.0)
        return (tokens / 1_000_000) * price
    
    def execute(self, user_message: str, context: Optional[Dict] = None) -> Dict:
        """Pipeline完全実行"""
        print(f"\n{'='*50}")
        print(f"Pipeline開始: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"問い合わせ: {user_message[:50]}...")
        
        results = {}
        
        # Step 1: 意図分類
        step1 = classify_intent(self.pipeline, user_message)
        self.execution_log.append(step1)
        results["classification"] = step1
        
        if not step1.success:
            return {"status": "failed", "step": "classification", "error": step1.error}
        
        intent = step1.output_data["intent"]
        
        # Step 2: 回答生成
        step2 = generate_response(
            self.pipeline, 
            intent, 
            user_message, 
            context
        )
        self.execution_log.append(step2)
        results["generation"] = step2
        
        if not step2.success:
            return {"status": "failed", "step": "generation", "error": step2.error}
        
        # Step 3: 品質チェック
        step3 = quality_check(
            self.pipeline,
            step2.output_data["response"],
            user_message
        )
        self.execution_log.append(step3)
        results["quality_check"] = step3
        
        # コスト集計
        total_tokens = sum(r.tokens_used for r in self.execution_log)
        total_cost_usd = self.estimate_cost(total_tokens, "deepseek-v3.2")
        
        # 最終结果
        final_response = step2.output_data["response"]
        if not step3.success or not step3.output_data["approved"]:
            # 品質チェック失敗時はフォールバック回答
            final_response = self._generate_fallback_response(intent)
        
        print(f"\n{'='*50}")
        print(f"Pipeline完了 - 総レイテンシ: {sum(r.latency_ms for r in self.execution_log):.1f}ms")
        print(f"総トークン: {total_tokens} | コスト: ${total_cost_usd:.4f}")
        
        return {
            "status": "success",
            "intent": intent.value,
            "response": final_response,
            "quality_score": step3.output_data.get("final_score", "N/A"),
            "metrics": {
                "total_tokens": total_tokens,
                "cost_usd": total_cost_usd,
                "cost_jpy": total_cost_usd * 160,  # 概算
                "total_latency_ms": sum(r.latency_ms for r in self.execution_log)
            }
        }
    
    def _generate_fallback_response(self, intent: IntentType) -> str:
        """品質チェック失敗時のフォールバック"""
        fallbacks = {
            IntentType.COMPLAINT: "ご不便をおかけして申し訳ございません。担当者がすぐに対応いたしますので、恐れ入りますが[email protected]までご連絡ください。",
            IntentType.RETURN: "退货 신청은 ourサイト内の退货申请ページからお願いします:https://example.com/returns",
            IntentType.PRODUCT_INQUIRY: "商品詳細については、恐れ入りますが我们的的商品ページをご覧ください:https://example.com/products"
        }
        return fallbacks.get(intent, "申し訳ございません。一時的なシステムエラーが発生しました。後ほど再度お試しいただくか、カスタマーサポートまでご連絡ください。")

利用例

api_key = "YOUR_HOLYSHEEP_API_KEY" customer_service = CustomerServicePipeline(api_key) result = customer_service.execute( user_message="先程注文した книга の状態がUnionPayで支払い済みなのに、まだ届かない。注文番号はORD-20240115-8842です。", context={ "order_id": "ORD-20240115-8842", "order_date": "2024-01-15", "member_tier": "ゴールド" } ) print(json.dumps(result, ensure_ascii=False, indent=2))

HolySheep AI pricing table 2026年

モデル入力 ($/MTok)出力 ($/MTok)推奨用途
GPT-4.1$2.00$8.00高品质文章生成
Claude Sonnet 4.5$3.00$15.00长文分析·思考
Gemini 2.5 Flash$0.30$2.50高速·大批量处理
DeepSeek V3.2$0.27$0.42日常对话·分类

HolySheep AIでは ¥1=$1 の汇率で提供しており、公式汇率(¥7.3=$1)相比85%のコスト削减が可能です。また、WeChat PayやAlipayにも対応しており 가입 시 무료 크레딧도 제공됩니다。

よくあるエラーと対処法

エラー1:JSON解析エラー

# 問題:LLM出力が不完全なJSONで返される

原因:max_tokens不足、または出力が途中で切断

解決策1:max_tokensを増加

step = PipelineStep( name="classification", model="deepseek-v3.2", max_tokens=500, # 200→500に増加 temperature=0.3 )

解決策2:JSON回復处理を実装

import re def safe_json_parse(text: str) -> Optional[dict]: """不完全JSONの回復処理""" # バックティック内のJSONを抽出 json_match = re.search(r'``(?:json)?\s*([\s\S]*?)\s*``', text) if json_match: text = json_match.group(1) # 波括弧で囲まれた部分を抽出 brace_match = re.search(r'\{[\s\S]*\}', text) if brace_match: text = brace_match.group() try: return json.loads(text) except json.JSONDecodeError: # 最後のカンマを削除して再試行 cleaned = re.sub(r',(\s*[}\]])', r'\1', text) try: return json.loads(cleaned) except: return None

エラー2:APIタイムアウト

# 問題:httpx.Client.timeout 导致请求失败

原因:モデルが高负载狀態、または网络延迟

解決策:リトライ逻辑 + タイムアウト延长

from tenacity import retry, stop_after_attempt, wait_exponential class HolySheepPipelineRobust: def __init__(self, api_key: str): self.api_key = api_key self.base_url = "https://api.holysheep.ai/v1" self.client = httpx.Client(timeout=60.0) # 30→60秒に延長 @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10) ) def _call_with_retry(self, step: PipelineStep, message: str) -> tuple: """指数バックオフでリトライ""" response = self.client.post( f"{self.base_url}/chat/completions", headers=self._get_headers(), json=self._build_payload(step, message) ) if response.status_code == 429: raise RetryableError("Rate limit exceeded") elif response.status_code >= 500: raise RetryableError(f"Server error: {response.status_code}") return self._parse_response(response)

エラー3:意図分類の精度低下

# 問題:意図分類が「other」に偏る

原因:プロンプトの指示が不十分、またはexamples不足

解決策:Few-shot learningで精度向上

IMPROVED_CLASSIFICATION_PROMPT = """你是EC問い合わせ分类专家。 根据以下示例进行分类: 示例1: "靴の匂いが気になる" → {"intent": "product_inquiry"} 示例2: "まだ届かない、もう3週間たった" → {"intent": "complaint"} 示例3: "サイズ違いで 교환したい" → {"intent": "return"} 示例4: "ポイントを買い物に使えますか?" → {"intent": "other"} 现在分类以下查询: {user_message} 输出格式:{"intent": "意图", "confidence": 0.0-1.0}