บทนำ: ทำไมต้อง Template ข้อความ?

ในปี 2026 การใช้งาน Large Language Model (LLM) กลายเป็นส่วนสำคัญของการพัฒนาแอปพลิเคชัน AI อย่างไรก็ตาม การส่งข้อความ (prompt) แบบเดิมซ้ำๆ ไม่เพียงสิ้นเปลือง tokens หากเราใช้ API ที่มีราคาสูง แต่ยังทำให้โค้ดซ้ำซ้อนและยากต่อการบำรุงรักษา วันนี้เราจะมาเรียนรู้การใช้ LangChain สร้างระบบ Template ข้อความที่ประหยัด รวดเร็ว และนำกลับมาใช้ใหม่ได้

เปรียบเทียบค่าใช้จ่าย LLM API ปี 2026

ก่อนเริ่มต้น เรามาดูค่าใช้จ่ายจริงของแต่ละเจ้าหน้าที่กัน: ตัวอย่างการคำนวณค่าใช้จ่าย 10 ล้าน tokens/เดือน: หากคุณสมัคร HolyShehe AI วันนี้ คุณจะได้รับอัตราแลกเปลี่ยน ¥1=$1 ซึ่งหมายความว่าใช้ DeepSeek V3.2 ในราคาเพียง ¥4.20/ล้าน tokens หรือประหยัดมากกว่า 85% เมื่อเทียบกับ Claude ตอนนี้เรามาดูวิธีลดค่าใช้จ่ายด้วยการ Template ข้อความกัน

พื้นฐาน LangChain PromptTemplate

1. สร้าง Template ข้อความพื้นฐาน

"""
LangChain Prompt Template 基础教程
使用 HolySheep AI API
"""
import os
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain

ตั้งค่า API Key และ Base URL

⚠️ ต้องใช้ HolySheep AI เท่านั้น!

os.environ["OPENAI_API_KEY"] = "YOUR_HOLYSHEEP_API_KEY" os.environ["OPENAI_BASE_URL"] = "https://api.holysheep.ai/v1"

สร้าง Template พื้นฐาน

basic_template = PromptTemplate( input_variables=["product", "feature"], template=""" สวัสดีครับ! ผมต้องการทราบเกี่ยวกับ {product} โดยเฉพาะฟีเจอร์ {feature} มีความสามารถอย่างไร? กรุณาอธิบายแบบละเอียดพร้อมตัวอย่างการใช้งาน ขอบคุณครับ """ )

สร้าง LLM Chain

llm = ChatOpenAI( model="gpt-4.1", temperature=0.7, max_tokens=1000 ) chain = LLMChain(llm=llm, prompt=basic_template)

เรียกใช้งาน

result = chain.invoke({ "product": "สมาร์ทโฟน", "feature": "กล้อง AI" }) print(result["text"])

2. Template แบบมีโครงสร้าง (Structured Template)

"""
Template แบบมีโครงสร้างสำหรับระบบตอบคำถาม
รองรับหลายภาษาและหลายรูปแบบการตอบ
"""
from langchain.prompts import PromptTemplate, ChatPromptTemplate
from langchain.prompts.chat import SystemMessage, HumanMessagePromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from typing import List, Optional

กำหนด Schema สำหรับ output

class ProductInfo(BaseModel): name: str = Field(description="ชื่อสินค้า") price: float = Field(description="ราคาเป็นบาท") features: List[str] = Field(description="รายการฟีเจอร์หลัก") rating: Optional[float] = Field(default=0.0, description="คะแนน 1-5")

System Prompt Template

system_template = """คุณเป็นผู้เชี่ยวชาญด้านการวิเคราะห์สินค้าอิเล็กทรอนิกส์ คุณต้องตอบเป็นภาษา {language} เท่านั้น รูปแบบการตอบ: {response_format} """

Chat Prompt Template

chat_prompt = ChatPromptTemplate.from_messages([ SystemMessage(content=system_template), HumanMessagePromptTemplate.from_template( template=""" วิเคราะห์สินค้าต่อไปนี้: ชื่อ: {product_name} ราคา: {price} บาท ฟีเจอร์: {features} โปรดให้คะแนนความคุ้มค่า (1-5 ดาว) พร้อมเหตุผล """ ) ])

สร้าง LLM สำหรับ DeepSeek (ประหยัดที่สุด)

llm_deepseek = ChatOpenAI( model="deepseek-chat", base_url="https://api.holysheep.ai/v1", api_key="YOUR_HOLYSHEEP_API_KEY", temperature=0.5 )

แปลงเป็น output parser

from langchain.output_parsers import PydanticOutputParser output_parser = PydanticOutputParser(pydantic_object=ProductInfo)

