0Pricing
AI Prompt Engineering · บทเรียน

การกระจายโหลดระหว่างโมเดล

ส่งพรอมต์ราคาถูกไปยังโมเดลขนาดเล็ก และพรอมต์ยากไปยังโมเดลขนาดใหญ่

การกระจายโหลดระหว่างโมเดล เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

เหตุใดจึงต้องกำหนดเส้นทางข้ามโมเดล

ไม่ใช่ทุกงานที่ต้องใช้โมเดลที่ทรงพลังที่สุดและมีราคาแพงที่สุด การตอบคำทักทายง่าย ๆ ไม่จำเป็นต้องใช้ GPT-4o การกำหนดเส้นทางโมเดลจะส่งคำขอแต่ละรายการไปยังโมเดลที่มีราคาถูกที่สุดซึ่งรองรับงานนั้นได้ดี ช่วยลดค่าใช้จ่ายลง 50-90% พร้อมรักษาคุณภาพในส่วนที่สำคัญ

การกำหนดเส้นทางตามความซับซ้อน

จำแนกความซับซ้อนของงานก่อนเรียกใช้เอพีไอ งานง่ายให้ส่งไปยังโมเดลราคาถูก ส่วนงานซับซ้อนให้ส่งไปยังโมเดลที่มีความสามารถสูง ตัวจำแนกขนาดเล็กหรือหลักเกณฑ์เชิงประสบการณ์สามารถตัดสินใจนี้ได้อย่างรวดเร็ว

COMPLEXITY_CLASSIFIER_PROMPT = '''Classify the complexity of this user request.
Return ONLY one word: SIMPLE, MODERATE, or COMPLEX.

SIMPLE: greeting, factual lookup, single-step question, direct answer needed
MODERATE: multi-step explanation, comparison, short analysis, code snippet
COMPLEX: deep analysis, long code generation, reasoning chain, specialized domain

Request: {request}'''

import openai

client_mini = openai.OpenAI(api_key='YOUR_API_KEY')

def classify_complexity(request):
    response = client_mini.chat.completions.create(
        model='gpt-4o-mini',  # always use cheap model for classifier
        messages=[{'role': 'user', 'content':
            COMPLEXITY_CLASSIFIER_PROMPT.format(request=request)}],
        max_tokens=5,
        temperature=0
    )
    label = response.choices[0].message.content.strip().upper()
    if label not in ('SIMPLE', 'MODERATE', 'COMPLEX'):
        label = 'MODERATE'  # safe default
    return label

for req in ['Hi', 'Explain quicksort', 'Design a distributed systems architecture']:
    print(f'{req[:40]}: {classify_complexity(req)}')

คลาสตัวกำหนดเส้นทางโมเดล

ตัวกำหนดเส้นทางโมเดลจะจับคู่ป้ายกำกับความซับซ้อนกับโมเดล และกำหนดเส้นทางให้แต่ละคำขอตามนั้น การตัดสินใจกำหนดเส้นทางมีผลลัพธ์แน่นอนและอิงตามเกณฑ์ขอบเขตที่กำหนดค่าได้

MODEL_ROUTES = {
    'SIMPLE': {
        'model': 'gpt-4o-mini',
        'max_tokens': 300,
        'cost_per_1k_input': 0.00015,
        'use_case': 'greetings, FAQ, simple factual questions'
    },
    'MODERATE': {
        'model': 'gpt-4o',
        'max_tokens': 1500,
        'cost_per_1k_input': 0.0025,
        'use_case': 'explanations, analysis, code snippets'
    },
    'COMPLEX': {
        'model': 'claude-opus-4-5',
        'max_tokens': 4096,
        'cost_per_1k_input': 0.015,
        'use_case': 'deep reasoning, long code, specialized domains'
    }
}

