การพัฒนาแอปพลิเคชันที่ใช้ LLM (Large Language Model) ในยุคปัจจุบันต้องการความยืดหยุ่นในการจัดการ Prompt อย่างมีประสิทธิภาพ บทความนี้จะสอนการออกแบบ Prompt Template Engine โดยใช้ Jinja2 Template Engine ร่วมกับ LLM API เพื่อสร้างระบบ Dynamic Prompt ที่รองรับการปรับแต่งได้หลากหลาย โดยใช้ HolySheep AI เป็นตัวอย่างหลักในการเรียกใช้งาน

ตารางเปรียบเทียบบริการ LLM API

รายการเปรียบเทียบ HolySheep AI API อย่างเป็นทางการ บริการรีเลย์อื่นๆ
อัตราแลกเปลี่ยน ¥1 = $1 (ประหยัด 85%+) อัตราปกติของ OpenAI/Anthropic มักมีค่าธรรมเนียมเพิ่มเติม
วิธีชำระเงิน WeChat / Alipay บัตรเครดิตระหว่างประเทศ หลากหลาย แต่ซับซ้อน
ความหน่วง (Latency) <50ms 50-200ms 100-500ms
เครดิตฟรี มีเมื่อลงทะเบียน ไม่มี ขึ้นอยู่กับโปรโมชัน
GPT-4.1 $8/MTok $60/MTok $40-50/MTok
Claude Sonnet 4.5 $15/MTok $90/MTok $50-70/MTok
Gemini 2.5 Flash $2.50/MTok $15/MTok $10-12/MTok
DeepSeek V3.2 $0.42/MTok ไม่มี $0.50-0.80/MTok

ทำไมต้องใช้ Template Engine?

เมื่อพัฒนาแอปพลิเคชันที่ต้องสร้าง Prompt หลายรูปแบบ การเขียน Prompt แบบ Hard-code จะทำให้:

Jinja2 ช่วยแก้ปัญหาเหล่านี้ด้วยระบบ Template ที่ทรงพลัง รองรับตัวแปร, เงื่อนไข, และ Loop

การติดตั้งและตั้งค่าพื้นฐาน

pip install jinja2 openai requests

โครงสร้างพื้นฐานของ Prompt Template Engine

import os
from jinja2 import Environment, BaseLoader
from openai import OpenAI