เพิ่ม format instructions เข้า template

product_template = PromptTemplate( template=""" {format_instructions} วิเคราะห์สินค้า: {product_text} """, input_variables=["product_text"], partial_variables={ "format_instructions": output_parser.get_format_instructions() } ) chain = product_template | llm_deepseek | output_parser result = chain.invoke({ "product_text": "iPhone 16 Pro Max ราคา 54,900 บาท มีฟีเจอร์กล้อง 48MP, ชิป A18 Pro, จอ 6.9 นิ้ว ProMotion 120Hz" }) print(f"ชื่อ: {result.name}") print(f"ราคา: {result.price} บาท") print(f"ฟีเจอร์: {result.features}") print(f"คะแนน: {result.rating}/5")

การสร้าง Reusable Prompt Library

สำหรับโปรเจกต์ขนาดใหญ่ การสร้าง Library ของ Prompts ที่ใช้ซ้ำได้จะช่วยลดค่าใช้จ่ายและเวลาพัฒนาอย่างมาก
"""
Prompt Library สำหรับระบบ E-Commerce
รองรับการจัดการหลายภาษาและหลายกรณีใช้งาน
"""
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from enum import Enum
from dataclasses import dataclass
from typing import Dict, Optional, List

class PromptType(Enum):
    PRODUCT_DESCRIPTION = "description"
    CUSTOMER_SUPPORT = "support"
    REVIEW_SUMMARY = "summary"
    SEO_OPTIMIZE = "seo"

@dataclass
class PromptConfig:
    template: str
    model: str
    temperature: float
    max_tokens: int

class PromptLibrary:
    """Library สำหรับจัดการ Prompts ทั้งหมด"""
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self._init_templates()
    
    def _init_templates(self):
        """กำหนด Templates ทั้งหมด"""
        self.templates: Dict[PromptType, PromptConfig] = {
            PromptType.PRODUCT_DESCRIPTION: PromptConfig(
                template="""
                สร้างคำอธิบายสินค้าสำหรับ: {product_name}
                
                ข้อมูลสินค้า:
                - หมวดหมู่: {category}
                - ราคา: {price} บาท
                - ฟีเจอร์หลัก: {features}
                - กลุ่มเป้าหมาย: {target_audience}
                
                รูปแบบที่ต้องการ: {format_type}
                ความยาว: {length} คำ
                
                ควรมี Call-to-Action ท้ายบทความ
                """,
                model="gpt-4.1",
                temperature=0.7,
                max_tokens=800
            ),
            PromptType.CUSTOMER_SUPPORT: PromptConfig(
                template="""
                คุณเป็นพนักงานฝ่ายบริการลูกค้าที่เป็นมิตร
                ชื่อร้าน: {store_name}
                
                คำถามลูกค้า: {customer_question}
                ข้อมูลเพิ่มเติม: {additional_context}
                
                กรุณาตอบในภาษาที่ลูกค้าใช้: {language}
                โทนการตอบ: {tone}
                
                หากไม่สามารถตอบได้ ให้แนะนำช่องทางติดต่ออื่น
                """,
                model="deepseek-chat",
                temperature=0.3,
                max_tokens=500
            ),
            PromptType.SEO_OPTIMIZE: PromptConfig(
                template="""
                ปรับปรุงข้อความต่อไปนี้ให้เหมาะกับ SEO:
                
                ข้อความเดิม: {original_text}
                คีย์เวิร์ดหลัก: {main_keyword}
                คีย์เวิร์ดรอง: {secondary_keywords}
                
                ต้องมี:
                1. Title tag (ไม่เกิน 60 ตัวอักษร)
                2. Meta description (ไม่เกิน 160 ตัวอักษร)
                3. H1-H3 structure
                4. Internal/external link suggestions
                """,
                model="gemini-2.0-flash",
                temperature=0.5,
                max_tokens=1000
            )
        }
    
    def get_chain(self, prompt_type: PromptType) -> LLMChain:
        """สร้าง LLMChain ตามประเภท Prompt"""
        config = self.templates[prompt_type]
        
        llm = ChatOpenAI(
            model=config.model,
            base_url=self.base_url,
            api_key=self.api_key,
            temperature=config.temperature,
            max_tokens=config.max_tokens
        )
        
        template = PromptTemplate(
            template=config.template,
            input_variables=self._get_variables(config.template)
        )
        
        return LLMChain(llm=llm, prompt=template)
    
    def _get_variables(self, template: str) -> List[str]:
        """ดึงตัวแปรจาก template"""
        import re
        return re.findall(r'\{(\w+)\}', template)
    
    def generate_product_description(
        self,
        product_name: str,
        category: str,
        price: float,
        features: str,
        target_audience: str,
        format_type: str = "bullet_points",
        length: int = 200
    ) -> str:
        """สร้างคำอธิบายสินค้าแบบง่าย"""
        chain = self.get_chain(PromptType.PRODUCT_DESCRIPTION)
        return chain.invoke({
            "product_name": product_name,
            "category": category,
            "price": price,
            "features": features,
            "target_audience": target_audience,
            "format_type": format_type,
            "length": length
        })["text"]