class ModelRouter:
    def __init__(self):
        self.routes = MODEL_ROUTES
        self.call_counts = {k: 0 for k in MODEL_ROUTES}

    def route(self, request, messages):
        complexity = classify_complexity(request)
        route = self.routes[complexity]
        self.call_counts[complexity] += 1
        print(f'Routing "{request[:40]}" -> {route["model"]} ({complexity})')
        return route['model'], route['max_tokens']

    def cost_report(self):
        total = sum(self.call_counts.values())
        for complexity, count in self.call_counts.items():
            pct = count / total * 100 if total else 0
            print(f'{complexity}: {count} calls ({pct:.0f}%)')

การกำหนดเส้นทางที่คำนึงถึงค่าใช้จ่าย

นอกเหนือจากความซับซ้อนแล้ว การกำหนดเส้นทางที่คำนึงถึงค่าใช้จ่ายยังพิจารณางบประมาณโทเค็น ระดับผู้ใช้ (ฟรีหรือชำระเงิน) และเพดานการใช้จ่ายรายวัน เพื่อให้คาดการณ์ค่าใช้จ่ายได้ทั่วทั้งระบบ

class CostAwareRouter(ModelRouter):
    def __init__(self, daily_budget_usd=100.0):
        super().__init__()
        self.daily_budget = daily_budget_usd
        self.daily_spent = 0.0

    def estimate_cost(self, model, input_tokens, max_output_tokens):
        route = next((r for r in self.routes.values() if r['model'] == model), None)
        if not route:
            return 0.0
        return (
            (input_tokens / 1000) * route['cost_per_1k_input'] +
            (max_output_tokens / 1000) * route['cost_per_1k_input'] * 3
        )

    def route_with_budget(self, request, messages, user_tier='free'):
        complexity = classify_complexity(request)

        # Downgrade if budget is exhausted or user is on free tier
        budget_remaining = self.daily_budget - self.daily_spent
        if budget_remaining < 0.01 or user_tier == 'free':
            complexity = 'SIMPLE'  # downgrade to cheapest model
            print('Budget constraint: routing to SIMPLE model')

        route = self.routes[complexity]
        input_tokens = sum(len(m['content'].split()) for m in messages) * 1.3
        cost = self.estimate_cost(route['model'], input_tokens, route['max_tokens'])
        self.daily_spent += cost
        return route['model'], route['max_tokens']

การกำหนดเส้นทางที่คำนึงถึงเวลาแฝง

โมเดลแต่ละแบบมีลักษณะเวลาแฝงแตกต่างกัน เมื่อมีข้อจำกัดด้านเวลา เช่น แชตบอตที่มี SLA 3 วินาที ให้กำหนดเส้นทางไปยังโมเดลที่เร็วกว่า แม้โมเดลนั้นจะมีความสามารถน้อยกว่า

import time

# Model latency profiles (approximate P95 values)
MODEL_LATENCY_P95 = {
    'gpt-4o-mini': 1.5,       # seconds
    'gpt-4o': 4.0,
    'claude-haiku-4-5': 1.2,
    'claude-sonnet-4-5': 3.0,
    'claude-opus-4-5': 6.0
}

SLA_LATENCY_BUDGET = 3.0  # seconds

def route_with_latency_constraint(complexity, sla_seconds=SLA_LATENCY_BUDGET):
    route = MODEL_ROUTES[complexity]
    p95_latency = MODEL_LATENCY_P95.get(route['model'], 5.0)

    if p95_latency > sla_seconds:
        # Find fastest model under SLA
        affordable_models = [
            (lat, m) for m, lat in MODEL_LATENCY_P95.items()
            if lat <= sla_seconds
        ]
        if affordable_models:
            fastest = min(affordable_models)[1]
            print(f'Latency constraint: downgrading from {route["model"]} to {fastest}')
            return fastest
    return route['model']

print('COMPLEX request under 3s SLA:', route_with_latency_constraint('COMPLEX'))

การกำหนดเส้นทางที่คำนึงถึงความสามารถ

งานบางประเภทต้องใช้ความสามารถเฉพาะของโมเดล เช่น การมองเห็น การเรียกฟังก์ชัน บริบทยาว หรือตัวแปลโค้ด การกำหนดเส้นทางที่คำนึงถึงความสามารถจะช่วยให้มั่นใจว่าโมเดลที่เลือกสามารถรองรับงานนั้นได้จริง

