ในการพัฒนาแอปพลิเคชันที่ใช้ AI API การทดสอบด้วย Mock Response เป็นสิ่งจำเป็นอย่างยิ่ง โดยเฉพาะเมื่อต้องทำงานกับ AI ที่มีค่าใช้จ่ายสูงอย่าง GPT-4.1 หรือ Claude Sonnet 4.5 บทความนี้จะแสดงวิธีการจำลอง Response อย่างมีประสิทธิภาพ พร้อมโค้ดตัวอย่างที่ใช้งานได้จริง โดยใช้ HolySheep AI ซึ่งมีอัตราค่าบริการที่ประหยัดกว่า 85% เมื่อเทียบกับผู้ให้บริการอื่น

ทำไมต้อง Mock AI API Response?

จากประสบการณ์ของผมในการพัฒนาระบบ RAG ขององค์กรขนาดใหญ่ การทดสอบ AI API โดยตรงมีข้อจำกัดหลายประการ:

กรณีศึกษา: ระบบ RAG ขององค์กร

ในโปรเจกต์หนึ่ง ทีมของผมพัฒนาระบบ RAG สำหรับองค์กรที่ต้องจัดการเอกสารลูกค้าหลายหมื่นฉบับ การใช้ HolySheep AI ช่วยลดค่าใช้จ่ายจาก $500/วัน เหลือเพียง $75/วัน เนื่องจากราคาของ DeepSeek V3.2 อยู่ที่เพียง $0.42/MTok เท่านั้น

โครงสร้าง Mock Server พื้นฐาน

โค้ดต่อไปนี้แสดงการสร้าง Mock Server สำหรับ AI API โดยใช้ FastAPI:

import json
from typing import Generator, Optional
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
import asyncio

app = FastAPI(title="AI API Mock Server")

กำหนด Mock Responses สำหรับแต่ละ Intent

MOCK_RESPONSES = { "product_inquiry": { "model": "gpt-4.1", "content": "สินค้านี้มีส่วนลด 20% สำหรับสมาชิก VIP ค่ะ", "usage": {"prompt_tokens": 45, "completion_tokens": 28, "total_tokens": 73} }, "order_status": { "model": "claude-sonnet-4.5", "content": "คำสั่งซื้อของคุณอยู่ในสถานะจัดส่งแล้วค่ะ คาดว่าจะถึงภายใน 2-3 วันทำการ", "usage": {"prompt_tokens": 62, "completion_tokens": 45, "total_tokens": 107} }, "refund_request": { "model": "gemini-2.5-flash", "content": "ระบบได้รับคำขอคืนเงินของคุณแล้ว จะดำเนินการภายใน 7 วันทำการ", "usage": {"prompt_tokens": 38, "completion_tokens": 35, "total_tokens": 73} } } @app.post("/v1/chat/completions") async def mock_chat_completions(request: Request): body = await request.json() messages = body.get("messages", []) model = body.get("model", "gpt-4.1") # วิเคราะห์ Intent จากข้อความ (Mock Logic) last_message = messages[-1]["content"] if messages else "" intent = "product_inquiry" if "สถานะ" in last_message or "ติดตาม" in last_message: intent = "order_status" elif "คืนเงิน" in last_message or "ยกเลิก" in last_message: intent = "refund_request" mock_data = MOCK_RESPONSES[intent] # จำลอง Response response = { "id": f"mock-{request.headers.get('x-request-id', 'req-001')}", "object": "chat.completion", "created": 1704067200, "model": model, "choices": [{ "index": 0, "message": { "role": "assistant", "content": mock_data["content"] }, "finish_reason": "stop" }], "usage": mock_data["usage"] } return JSONResponse(content=response) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)

การใช้ HolySheep AI ร่วมกับ Mock Strategy

แนวทางที่ดีที่สุดคือการใช้ Mock ในระหว่าง development และ QA แต่ใช้ API จริงใน production โค้ดต่อไปนี้แสดงวิธีการสลับระหว่าง Mock และ Real API:

import os
from typing import Optional
import openai

