Technology

copilot prompt engineering

copilot prompt engineering
copilot prompt engineering | SiamCafe Blog
2025-08-31· อ. บอม — SiamCafe.net· 11,806 คำ

Copilot Prompt Engineering

GitHub Copilot Prompt Engineering AI Code Completion Context Comment Test-first Few-shot VS Code JetBrains Copilot Chat Advanced

TechniqueHowWhen to UseEffectiveness
Comment-drivenเขียน Comment อธิบายก่อนฟังก์ชันใหม่ทุกตัวสูง
Type-firstเขียน Type/Interface ก่อนComplex data structuresสูงมาก
Test-firstเขียน Test ก่อน ImplementationTDD workflowสูงมาก
Few-shotให้ตัวอย่าง 1-2 ตัวRepetitive patternsสูง
Step-by-stepเขียน Algorithm เป็นขั้นตอนComplex algorithmsสูง
Context filesเปิดไฟล์ที่เกี่ยวข้องMulti-file projectsกลาง-สูง

Basic Techniques

# === Comment-driven Development ===

# Technique 1: Descriptive comments before functions
# Bad: (vague comment)
# # Process data
# def process(data):

# Good: (specific comment)
# # Parse CSV string into list of dictionaries
# # Each row becomes a dict with headers as keys
# # Skip empty rows and strip whitespace from values
# # Returns: List[Dict[str, str]]
# def parse_csv(csv_string: str) -> list[dict[str, str]]:

# Technique 2: Function signature as specification
# def calculate_compound_interest(
#     principal: float,
#     annual_rate: float,
#     years: int,
#     compounds_per_year: int = 12
# ) -> float:
#     """Calculate compound interest.
#     Formula: A = P(1 + r/n)^(nt)
#     Returns the final amount including principal.
#     """

# Technique 3: Type hints drive suggestions
# from typing import TypedDict
# class UserProfile(TypedDict):
#     id: int
#     name: str
#     email: str
#     is_active: bool
#     created_at: datetime
#
# def create_user_profile(name: str, email: str) -> UserProfile:
#     # Copilot can now generate correct implementation

from dataclasses import dataclass

@dataclass
class PromptPattern:
    pattern: str
    example: str
    copilot_output: str
    quality: str

patterns = [
    PromptPattern("Descriptive Comment",
        "# Sort list of users by last login date descending",
        "users.sort(key=lambda u: u.last_login, reverse=True)",
        "High — clear intent, single purpose"),
    PromptPattern("Type Signature",
        "def merge_dicts(base: dict, override: dict) -> dict:",
        "return {**base, **override}",
        "High — types constrain output"),
    PromptPattern("Docstring Spec",
        '"""Retry function up to 3 times with exponential backoff"""',
        "Full retry decorator with sleep(2**attempt)",
        "Very high — detailed spec"),
    PromptPattern("Test-first",
        "assert calculate_tax(100, 0.07) == 7.0",
        "def calculate_tax(amount, rate): return amount * rate",
        "Very high — test defines behavior"),
    PromptPattern("Example-driven",
        "# Example: slugify('Hello World') -> 'hello-world'",
        "def slugify(text): return re.sub(r'\\s+', '-', text.lower())",
        "High — concrete example"),
]

print("=== Prompt Patterns ===")
for p in patterns:
    print(f"  [{p.pattern}] Quality: {p.quality}")
    print(f"    Prompt: {p.example}")
    print(f"    Output: {p.copilot_output}")

Advanced Techniques

# === Advanced Copilot Techniques ===

# Few-shot Prompting — give examples, Copilot continues the pattern
# def format_phone(phone: str) -> str:
#     """Format phone number.
#     Examples:
#         format_phone("0812345678") -> "081-234-5678"
#         format_phone("021234567") -> "02-123-4567"
#         format_phone("+66812345678") -> "+66 81-234-5678"
#     """
# Copilot generates implementation matching all examples

# Step-by-step Algorithm
# def find_longest_palindrome(s: str) -> str:
#     # Step 1: Handle edge cases (empty string, single char)
#     # Step 2: Try each character as center of palindrome
#     # Step 3: Expand outward while characters match
#     # Step 4: Track the longest palindrome found
#     # Step 5: Return the longest palindrome substring
# Copilot fills in each step

# Copilot Chat Commands
# /explain    — Explain selected code
# /fix        — Fix bugs in selected code
# /test       — Generate tests for selected code
# /doc        — Generate documentation
# /optimize   — Suggest optimizations
# @workspace  — Ask about entire project
# #file       — Reference specific file
# #selection  — Reference selected code

# Negative prompting
# # Parse JSON config file
# # Do NOT use eval() or exec()
# # Do NOT catch generic Exception
# # Use json.load with proper error handling

@dataclass
class ChatCommand:
    command: str
    description: str
    example: str
    output: str