MODEL_CAPABILITIES = {
    'gpt-4o-mini': {
        'vision': True,
        'function_calling': True,
        'context_window': 128000,
        'code_interpreter': False
    },
    'gpt-4o': {
        'vision': True,
        'function_calling': True,
        'context_window': 128000,
        'code_interpreter': True
    },
    'claude-opus-4-5': {
        'vision': True,
        'function_calling': True,
        'context_window': 200000,
        'code_interpreter': False
    }
}

def capability_aware_route(required_capabilities, context_length=0):
    candidates = []
    for model, caps in MODEL_CAPABILITIES.items():
        if context_length > caps['context_window']:
            continue
        if all(caps.get(cap, False) for cap in required_capabilities):
            candidates.append(model)

    if not candidates:
        raise ValueError(f'No model supports: {required_capabilities}')

    # Among capable models, pick cheapest
    cost_rank = ['gpt-4o-mini', 'claude-opus-4-5', 'gpt-4o']
    for model in cost_rank:
        if model in candidates:
            return model
    return candidates[0]

print(capability_aware_route(['vision', 'function_calling'], context_length=5000))

ลำดับโมเดลสำรอง

ลำดับโมเดลสำรองจะกำหนดลำดับของโมเดลที่จะลองใช้เมื่อโมเดลหลักล้มเหลว วิธีนี้ช่วยให้ระบบพร้อมใช้งานสูง แม้ผู้ให้บริการบางรายจะขัดข้องหรือมีปัญหาด้านขีดจำกัดอัตรา

FALLBACK_CHAINS = {
    'primary': 'claude-opus-4-5',
    'fallback': 'gpt-4o',
    'emergency': 'gpt-4o-mini'
}

def call_with_fallback(messages, chain=FALLBACK_CHAINS):
    providers = [
        ('anthropic', chain['primary']),
        ('openai', chain['fallback']),
        ('openai', chain['emergency'])
    ]

    for provider, model in providers:
        try:
            print(f'Trying {model}...')
            if provider == 'anthropic':
                import anthropic
                ac = anthropic.Anthropic(api_key='YOUR_KEY')
                resp = ac.messages.create(
                    model=model, max_tokens=500, messages=messages
                )
                return resp.content[0].text
            else:
                import openai
                oc = openai.OpenAI(api_key='YOUR_KEY')
                resp = oc.chat.completions.create(
                    model=model, messages=messages, max_tokens=500
                )
                return resp.choices[0].message.content
        except Exception as e:
            print(f'{model} failed: {e}. Trying next...')

    raise RuntimeError('All models in fallback chain failed')

การบันทึกการตัดสินใจกำหนดเส้นทาง

บันทึกการตัดสินใจกำหนดเส้นทางทุกครั้งพร้อมบริบทที่เพียงพอสำหรับการตรวจสอบย้อนหลัง การปรับเกณฑ์ และการทำความเข้าใจการกระจายค่าใช้จ่าย ข้อมูลนี้จำเป็นต่อการเพิ่มประสิทธิภาพตรรกะการกำหนดเส้นทางในระยะยาว

import json
from datetime import datetime

ROUTING_LOG_FILE = 'routing_decisions.jsonl'

def log_routing_decision(request_id, request_text, complexity,
                          model_selected, cost_estimate, latency_ms,
                          user_tier='free'):
    entry = {
        'timestamp': datetime.utcnow().isoformat(),
        'request_id': request_id,
        'request_preview': request_text[:50],
        'complexity': complexity,
        'model': model_selected,
        'cost_estimate_usd': round(cost_estimate, 6),
        'latency_ms': round(latency_ms),
        'user_tier': user_tier
    }
    with open(ROUTING_LOG_FILE, 'a') as f:
        f.write(json.dumps(entry) + '\n')

# Analyze routing log to tune thresholds
def analyze_routing_log():
    from collections import Counter
    model_counts = Counter()
    total_cost = 0.0
    with open(ROUTING_LOG_FILE) as f:
        for line in f:
            e = json.loads(line)
            model_counts[e['model']] += 1
            total_cost += e['cost_estimate_usd']
    print('Model distribution:', dict(model_counts))
    print(f'Total estimated cost: ${total_cost:.4f}')