class PromptTemplateEngine:
    """เครื่องมือจัดการ Prompt Template ด้วย Jinja2"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
        """
        สร้างอินสแตนซ์ของ Template Engine
        
        Args:
            api_key: API Key จาก HolySheep AI
            base_url: URL ของ API (ต้องเป็น https://api.holysheep.ai/v1)
        """
        self.client = OpenAI(
            api_key=api_key,
            base_url=base_url
        )
        self.env = Environment(loader=BaseLoader())
    
    def register_template(self, name: str, template_str: str):
        """ลงทะเบียน Template ใหม่"""
        self.env.template_vars[name] = template_str
        return self
    
    def render(self, template_str: str, **kwargs) -> str:
        """เรนเดอร์ Template พร้อมตัวแปร"""
        template = self.env.from_string(template_str)
        return template.render(**kwargs)
    
    def call_llm(self, prompt: str, model: str = "gpt-4.1", 
                 temperature: float = 0.7, max_tokens: int = 2000):
        """
        เรียกใช้ LLM ผ่าน HolySheep API
        
        Args:
            prompt: Prompt ที่เรนเดอร์แล้ว
            model: โมเดลที่ต้องการใช้งาน
            temperature: ค่าความสุ่มของคำตอบ (0-2)
            max_tokens: จำนวน Token สูงสุดของคำตอบ
        
        Returns:
            ข้อความคำตอบจาก LLM
        """
        response = self.client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": "คุณเป็นผู้ช่วย AI ที่เป็นประโยชน์"},
                {"role": "user", "content": prompt}
            ],
            temperature=temperature,
            max_tokens=max_tokens
        )
        return response.choices[0].message.content


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

if __name__ == "__main__": engine = PromptTemplateEngine( api_key="YOUR_HOLYSHEEP_API_KEY", base_url="https://api.holysheep.ai/v1" ) print("✅ Prompt Template Engine พร้อมใช้งานแล้ว")

Template หลายรูปแบบสำหรับงานต่างๆ

from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from enum import Enum

class PromptType(Enum):
    """ประเภทของ Prompt Template"""
    SUMMARIZE = "summarize"
    TRANSLATE = "translate"
    ANALYZE = "analyze"
    GENERATE = "generate"
    CLASSIFY = "classify"

@dataclass
class PromptTemplate:
    """โครงสร้างข้อมูลของ Template"""
    name: str
    type: PromptType
    system_prompt: str
    user_template: str
    description: str = ""
    examples: List[Dict[str, str]] = field(default_factory=list)

class AdvancedPromptEngine(PromptTemplateEngine):
    """ระบบ Template ขั้นสูงที่รองรับหลายรูปแบบ"""
    
    # Template คอลเลกชัน
    TEMPLATES: Dict[str, PromptTemplate] = {
        "summarize_th": PromptTemplate(
            name="สรุปบทความ (ไทย)",
            type=PromptType.SUMMARIZE,
            system_prompt="คุณเป็นผู้เชี่ยวชาญในการสรุปบทความ คุณต้องสรุปให้กระชับและครอบคลุม",
            user_template="""สรุปบทความต่อไปนี้ให้ได้ใจความสำคัญ 3-5 ย่อหน้า:

หัวข้อ: {{ title }}
ผู้เขียน: {{ author }}
วันที่: {{ date }}

เนื้อหา:
{{ content }}

รูปแบบการสรุป:
- ความยาว: {{ length | default("กลาง") }}
- เน้น: {{ focus | default("เนื้อหาหลัก") }}
{% if include_keywords %}
- คำสำคัญ: {{ keywords | join(", ") }}
{% endif %}"""
        ),
        "translate_multi": PromptTemplate(
            name="แปลภาษาหลายรูปแบบ",
            type=PromptType.TRANSLATE,
            system_prompt="คุณเป็นนักแปลมืออาชีพที่รองรับหลายภาษา",
            user_template="""แปลข้อความต่อไปนี้เป็น {{ target_language }}:

ข้อความต้นฉบับ ({{ source_language }}):
{{ text }}

{% if context %}
บริบทเพิ่มเติม: {{ context }}
{% endif %}

{% if tone %}
โทนของการแปล: {{ tone }}
{% endif %}

{% if technical %}
คำศัพท์เทคนิคที่ต้องใช้: {{ technical_terms | join(", ") }}
{% endif %}"""
        ),
        "sentiment_analyze": PromptTemplate(
            name="วิเคราะห์ความรู้สึก",
            type=PromptType.ANALYZE,
            system_prompt="คุณเป็นผู้เชี่ยวชาญด้านการวิเคราะห์ความรู้สึกจากข้อความ",
            user_template="""วิเคราะห์ความรู้สึกจากข้อความต่อไปนี้:

ข้อความ: "{{ text }}"
แหล่งที่มา: {{ source | default("ไม่ระบุ") }}

{% if include_aspects %}
วิเคราะห์เฉพาะด้านต่อไปนี้:
{% for aspect in aspects %}
  - {{ aspect }}
{% endfor %}
{% endif %}

รูปแบบการตอบกลับ: {{ output_format | default("JSON") }}"""
        ),
        "code_review": PromptTemplate(
            name="ตรวจสอบโค้ด",
            type=PromptType.ANALYZE,
            system_prompt="คุณเป็น Senior Developer ที่มีประสบการณ์ในการตรวจสอบโค้ด",
            user_template="""ตรวจสอบโค้ดต่อไปนี้และให้คำแนะนำ:

ภาษาโปรแกรม: {{ language }}
ไฟล์: {{ filename }}

```{{ language }}
{{ code }}
```

{% if focus_areas %}
เน้นตรวจสอบด้านต่อไปนี้:
{% for area in focus_areas %}
  - {{ area }}
{% endfor %}
{% endif %}

{% if security_check %}
⚠️ ตรวจสอบด้านความปลอดภัยด้วย
{% endif %}

รูปแบบการตอบกลับ: {{ format | default("detailed") }}"""
        )
    }
    
    def render_prompt(self, template_name: str, **context) -> Dict[str, str]:
        """เรนเดอร์ Prompt จาก Template ที่กำหนด"""
        if template_name not in self.TEMPLATES:
            raise ValueError(f"Template '{template_name}' ไม่พบในระบบ")
        
        template = self.TEMPLATES[template_name]
        
        # เรนเดอร์ System และ User Prompt
        system_prompt = template.system_prompt
        user_prompt = self.render(template.user_template, **context)
        
        return {
            "system": system_prompt,
            "user": user_prompt,
            "type": template.type.value
        }
    
    def process_with_template(self, template_name: str, 
                               model: str = "gpt-4.1",
                               **context) -> str:
        """เรนเดอร์และส่ง Prompt ไปประมวลผลกับ LLM"""
        prompts = self.render_prompt(template_name, **context)
        
        response = self.client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": prompts["system"]},
                {"role": "user", "content": prompts["user"]}
            ],
            temperature=0.7,
            max_tokens=2000
        )
        
        return response.choices[0].message.content


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

if __name__ == "__main__": engine = AdvancedPromptEngine( api_key="YOUR_HOLYSHEEP_API_KEY" ) # ตัวอย่างที่ 1: สรุปบทความ summary_result = engine.process_with_template( "summarize_th", title="การพัฒนา AI ในประเทศไทย", author="ดร.สมชาย ใจดี", date="15 มกราคม 2569", content="บทความนี้กล่าวถึงแนวโน้มการใช้ AI ในภาคธุรกิจ...", length="สั้น", focus="บทสรุปผู้บริหาร" ) # ตัวอย่างที่ 2: แปลภาษา translate_result = engine.process_with_template( "translate_multi", text="Hello, how are you today?", source_language="อังกฤษ", target_language="ไทย", tone="เป็นทางการ" ) # ตัวอย่างที่ 3: วิเคราะห์ความรู้สึก sentiment_result = engine.process_with_template( "sentiment_analyze", text="สินค้าดีมาก แต่การจัดส่งช้านิดหน่อย", source="รีวิว Shopee", include_aspects=True, aspects=["คุณภาพสินค้า", "การจัดส่ง", "บริการ"], output_format="JSON" ) print("✅ ตัวอย่างการใช้งานเสร็จสมบูรณ์")

การใช้ Loops และ Conditions ใน Template

class DynamicPromptBuilder:
    """ตัวสร้าง Prompt แบบ Dynamic ที่ซับซ้อน"""
    
    def __init__(self, api_key: str):
        self.client = OpenAI(
            api_key=api_key,
            base_url="https://api.holysheep.ai/v1"
        )
        self.env = Environment(loader=BaseLoader())
    
    def build_multi_language_prompt(self, 
                                    content: str,
                                    languages: List[str],
                                    purpose: str) -> str:
        """สร้าง Prompt สำหรับแปลหลายภาษาพร้อมกัน"""
        
        template_str = """ทำการแปลเนื้อหาต่อไปนี้เป็น {{ languages | length }} ภาษา:

{% raw %}
เนื้อหาต้นฉบับ:
{{ content }}

{% for lang in languages %}
=== {{ lang | upper }} ===
{{ loop.index }}. แปลเป็น {{ lang }}:

{% endfor %}

ข้อกำหนด:
- รักษาโทนและนัยสำคัญของต้นฉบับ
{% if purpose == "marketing" %}
- ใช้ภาษาที่ดึงดูดความสนใจ
{% elif purpose == "technical" %}
- ใช้ศัพท์เทคนิคที่ถูกต้อง
{% else %}
- ใช้ภาษาที่เข้าใจง่าย
{% endif %}
{% endraw %}"""
        
        template = self.env.from_string(template_str)
        return template.render(
            content=content,
            languages=languages,
            purpose=purpose
        )
    
    def build_analysis_prompt(self,
                              text: str,
                              analysis_types: List[str],
                              include_examples: bool = True) -> str:
        """สร้าง Prompt สำหรับวิเคราะห์หลายมิติ"""
        
        template_str = """วิเคราะห์ข้อความต่อไปนี้ในมิติที่กำหนด:

ข้อความ: "{{ text }}"

{% raw %}
{% for analysis_type in analysis_types %}
---
{{ loop.index }}. {{ analysis_type | upper }}
{% if analysis_type == "sentiment" %}
   - ระบุความรู้สึก (บวก/ลบ/เป็นกลาง)
   - ระดับความเข้มข้น (1-10)
   - อธิบายเหตุผล
{% elif analysis_type == "entities" %}
   - ระบุบุคคล สถานที่ องค์กร
   - ระบุความสัมพันธ์
{% elif analysis_type == "keywords" %}
   - คำสำคัญ 5-10 คำ
   - คำซ้ำ/คำเชื่อม
{% elif analysis_type == "summary" %}
   - สรุป 2-3 ประโยค
   - หัวข้อหลัก
{% endif %}
{% endfor %}

{% if include_examples %}
---
หมายเหตุ: หากมีตัวอย่างประกอบ จะช่วยให้เข้าใจบริบทได้ดีขึ้น
{% endif %}

{% if language == "th" %}
คำตอบเป็นภาษาไทย
{% elif language == "en" %}
คำตอบเป็นภาษาอังกฤษ
{% else %}
คำตอบเป็นภาษาที่เหมาะสม
{% endif %}
{% endraw %}"""
        
        template = self.env.from_string(template_str)
        return template.render(
            text=text,
            analysis_types=analysis_types,
            include_examples=include_examples
        )
    
    def build_conversation_prompt(self,
                                 conversation_history: List[Dict],
                                 current_message: str,
                                 user_profile: Optional[Dict] = None) -> List[Dict]:
        """สร้าง Prompt สำหรับการสนทนาต่อเนื่อง"""
        
        messages = []
        
        # System Prompt ที่ปรับตาม User Profile
        system_template = """คุณกำลังสนทนากับผู้ใช้{% if user_profile.name %} ชื่อ {{ user_profile.name }}{% endif %}
{% if user_profile.preference == "formal" %}
- ใช้ภาษาที่เป็นทางการ
{% elif user_profile.preference == "casual" %}
- ใช้ภาษาที่เป็นกันเอง
{% endif %}
{% if user_profile.language == "th" %}
- ตอบเป็นภาษาไทย
{% endif %}
{% if user_profile.expertise %}
- ผู้ใช้มีความเชี่ยวชาญระดับ: {{ user_profile.expertise }}
{% endif %}"""
        
        template = self.env.from_string(system_template)
        system_prompt = template.render(user_profile=user_profile or {})
        messages.append({"role": "system", "content": system_prompt})
        
        # เพิ่มประวัติการสนทนา
        for msg in conversation_history[-5:]:  # เอาเฉพาะ 5 ข้อความล่าสุด
            messages.append({
                "role": msg.get("role", "user"),
                "content": msg.get("content", "")
            })
        
        # เพิ่มข้อความปัจจุบัน
        messages.append({"role": "user", "content": current_message})
        
        return messages


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

if __name__ == "__main__": builder = DynamicPromptBuilder("YOUR_HOLYSHEEP_API_KEY") # ตัวอย่าง: แปลหลายภาษา multi_lang_prompt = builder.build_multi_language_prompt( content="Artificial Intelligence is transforming the world.", languages=["ไทย", "ญี่ปุ่น", "เกาหลี", "เวียดนาม"], purpose="marketing" ) # ตัวอย่าง: วิเคราะห์หลายมิติ analysis_prompt = builder.build_analysis_prompt( text="บริษัท ABC ประกาศเปิดตัวผลิตภัณฑ์ AI ใหม่ที่สำนักงานใหญ่กรุงเทพฯ", analysis_types=["sentiment", "entities", "keywords"], include_examples=True ) # ตัวอย่าง: สนทนาต่อเนื่อง messages = builder.build_conversation_prompt( conversation_history=[ {"role": "user", "content": "สอนเรื่อง Machine Learning หน่อย"}, {"role": "assistant", "content": "Machine Learning คือ..."}, {"role": "user", "content": "แล้ว Deep Learning ต่างกันยังไง?"} ], current_message="Neural Network คืออะไร?", user_profile={ "name": "สมชาย", "preference": "casual", "language": "th", "expertise": "intermediate" } ) print("✅ Dynamic Prompt Builder พร้อมใช้งาน")

ระบบ Caching และ Optimization

import hashlib
import json
import time
from functools import lru_cache
from typing import Optional, Any

class CachedPromptEngine:
    """Prompt Engine พร้อมระบบ Cache สำหรับลดค่าใช้จ่าย"""
    
    def __init__(self, api_key: str, cache_ttl: int = 3600):
        self.client = OpenAI(
            api_key=api_key,
            base_url="https://api.holysheep.ai/v1"
        )
        self.env = Environment(loader=BaseLoader())
        self.cache: Dict[str, Dict[str, Any]] = {}
        self.cache_ttl = cache_ttl  # Cache นาน 1 ชั่วโมง
    
    def _generate_cache_key(self, template: str, **context) -> str:
        """สร้าง Cache Key จาก Template และ Context"""
        data = {
            "template": template,
            "context": context
        }
        return hashlib.sha256(
            json.dumps(data, sort_keys=True).encode()
        ).hexdigest()
    
    def _get_from_cache(self, key: str) -> Optional[str]:
        """ดึงข้อมูลจาก Cache"""
        if key in self.cache:
            entry = self.cache[key]
            if time.time() - entry["timestamp"] < self.cache_ttl:
                entry["hits"] += 1
                return entry["result"]
            else:
                del self.cache[key]
        return None
    
    def _save_to_cache(self, key: str, result: str):
        """บันทึกผลลัพธ์ลง Cache"""
        self.cache[key] = {
            "result": result,
            "timestamp": time.time(),
            "hits": 0
        }
    
    def cached_call(self, 
                    template_str: str,
                    model: str = "gpt-4.1",
                    use_cache: bool = True,
                    **context) -> str:
        """เรียก LLM พร้อมระบบ Cache"""
        
        if use_cache:
            cache_key = self._generate_cache_key(template_str, **context)
            cached_result = self._get_from_cache(cache_key)
            
            if cached_result:
                print(f"📦 ใช้ Cache (Key: {cache_key[:8]}...)")
                return cached_result
        
        # Render Prompt
        template = self.env.from_string(template_str)
        rendered_prompt = template.render(**context)
        
        # เรียก LLM
        print(f"🔄 เรียก API: {model}")
        start_time = time.time()
        
        response = self.client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": rendered_prompt}],
            temperature=0.7,
            max_tokens=2000
        )
        
        result = response.choices[0].message.content
        elapsed = time.time() - start_time
        print(f"⏱️ ใช้เวลา: {elapsed*1000:.0f}ms")
        
        # บันทึก Cache
        if use_cache:
            self._save_to_cache(cache_key, result)
        
        return result
    
    def get_cache_stats(self) -> Dict[str, Any]:
        """ดูสถิติการใช้ Cache"""
        total_hits = sum(entry["hits"] for entry in self.cache.values