commands = [
    ChatCommand("/explain",
        "อธิบาย Code ที่เลือก",
        "Select complex regex, type /explain",
        "Step-by-step explanation of regex"),
    ChatCommand("/fix",
        "แก้ Bug ใน Code ที่เลือก",
        "Select buggy function, type /fix",
        "Fixed version with explanation"),
    ChatCommand("/test",
        "สร้าง Test สำหรับ Code ที่เลือก",
        "Select function, type /test",
        "Unit tests with edge cases"),
    ChatCommand("/doc",
        "สร้าง Documentation",
        "Select class, type /doc",
        "Docstring with params and examples"),
    ChatCommand("@workspace",
        "ถามเกี่ยวกับทั้ง Project",
        "@workspace how does auth work?",
        "Overview of auth flow across files"),
    ChatCommand("#file",
        "อ้างอิงไฟล์เฉพาะ",
        "Explain #file:auth.py login flow",
        "Explanation with file context"),
]

print("\n=== Copilot Chat Commands ===")
for c in commands:
    print(f"  [{c.command}] {c.description}")
    print(f"    Example: {c.example}")
    print(f"    Output: {c.output}")

Best Practices and Pitfalls

# === Best Practices ===

@dataclass
class Practice:
    category: str
    do: str
    dont: str
    reason: str

practices = [
    Practice("Comments",
        "เขียน Comment เฉพาะเจาะจง บอก Input Output Edge case",
        "เขียน Comment กว้างๆ เช่น 'process data'",
        "Copilot ต้องการ Context ชัดเจนเพื่อสร้าง Code ถูกต้อง"),
    Practice("Function Size",
        "แบ่งเป็นฟังก์ชันเล็กๆ 10-20 บรรทัด",
        "ให้ Copilot สร้างฟังก์ชันยาว 100+ บรรทัด",
        "ฟังก์ชันเล็กมีโอกาสถูกต้องมากกว่า"),
    Practice("Verification",
        "ตรวจสอบทุก Suggestion อ่าน Code ก่อน Accept",
        "Accept ทุก Suggestion โดยไม่อ่าน",
        "Copilot อาจสร้าง Code ที่ดูถูกแต่ Logic ผิด"),
    Practice("Security",
        "ตรวจ SQL Injection XSS Input Validation",
        "เชื่อว่า Copilot สร้าง Secure Code เสมอ",
        "Copilot ไม่ได้ออกแบบมาเพื่อ Security เป็นหลัก"),
    Practice("Context",
        "เปิดไฟล์ที่เกี่ยวข้องใน Tab ก่อนเขียน",
        "เขียนโดยไม่เปิด Related files",
        "Copilot ใช้ Open tabs เป็น Context เพิ่มเติม"),
    Practice("Secrets",
        "ใช้ Environment Variables สำหรับ API Keys",
        "เขียน API Key ใน Comment หรือ Code",
        "Prompt อาจถูกส่งไป Server อาจรั่วไหล"),
]

print("=== Best Practices ===")
for p in practices:
    print(f"  [{p.category}]")
    print(f"    DO: {p.do}")
    print(f"    DON'T: {p.dont}")
    print(f"    Why: {p.reason}")

# Productivity metrics
metrics = {
    "Code Acceptance Rate": "ยอมรับ Suggestion 25-35% ของทั้งหมด (ปกติ)",
    "Time Saved": "ลดเวลาเขียน Code 30-55% (GitHub Research)",
    "Bug Rate": "เท่าเดิมหรือลดลงเล็กน้อย ถ้า Review ดี",
    "Learning Curve": "1-2 สัปดาห์ เรียนรู้ Prompt Pattern",
    "Best Languages": "Python, JavaScript, TypeScript ได้ผลดีสุด",
}

print(f"\n\nProductivity Metrics:")
for k, v in metrics.items():
    print(f"  [{k}]: {v}")

เคล็ดลับ

GitHub Copilot คืออะไร

AI Pair Programmer GitHub OpenAI VS Code JetBrains Code Completion Python JavaScript TypeScript $10 $19 Copilot Chat ถามคำถาม

Prompt Engineering สำหรับ Copilot ทำอย่างไร

Comment ชัดเจน ชื่อ Function Variable Context Import Tab Type Hints Docstring Interface Test-first แบ่งฟังก์ชันเล็ก

เทคนิคขั้นสูงมีอะไรบ้าง

Few-shot ตัวอย่าง Pattern Negative Prompting Step-by-step Algorithm Copilot Chat /explain /fix /test /doc @workspace #file Slash Commands

ข้อควรระวังคืออะไร

ตรวจ Code Bug Logic ผิด Security SQL Injection XSS Library เก่า License Training Data Coding Standard Secret API Key Code Review

สรุป

Copilot Prompt Engineering Comment-driven Type-first Test-first Few-shot Chat Commands Context Security Review Best Practices Production

📖 บทความที่เกี่ยวข้อง

prompt engineering ต้องเรียนอะไรอ่านบทความ → copilot ai คืออ่านบทความ → WordPress Headless Chaos Engineeringอ่านบทความ → Apollo Server Platform Engineeringอ่านบทความ → SSE Security Chaos Engineeringอ่านบทความ →

📚 ดูบทความทั้งหมด →