การทดสอบโมเดลแบบ A/B ในระบบจริง

การกำหนดเส้นทางโมเดลยังสามารถใช้การทดสอบแบบ A/B ได้ โดยส่งปริมาณการใช้งานบางส่วนไปยังโมเดลใหม่เพื่อเปรียบเทียบคุณภาพก่อนเปิดใช้เต็มรูปแบบ ควรใช้ร่วมกับการเฝ้าติดตามเพื่อเลือกโมเดลโดยอิงข้อมูล

import random

class ABModelRouter:
    def __init__(self, control_model, treatment_model, treatment_pct=10):
        self.control = control_model
        self.treatment = treatment_model
        self.treatment_pct = treatment_pct
        self.assignment_log = {}  # request_id: 'control' | 'treatment'

    def route(self, request_id):
        if request_id in self.assignment_log:
            # Sticky assignment: same user always gets same model
            return self.assignment_log[request_id]

        if random.random() * 100 < self.treatment_pct:
            assignment = 'treatment'
            model = self.treatment
        else:
            assignment = 'control'
            model = self.control

        self.assignment_log[request_id] = assignment
        return model, assignment

# Usage
ab_router = ABModelRouter(
    control_model='gpt-4o',
    treatment_model='claude-opus-4-5',
    treatment_pct=10  # 10% get new model
)

for user_id in range(5):
    result = ab_router.route(f'user_{user_id}')
    print(f'user_{user_id}: {result}')

การตรวจสอบสถานะพร้อมใช้งานของโมเดล

ก่อนส่งปริมาณการใช้งานไปยังโมเดล ให้ตรวจสอบว่าโมเดลตอบสนองได้ถูกต้อง การตรวจสอบสถานะจะส่งพรอมต์ที่ทราบผลไปยังโมเดล และตรวจสอบความถูกต้องของคำตอบเพื่อยืนยันว่าผู้ให้บริการพร้อมใช้งาน

import time

def health_check(model, provider='openai', timeout=5):
    '''
    Returns True if model is healthy, False if timed out or errored.
    '''
    test_prompt = 'Reply with exactly: OK'
    try:
        start = time.time()
        if provider == 'openai':
            import openai
            client = openai.OpenAI(api_key='YOUR_API_KEY')
            resp = client.chat.completions.create(
                model=model,
                messages=[{'role': 'user', 'content': test_prompt}],
                max_tokens=5,
                timeout=timeout
            )
            text = resp.choices[0].message.content.strip()
        elif provider == 'anthropic':
            import anthropic
            client = anthropic.Anthropic(api_key='YOUR_API_KEY')
            resp = client.messages.create(
                model=model, max_tokens=5,
                messages=[{'role': 'user', 'content': test_prompt}],
            )
            text = resp.content[0].text.strip()
        latency = (time.time() - start) * 1000
        healthy = 'ok' in text.lower()
        print(f'{model}: {"HEALTHY" if healthy else "DEGRADED"} ({latency:.0f}ms)')
        return healthy
    except Exception as e:
        print(f'{model}: UNHEALTHY ({e})')
        return False

# Run health checks before routing critical traffic
# health_check('gpt-4o-mini', provider='openai')
# health_check('claude-haiku-4-5', provider='anthropic')

การวิเคราะห์ผลกระทบด้านค่าใช้จ่าย

วัดปริมาณเงินที่ประหยัดได้จากการกำหนดเส้นทางโมเดล หากปริมาณการใช้งานประกอบด้วย SIMPLE 60%, MODERATE 30% และ COMPLEX 10% การกำหนดเส้นทางอย่างชาญฉลาดสามารถลดค่าใช้จ่ายได้ 70-80% เมื่อเทียบกับการใช้โมเดลที่ดีที่สุดกับทุกงาน