class AIService:
    def __init__(self, use_mock: bool = False):
        self.use_mock = use_mock
        self.base_url = "https://api.holysheep.ai/v1"
        
        if not use_mock:
            self.client = openai.OpenAI(
                api_key=os.environ.get("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY"),
                base_url=self.base_url
            )
    
    async def chat_completion(
        self, 
        messages: list, 
        model: str = "gpt-4.1",
        temperature: float = 0.7
    ) -> dict:
        if self.use_mock:
            return self._mock_response(messages, model)
        
        response = self.client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature
        )
        return {
            "content": response.choices[0].message.content,
            "usage": {
                "prompt_tokens": response.usage.prompt_tokens,
                "completion_tokens": response.usage.completion_tokens,
                "total_tokens": response.usage.total_tokens
            },
            "model": response.model
        }
    
    def _mock_response(self, messages: list, model: str) -> dict:
        # Mock logic สำหรับ development
        last_msg = messages[-1]["content"] if messages else ""
        
        return {
            "content": f"[MOCK] นี่คือ response จำลองสำหรับ: {last_msg[:50]}...",
            "usage": {"prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25},
            "model": model,
            "is_mock": True
        }

การใช้งาน

service_dev = AIService(use_mock=True) # Development mode service_prod = AIService(use_mock=False) # Production mode

Mock Testing สำหรับ QA Team

สำหรับ QA Team โค้ดต่อไปนี้แสดงการสร้าง Mock Server ที่รองรับ Streaming และ Error Simulation:

import time
import random
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
import json

app = FastAPI()

กำหนด Test Scenarios

TEST_SCENARIOS = { "success": {"status": 200, "delay_ms": 0}, "slow_response": {"status": 200, "delay_ms": 5000}, "rate_limit": {"status": 429, "error": "Rate limit exceeded"}, "server_error": {"status": 500, "error": "Internal server error"}, "timeout": {"status": 408, "error": "Request timeout"}, "empty_response": {"status": 200, "content": ""} } @app.post("/v1/chat/completions") async def mock_qa_endpoint(request: Request): body = await request.json() scenario = body.get("test_scenario", "success") enable_streaming = body.get("stream", False) scenario_config = TEST_SCENARIOS.get(scenario, TEST_SCENARIOS["success"]) # Simulate Delay if scenario_config.get("delay_ms"): await asyncio.sleep(scenario_config["delay_ms"] / 1000) # Handle Error Scenarios if scenario_config["status"] != 200: raise HTTPException( status_code=scenario_config["status"], detail=scenario_config["error"] ) # Generate Response if enable_streaming: return StreamingResponse( mock_stream_response(body), media_type="text/event-stream" ) return { "id": f"qa-test-{int(time.time())}", "object": "chat.completion", "created": int(time.time()), "model": body.get("model", "gpt-4.1"), "choices": [{ "index": 0, "message": { "role": "assistant", "content": body.get("mock_response", "[QA Test Response]") }, "finish_reason": "stop" }], "usage": {"prompt_tokens": 50, "completion_tokens": 25, "total_tokens": 75} } async def mock_stream_response(body: dict) -> AsyncGenerator[str, None]: """Simulate streaming response for load testing""" content = body.get("mock_response", "Streaming test response") chunk_size = 5 for i in range(0, len(content), chunk_size): chunk = content[i:i+chunk_size] data = { "choices": [{ "delta": {"content": chunk}, "index": 0, "finish_reason": None }] } yield f"data: {json.dumps(data)}\n\n" await asyncio.sleep(0.05) # 50ms between chunks # Send final chunk yield f"data: {json.dumps({'choices': [{'delta': {}, 'index': 0, 'finish_reason': 'stop'}]})}\n\n"

Example test case for QA

TEST_CASE = { "model": "gpt-4.1", "messages": [{"role": "user", "content": "ทดสอบระบบ"}], "test_scenario": "rate_limit", "mock_response": "This should not appear" }

ข้อผิดพลาดที่พบบ่อยและวิธีแก้ไข

1. ปัญหา: Mock Response ไม่ตรงกับ Format จริง

อาการ: เมื่อสลับจาก Mock เป็น Real API โค้ดพังเพราะ response structure ไม่ตรงกัน

สาเหตุ: Mock server ใช้ format ที่ไม่เหมือน API จริง โดยเฉพาะ OpenAI-compatible format

วิธีแก้:

# ❌ วิธีผิด - Response format ไม่ตรงกัน
class BadMockResponse:
    def __init__(self):
        self.text = "Hello"  # ใช้ .text แต่ OpenAI ใช้ .content

✅ วิธีถูก - ใช้ format เดียวกับ OpenAI SDK

class HolySheepMockResponse: """Mock ที่ match กับ OpenAI SDK response structure""" def __init__(self, content: str, model: str): self.model = model self.id = f"mock-{random.randint(1000,9999)}" self.choices = [self.Choice(content)] self.usage = self.Usage(50, 25, 75) class Choice: def __init__(self, content): self.message = self.Message(content) class Message: def __init__(self, content): self.content = content class Usage: def __init__(self, p, c, t): self.prompt_tokens = p self.completion_tokens = c self.total_tokens = t

การใช้งาน

response = HolySheepMockResponse("สวัสดีครับ", "gpt-4.1") print(response.choices[0].message.content) # จะทำงานเหมือน response จริง

2. ปัญหา: Rate Limit ทำให้ Test ล้มเหลว

อาการ: Integration test ล้มเพราะ API ถูก rate limit ระหว่าง test execution

สาเหตุ: Test หลายตัวเรียก API พร้อมกันโดยไม่มีการจำกัด concurrency

วิธีแก้:

import asyncio
from typing import List
import os

class RateLimitAwareTester:
    def __init__(self, max_concurrent: int = 5):
        self.max_concurrent = max_concurrent
        self.semaphore = asyncio.Semaphore(max_concurrent)
        self.api_key = os.environ.get("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY")
        self.base_url = "https://api.holysheep.ai/v1"
        self.use_mock = os.environ.get("USE_MOCK", "true").lower() == "true"
    
    async def run_tests(self, test_cases: List[dict]) -> List[dict]:
        tasks = [self._run_single_test(tc) for tc in test_cases]
        return await asyncio.gather(*tasks)
    
    async def _run_single_test(self, test_case: dict) -> dict:
        async with self.semaphore:  # จำกัด concurrent requests
            if self.use_mock:
                return await self._mock_test(test_case)
            return await self._real_api_test(test_case)
    
    async def _mock_test(self, test_case: dict) -> dict:
        # Simulate API delay
        await asyncio.sleep(0.1)
        return {"status": "passed", "mock": True, "case": test_case["name"]}
    
    async def _real_api_test(self, test_case: dict) -> dict:
        # เรียก HolySheep AI API จริง
        import openai
        client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
        
        try:
            response = client.chat.completions.create(
                model="gpt-4.1",
                messages=test_case["messages"]
            )
            return {"status": "passed", "response": response.choices[0].message.content}
        except Exception as e:
            return {"status": "failed", "error": str(e)}

การใช้งาน - รัน test 50 ตัวพร้อมกัน แต่จำกัด concurrent 5 ตัว

tester = RateLimitAwareTester(max_concurrent=5) results = asyncio.run(tester.run_tests([ {"name": "test_1", "messages": [{"role": "user", "content": "ทดสอบ"}]}, {"name": "test_2", "messages": [{"role": "user", "content": "ทดสอบ 2"}]}, # ... test cases อื่นๆ ]))

3. ปัญหา: Token Usage Tracking ไม่ถูกต้อง

อาการ: ค่าใช้จ่ายที่คำนวณได้ไม่ตรงกับรายงานจริงจาก API provider

สาเหตุ: Mock server ไม่ได้คำนวณ tokens ตาม tiktoken หรือ tokenizer จริง

วิธีแก้:

import tiktoken

class AccurateTokenCounter:
    """นับ tokens ให้ตรงกับ API จริง"""
    
    ENCODINGS = {
        "gpt-4.1": "cl100k_base",
        "claude-sonnet-4.5": "cl100k_base",  # Claude ก็ใช้ same tokenizer
        "gemini-2.5-flash": "cl100k_base",
        "deepseek-v3.2": "cl100k_base"
    }
    
    @classmethod
    def count_tokens(cls, text: str, model: str) -> int:
        encoding_name = cls.ENCODINGS.get(model, "cl100k_base")
        encoding = tiktoken.get_encoding(encoding_name)
        return len(encoding.encode(text))
    
    @classmethod
    def count_messages_tokens(cls, messages: list, model: str) -> int:
        """นับ tokens สำหรับ chat format ทั้งหมด"""
        tokens_per_message = 3  # overhead สำหรับ format
        tokens = tokens_per_message
        
        for msg in messages:
            tokens += cls.count_tokens(msg.get("content", ""), model)
            tokens += cls.count_tokens(msg.get("role", ""), model)
        
        tokens += 3  # final overhead
        return tokens
    
    @classmethod
    def calculate_cost(cls, model: str, prompt_tokens: int, completion_tokens: int) -> float:
        """คำนวณค่าใช้จ่ายตามราคา 2026"""
        PRICES = {
            "gpt-4.1": {"prompt": 8.0, "completion": 8.0},  # $/MTok
            "claude-sonnet-4.5": {"prompt": 15.0, "completion": 15.0},
            "gemini-2.5-flash": {"prompt": 2.5, "completion": 2.5},
            "deepseek-v3.2": {"prompt": 0.42, "completion": 0.42}
        }
        
        prices = PRICES.get(model, PRICES["gpt-4.1"])
        prompt_cost = (prompt_tokens / 1_000_000) * prices["prompt"]
        completion_cost = (completion_tokens / 1_000_000) * prices["completion"]
        
        return prompt_cost + completion_cost

การใช้งาน

messages = [ {"role": "system", "content": "คุณเป็นผู้ช่วยอีคอมเมิร์ซ"}, {"role": "user", "content": "สินค้านี้มีส่วนลดเท่าไหร่?"} ] tokens = AccurateTokenCounter.count_messages_tokens(messages, "gpt-4.1") cost = AccurateTokenCounter.calculate_cost("gpt-4.1", tokens, 50) print(f"Tokens: {tokens}, Cost: ${cost:.6f}") # จะได้ค่าที่ใกล้เคียง API จริงมาก

สรุป

การทำ Mock Testing สำหรับ AI API เป็นสิ่งจำเป็นสำหรับ development และ QA ที่มีประสิทธิภาพ การใช้ HolySheep AI ช่วยลดค่าใช้จ่ายได้ถึง 85% ขณะที่ยังคงได้ API ที่มีความหน่วงต่ำกว่า 50ms พร้อมรองรับวิธีการชำระเงินผ่าน WeChat และ Alipay

สำหรับทีมที่ต้องการปรับปรุงกระบวนการทดสอบ ผมแนะนำให้เริ่มจากการสร้าง Mock Server ตามโค้ดตัวอย่างข้างต้น จากนั้นค่อยๆ ขยายให้ครอบคลุม test cases ที่ซับซ้อนขึ้น

👉 สมัคร HolySheep AI — รับเครดิตฟรีเมื่อลงทะเบียน