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

เทคนิคการแทนที่ตัวแปร

f-strings, .format() และไลบรารีเทมเพลตสำหรับการแสดงผลพรอมป์ต

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

สี่แนวทางของ Python สำหรับการสร้างผลลัพธ์จากแม่แบบ

Python มีหลายวิธีในการสร้างผลลัพธ์จากแม่แบบพรอมต์พร้อมการแทนค่าตัวแปร แต่ละวิธีมีจุดเด่นและข้อแลกเปลี่ยน:

  • สตริง f — แทรกในบรรทัด ทำงานทันที และไม่ต้องนำเข้าอะไร
  • str.format() — ตัวยึดตำแหน่งแบบมีชื่อ และเหมาะกับการตรวจสอบ
  • string.Template — การแทนค่าด้วยเครื่องหมายดอลลาร์อย่างปลอดภัย และรองรับการเติมค่าเพียงบางส่วน
  • Jinja2 — เครื่องมือสร้างแม่แบบเต็มรูปแบบ: เงื่อนไข ลูป ตัวกรอง และการสืบทอดแม่แบบ

การเลือกแนวทางที่เหมาะสมขึ้นอยู่กับความซับซ้อนของแม่แบบ ทักษะของทีม และความต้องการใช้คุณลักษณะขั้นสูง เช่น เงื่อนไขและลูป

แนวทางที่ 1: สตริง f ของ Python

สตริง f เป็นแนวทางที่ง่ายที่สุดสำหรับแม่แบบพรอมต์ที่มีตัวแปรทั้งหมดพร้อมใช้งานขณะสร้างผลลัพธ์:

import openai

client = openai.OpenAI(api_key='sk-...')