ตัวอย่างการใช้งาน

if __name__ == "__main__": library = PromptLibrary(api_key="YOUR_HOLYSHEEP_API_KEY") description = library.generate_product_description( product_name="AirPods Pro 3", category="หูฟังไร้สาย", price=12900, features="Active Noise Cancellation, Transparency Mode, Spatial Audio, MagSafe Charging", target_audience="คนทำงานและคนรักเสียงเพลง", format_type="paragraph", length=150 ) print(description)

การใช้งาน Caching เพื่อลด Token Usage

หนึ่งในวิธีที่มีประสิทธิภาพมากที่สุดในการประหยัดค่าใช้จ่ายคือการใช้ Caching สำหรับ Prompts ที่ถูกเรียกใช้บ่อย
"""
Prompt Caching System
ลด Token Usage สำหรับ Prompts ที่ใช้บ่อย
"""
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.cache import InMemoryCache
from langchain.globals import set_llm_cache
from functools import lru_cache
import hashlib
import json
from typing import Any, Optional

เปิดใช้งาน In-Memory Cache

set_llm_cache(InMemoryCache()) class CachedPromptSystem: """ระบบ Prompt พร้อม Caching""" def __init__(self, api_key: str): self.base_url = "https://api.holysheep.ai/v1" self.api_key = api_key # ใช้ DeepSeek สำหรับงานทั่วไป (ประหยัดที่สุด) self.llm_cheap = ChatOpenAI( model="deepseek-chat", base_url=self.base_url, api_key=api_key, temperature=0.3 ) # ใช้ GPT-4.1 สำหรับงานที่ต้องการคุณภาพสูง self.llm_quality = ChatOpenAI( model="gpt-4.1", base_url=self.base_url, api_key=api_key, temperature=0.5 ) # Template สำหรับ Caching self.cached_templates = {} def register_template( self, name: str, template: str, use_quality_model: bool = False ): """ลงทะเบียน Template สำหรับ Caching""" self.cached_templates[name] = { "template": PromptTemplate( template=template, input_variables=self._extract_vars(template) ), "use_quality": use_quality_model } def _extract_vars(self, template: str) -> list: """ดึงตัวแปรจาก Template""" import re return re.findall(r'\{(\w+)\}', template) def invoke_cached( self, template_name: str, **kwargs ) -> str: """เรียกใช้ Prompt พร้อม Caching (อัตโนมัติ)""" if template_name not in self.cached_templates: raise ValueError(f"Template '{template_name}' ไม่มีอยู่ในระบบ") config = self.cached_templates[template_name] llm = self.llm_quality if config["use_quality"] else self.llm_cheap # Cache key จาก template name + params cache_key = self._generate_cache_key(template_name, kwargs) # สร้าง chain และเรียกใช้ chain = config["template"] | llm # LLM จะทำการ cache อัตโนมัติ result = chain.invoke(kwargs) return result.content if hasattr(result, 'content') else result["text"] def _generate_cache_key(self, template_name: str, params: dict) -> str: """สร้าง Cache Key ที่ไม่ซ้ำกัน""" content = json.dumps({ "template": template_name, "params": params }, sort_keys=True) return hashlib.md5(content.encode()).hexdigest()

ตัวอย่างการใช้งาน

system = CachedPromptSystem(api_key="YOUR_HOLYSHEEP_API_KEY")

ลงทะเบียน Template ที่ใช้บ่อย