def cost_impact_analysis(daily_requests=10000):
    # Traffic distribution
    traffic = {'SIMPLE': 0.60, 'MODERATE': 0.30, 'COMPLEX': 0.10}

    # Avg tokens per request (input + output)
    avg_tokens = {'SIMPLE': 500, 'MODERATE': 2000, 'COMPLEX': 5000}

    # Pricing per 1K tokens (blended input+output)
    pricing = {'SIMPLE': 0.00030, 'MODERATE': 0.01000, 'COMPLEX': 0.04500}
    premium_price = 0.04500  # if we used COMPLEX model for everything

    routed_cost = 0.0
    premium_cost = 0.0

    for complexity, pct in traffic.items():
        requests = daily_requests * pct
        tokens = avg_tokens[complexity]
        routed_cost += requests * (tokens / 1000) * pricing[complexity]
        premium_cost += requests * (tokens / 1000) * premium_price

    savings_pct = (1 - routed_cost / premium_cost) * 100
    print(f'Daily requests: {daily_requests:,}')
    print(f'With routing:  ${routed_cost:,.2f}/day')
    print(f'Without routing: ${premium_cost:,.2f}/day')
    print(f'Savings: {savings_pct:.0f}% (${premium_cost - routed_cost:,.2f}/day)')

cost_impact_analysis()

ตรวจสอบความเข้าใจ

ผู้ใช้ถามว่า 'สวัสดี คุณเป็นอย่างไรบ้าง' ตัวกำหนดเส้นทางโมเดลจำแนกคำถามนี้เป็น SIMPLE เหตุใดการกำหนดเส้นทางไปยัง gpt-4o-mini แทนที่จะเป็น gpt-4o จึงเป็นการตัดสินใจที่ถูกต้อง

สรุปการกำหนดเส้นทางโมเดล

การกระจายภาระระหว่างโมเดลช่วยลดค่าใช้จ่ายและทำให้เลือกโมเดลได้ตรงกับความสามารถที่ต้องการ:

  • การกำหนดเส้นทางตามความซับซ้อน: จำแนกงานเป็น SIMPLE/MODERATE/COMPLEX แล้วส่งไปยังระดับโมเดลที่ตรงกัน
  • การกำหนดเส้นทางที่คำนึงถึงค่าใช้จ่าย: ลดระดับโมเดลเมื่อใช้งบประมาณหมดหรือเมื่อเป็นผู้ใช้ระดับฟรี
  • การกำหนดเส้นทางที่คำนึงถึงเวลาแฝง: ใช้โมเดลที่เร็วกว่าเมื่อ SLA มีข้อจำกัดมาก
  • การกำหนดเส้นทางตามความสามารถ: ตรวจสอบว่าโมเดลที่เลือกสนับสนุนคุณลักษณะที่ต้องการ เช่น การมองเห็นและการเรียกใช้ฟังก์ชัน
  • ลำดับโมเดลสำรอง: โมเดลหลัก → โมเดลสำรอง → โมเดลฉุกเฉิน เพื่อให้พร้อมใช้งานสูง
  • การทดสอบแบบ A/B: ทดสอบโมเดลใหม่กับปริมาณการใช้งานบางส่วนก่อนเปิดใช้เต็มรูปแบบ
  • ผลกระทบด้านค่าใช้จ่าย: การกำหนดเส้นทางสามารถลดค่าใช้จ่ายได้ 70-80% เมื่อเทียบกับการใช้โมเดลที่ดีที่สุดเสมอ

คำถามที่พบบ่อย

บทเรียน “การกระจายโหลดระหว่างโมเดล” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การกระจายโหลดระหว่างโมเดล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การกระจายโหลดระหว่างโมเดล”

ส่งพรอมต์ราคาถูกไปยังโมเดลขนาดเล็ก และพรอมต์ยากไปยังโมเดลขนาดใหญ่ คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การกระจายโหลดระหว่างโมเดล” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม

ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. กลยุทธ์การแคชพรอมต์
  2. การประมวลผลเป็นชุดและการทำงานแบบอะซิงโครนัส
  3. การกระจายโหลดระหว่างโมเดล
  4. การตรวจติดตามและแจ้งเตือนสำหรับไปป์ไลน์พรอมต์
← กลับไปที่ AI Prompt Engineering