def generate_linkedin_post(company, topic, tone, word_count):
    prompt = (
        f'Write a LinkedIn post for {company} about {topic}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        'Professional but conversational. '
        'End with one question to engage readers. '
        'No hashtags. Active voice.'
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

print(generate_linkedin_post(
    company='DataStream Analytics',
    topic='how AI is changing data pipelines',
    tone='enthusiastic but grounded',
    word_count=180
))

แนวทางที่ 2: str.format()

str.format() ทำงานได้ดีเมื่อคุณต้องการจัดเก็บสตริงแม่แบบแยกจากโค้ดที่ใช้เติมค่า ซึ่งมีประโยชน์สำหรับการโหลดแม่แบบจากไฟล์:

import openai

client = openai.OpenAI(api_key='sk-...')

# Template stored as a module-level constant or loaded from a file
SUPPORT_REPLY_TEMPLATE = '''You are a customer support agent for {company_name}.

Respond to this customer message:
---
{customer_message}
---

Tone: {tone}.
Keep the response under {max_words} words.
Do not offer refunds unless the customer explicitly asks.
Always close by asking if there is anything else you can help with.'''

def generate_support_reply(company, message, tone='empathetic and helpful', max_words=150):
    prompt = SUPPORT_REPLY_TEMPLATE.format(
        company_name=company,
        customer_message=message,
        tone=tone,
        max_words=max_words
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

แนวทางที่ 3: string.Template

string.Template จากไลบรารีมาตรฐานของ Python ใช้ตัวยึดตำแหน่งที่มีเครื่องหมายดอลลาร์ ($variable หรือ ${variable}) ข้อดีสำคัญคือ safe_substitute() จะคงตัวแปรที่ขาดหายไว้เป็นข้อความตัวยึดตำแหน่งตามตัวอักษรแทนที่จะทำให้เกิดข้อผิดพลาด จึงรองรับการเติมค่าเพียงบางส่วนได้

from string import Template
import openai

client = openai.OpenAI(api_key='sk-...')

# $ placeholders — safe with code that contains curly braces
BASE_TEMPLATE = Template(
    'Write a $format_type for $audience about $topic. '
    'Tone: $tone. Length: $word_count words. '
    'Active voice. No jargon.'
)

def generate(format_type, audience, topic, tone='professional', word_count=200):
    prompt = BASE_TEMPLATE.substitute(
        format_type=format_type,
        audience=audience,
        topic=topic,
        tone=tone,
        word_count=word_count
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

# Partial fill example — safe_substitute leaves $word_count as-is
partial = BASE_TEMPLATE.safe_substitute(
    format_type='blog post', audience='developers', topic='API design'
)
print(partial)  # $tone and $word_count remain as placeholders

แนวทางที่ 4: พื้นฐาน Jinja2

Jinja2 เป็นเครื่องมือสร้างแม่แบบเต็มรูปแบบ รองรับเงื่อนไข ลูป ตัวกรอง และการสืบทอดแม่แบบ ซึ่งมีความสามารถมากกว่าการแทนค่าสตริงแบบง่ายอย่างมาก:

from jinja2 import Template
import openai

client = openai.OpenAI(api_key='sk-...')

# Jinja2 uses {{ }} for variables and {% %} for logic
JINJA_PROMPT = Template('''
Write a {{content_type}} for {{audience}} about {{topic}}.
Tone: {{tone}}.
{% if include_examples %}
Include {{example_count}} concrete examples.
{% endif %}
{% if word_count %}
Length: {{word_count}} words.
{% else %}
Aim for 200-300 words.
{% endif %}
Active voice. No jargon.
''')

def generate(content_type, audience, topic, tone, include_examples=False, example_count=2, word_count=None):
    prompt = JINJA_PROMPT.render(
        content_type=content_type,
        audience=audience,
        topic=topic,
        tone=tone,
        include_examples=include_examples,
        example_count=example_count,
        word_count=word_count
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

ลูป Jinja2 ในแม่แบบ

ลูปของ Jinja2 ช่วยให้คุณวนซ้ำรายการในแม่แบบได้ ซึ่งมีประโยชน์สำหรับการสร้างพรอมต์หลายรายการจากโครงสร้างข้อมูล:

from jinja2 import Template
import openai

client = openai.OpenAI(api_key='sk-...')

MULTI_PRODUCT_TEMPLATE = Template('''
Write a product comparison for {{audience}}.
Compare the following products:

{% for product in products %}
- {{product.name}}: {{product.description}}
{% endfor %}

Structure: one paragraph per product, then a 2-sentence recommendation.
Tone: {{tone}}. Active voice. No bullet points in paragraphs.
''')

products = [
    {'name': 'Asana', 'description': 'project management with timeline views'},
    {'name': 'Linear', 'description': 'developer-focused issue tracking'},
    {'name': 'Monday.com', 'description': 'visual work management for teams'}
]

prompt = MULTI_PRODUCT_TEMPLATE.render(
    audience='startup founders',
    products=products,
    tone='direct and practical'
)

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': prompt}]
)
print(response.choices[0].message.content)

ตัวกรอง Jinja2

ตัวกรอง Jinja2 ใช้แปลงค่าตัวแปรโดยแทรกอยู่ภายในระหว่างการสร้างผลลัพธ์จากแม่แบบ ตัวกรองในตัวที่มีประโยชน์สำหรับพรอมต์:

  • {{ topic | upper }} — แปลงหัวข้อเป็นตัวพิมพ์ใหญ่
  • {{ word_count | default(200) }} — ใช้ค่า 200 หากไม่ได้ระบุ word_count
  • {{ audience | title }} — แปลงสตริงกลุ่มเป้าหมายเป็นรูปแบบตัวพิมพ์ใหญ่ต้นคำ
  • {{ items | join(', ') }} — รวมรายการด้วยเครื่องหมายจุลภาค

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

การโหลดแม่แบบจากไฟล์

สำหรับแม่แบบขนาดใหญ่หรือซับซ้อน การจัดเก็บไว้ในไฟล์ข้อความแยกต่างหากช่วยให้โค้ด Python สะอาด Jinja2 จัดการเรื่องนี้ได้ดีด้วยสภาพแวดล้อมและ FileSystemLoader:

from jinja2 import Environment, FileSystemLoader
import openai

client = openai.OpenAI(api_key='sk-...')

# Load all templates from the 'prompts/' directory
env = Environment(loader=FileSystemLoader('prompts/'))

def render_template(template_name, variables):
    '''Load and render a .j2 template file with the given variables.'''
    template = env.get_template(template_name)
    return template.render(**variables)

def generate_from_file(template_name, variables):
    prompt = render_template(template_name, variables)

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

# Usage: load prompts/blog_post.j2 and fill with variables
result = generate_from_file('blog_post.j2', {
    'topic': 'API rate limiting strategies',
    'audience': 'backend engineers',
    'tone': 'technical and direct',
    'word_count': 500
})
print(result)

การเลือกแนวทางที่เหมาะสม

เลือกแนวทางการแทนค่าให้เหมาะกับความซับซ้อนของแม่แบบ:

  • สตริง f — สคริปต์สั้น ๆ การทำงานอัตโนมัติเฉพาะครั้ง หรือแม่แบบที่สั้นพอจะอ่านได้ภายในบรรทัด
  • str.format() — แม่แบบที่จัดเก็บไว้ โค้ดของทีม หรือกรณีที่ต้องการให้เกิด KeyError เมื่อตัวแปรขาดหาย
  • string.Template — เมื่อเนื้อหาอาจมีวงเล็บปีกกา (เช่น ตัวอย่างโค้ด) หรือจำเป็นต้องเติมค่าเพียงบางส่วน
  • Jinja2 — แม่แบบซับซ้อนที่มีเงื่อนไข ลูป หลายไฟล์ หรือทีมที่มีประสบการณ์ด้านการสร้างแม่แบบ

การออกแบบซับซ้อนเกินจำเป็นเป็นความเสี่ยงที่เกิดขึ้นจริง ควรเลือกใช้ Jinja2 เฉพาะเมื่อจำเป็นต้องใช้คุณลักษณะขั้นสูงอย่างแท้จริง

ความปลอดภัยของแม่แบบ: การโจมตีด้วยการแทรกคำสั่ง

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

มาตรการป้องกัน:

  • ตรวจสอบและทำความสะอาดตัวแปรทั้งหมดที่ผู้ใช้ระบุก่อนแทนค่า
  • สำหรับข้อมูลนำเข้าที่ผู้ใช้เห็น ให้ครอบตัวแปรด้วยตัวคั่น: "ข้อมูลนำเข้าของผู้ใช้คือ: ---{user_input}---"
  • ใช้การกรองผลลัพธ์เพื่อตรวจจับและปฏิเสธคำตอบที่ดูเหมือนทำตามคำสั่งที่ถูกแทรก
  • อย่าให้ค่าที่ผู้ใช้ระบุเข้าถึงตัวแปรของพรอมต์ระบบโดยเด็ดขาด

การทดสอบผลลัพธ์จากแม่แบบ

ทดสอบการสร้างผลลัพธ์จากแม่แบบแยกจากการเรียกใช้ API เสมอ ตรวจสอบสตริงผลลัพธ์ก่อนส่งไปยังโมเดล:

def test_template_render():
    test_cases = [
        {'topic': 'cloud security', 'audience': 'CTOs', 'tone': 'formal', 'word_count': 300},
        {'topic': 'ML pipelines', 'audience': 'data scientists', 'tone': 'technical', 'word_count': 500},
        # Edge cases
        {'topic': '', 'audience': 'developers', 'tone': 'casual', 'word_count': 100},  # empty topic
        {'topic': 'AI' * 100, 'audience': 'all', 'tone': 'brief', 'word_count': 50},  # very long topic
    ]

    TEMPLATE = 'Write a {word_count}-word {tone} article about {topic} for {audience}. Active voice.'

    for i, case in enumerate(test_cases):
        try:
            rendered = TEMPLATE.format(**case)
            assert len(rendered) > 0, 'Empty render'
            print(f'Case {i+1} OK: {len(rendered)} chars')
        except (KeyError, AssertionError) as e:
            print(f'Case {i+1} FAILED: {e}')

test_template_render()

ตรวจสอบความรู้: เทคนิคการแทนค่า

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

แนวทางการแทนค่าใดเหมาะกับสถานการณ์นี้ที่สุด

สรุป: เทคนิคการแทนค่าตัวแปร

Python มีสี่แนวทางสำหรับการสร้างผลลัพธ์จากแม่แบบพรอมต์ ได้แก่ สตริง f (แทรกในบรรทัดและเรียบง่าย), str.format() (ตัวยึดตำแหน่งแบบมีชื่อและเกิด KeyError เมื่อตัวแปรขาดหาย), string.Template (ไวยากรณ์เครื่องหมายดอลลาร์และการเติมค่าเพียงบางส่วนอย่างปลอดภัย) และ Jinja2 (เครื่องมือเต็มรูปแบบที่มีเงื่อนไข ลูป ตัวกรอง และการโหลดไฟล์)

เลือกแนวทางให้เหมาะกับความซับซ้อน: ใช้สตริง f สำหรับสคริปต์สั้น ๆ ใช้ str.format() สำหรับแม่แบบที่จัดเก็บไว้ ใช้ string.Template เมื่อเนื้อหามีวงเล็บปีกกา และใช้ Jinja2 เมื่อต้องการเงื่อนไข ลูป หรือแม่แบบที่ใช้ไฟล์เสริม ทดสอบการสร้างผลลัพธ์แยกจากการเรียกใช้ API เสมอ

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

บทเรียน “เทคนิคการแทนที่ตัวแปร” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “เทคนิคการแทนที่ตัวแปร”

f-strings, .format() และไลบรารีเทมเพลตสำหรับการแสดงผลพรอมป์ต คุณปฏิบัติ 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