system.register_template( name="product_qa", template=""" คุณเป็นผู้เชี่ยวชาญสินค้า สินค้า: {product_name} ราคา: {price} บาท คำถาม: {question} ตอบแบบกระชับ ใช้ภาษาง่ายๆ """, use_quality_model=False # ใช้ DeepSeek ประหยัด )

เรียกใช้ (ครั้งแรกจะเรียก API จริง)

result = system.invoke_cached( template_name="product_qa", product_name="MacBook Pro M4", price=67900, question="เหมาะกับนักออกแบบกราฟิกหรือไม่?" ) print(result)

เรียกซ้ำด้วย params เดิม (จะใช้ Cache ทันที)

result2 = system.invoke_cached( template_name="product_qa", product_name="MacBook Pro M4", price=67900, question="เหมาะกับนักออกแบบกราฟิกหรือไม่?" )

result2 จะมาจาก cache ไม่ต้องเสีย token เพิ่ม!

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

กรณีที่ 1: ImportError: cannot import name 'ChatOpenAI'

ปัญหา: เกิดข้อผิดพลาดเมื่อนำเข้า ChatOpenAI จาก langchain_openai
# ❌ วิธีที่ผิด - จะเกิด ImportError
from langchain.chat_models import ChatOpenAI

✅ วิธีที่ถูกต้อง - ใช้ langchain_openai

from langchain_openai import ChatOpenAI

หรือติดตั้ง package ที่จำเป็น

pip install langchain-openai langchain-community

กรณีที่ 2: APIError หรือ Authentication Error

ปัญหา: ไม่สามารถเชื่อมต่อ API เนื่องจาก base_url หรือ API key ไม่ถูกต้อง
# ❌ วิธีที่ผิด - ใช้ base_url ของ OpenAI โดยตรง
llm = ChatOpenAI(
    model="gpt-4.1",
    base_url="https://api.openai.com/v1",  # ❌ ผิด!
    api_key="sk-xxxx"
)

✅ วิธีที่ถูกต้อง - ใช้ HolySheep AI

llm = ChatOpenAI( model="gpt-4.1", base_url="https://api.holysheep.ai/v1", # ✅ ถูกต้อง api_key="YOUR_HOLYSHEEP_API_KEY", # หรือใช้ environment variable # api_key=os.environ.get("HOLYSHEEP_API_KEY") )

ตรวจสอบว่า API Key ถูกต้อง

import os os.environ["OPENAI_API_KEY"] = "YOUR_HOLYSHEEP_API_KEY" os.environ["OPENAI_BASE_URL"] = "https://api.holysheep.ai/v1"

กรณีที่ 3: Missing Input Variables Error

ปัญหา: PromptTemplate ขาดตัวแปรที่กำหนดใน template
from langchain.prompts import PromptTemplate

❌ วิธีที่ผิด - กำหนด input_variables ไม่ครบ

template = PromptTemplate( template="สินค้า {product} ราคา {price}", input_variables=["product"] # ❌ ขาด "price" )

✅ วิธีที่ถูกต้อง - ตรวจสอบตัวแปรทั้งหมด

import re template_text = "สินค้า {product} ราคา {price} บาท จาก {store}" variables = re.findall(r'\{(\w+)\}', template_text) template = PromptTemplate( template=template_text, input_variables=variables # ✅ ["product", "price", "store"] )

หรือใช้ partial_variables สำหรับค่าคงที่

fixed_template = PromptTemplate( template="สินค้า {product} จากร้าน {store}", input_variables=["product"], partial_variables={"store": "MyShop"} # store จะมีค่าคงที่ )

กรณีที่ 4: Response Format Error กับ Structured Output

ปัญหา: Model ไม่ส่ง output ตาม format ที่กำหนด
from pydantic import BaseModel, Field
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate

class ResponseSchema(BaseModel):
    summary: str = Field(description="สรุปสั้นๆ")
    score: int = Field(description="คะแนน 1-10")
    recommendation: str = Field(description="คำแนะนำ")

❌ วิธีที่ผิด - ลืมเพิ่ม format instructions

bad_template = PromptTemplate( template="วิเคราะห์: {text}", input_variables=["text"] )

✅ วิธีที่ถูกต้อง - เพิ่ม format instructions

parser = PydanticOutputParser(pydantic_object=ResponseSchema) good_template = PromptTemplate( template="วิเคราะห์: {text}\n\n{format_instructions}", input_variables=["text"], partial_variables={"format_instructions": parser.get_format_instructions()} )

หรือใช้ with_structured_output กับ ChatOpenAI โดยตรง

llm = ChatOpenAI( model="gpt-4.1", base_url="https://api.holysheep.ai/v1", api_key="YOUR_HOLYSHEEP_API_KEY" ) structured_llm = llm.with_structured_output(ResponseSchema) result = structured_llm.invoke("ผลิตภัณฑ์นี้ดีมาก ราคาไม่แพง ใช้งานง่าย")

สรุป: เริ่มต้นประหยัดวันนี้

การใช้ LangChain Prompt Template ช่วยให้คุณ: ด้วย HolySheep AI คุณจะได้รับ: เริ่มต้นสร้าง Template ของคุณวันนี้ แล้วคุณจะเห็นความแตกต่างของค่าใช้จ่ายทันที! 👉