AI Engineering Academy · บทเรียน

ปลายทางการเติมข้อความสนทนา

ทำความเข้าใจอาร์เรย์ข้อความที่มีบทบาท system, user และ assistant สร้างพรอมต์แรกของคุณ และตีความออบเจ็กต์การตอบกลับที่ส่งกลับมาจาก API

บทเรียน 2 จาก 413 ขั้นตอน

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

สถาปัตยกรรมอาร์เรย์ข้อความ

จุดเชื่อมต่อ Chat Completions ทำงานด้วยอาร์เรย์ข้อความ: รายการของแต่ละช่วงการสนทนา โดยแต่ละรายการมีบทบาท (system, user หรือ assistant) โมเดลไม่มีสถานะ ดังนั้นคุณจึงต้องส่งประวัติทั้งหมดไปทุกครั้ง

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'system', 'content': 'You are a concise Python tutor.'},
        {'role': 'user', 'content': 'What is a list comprehension?'}
    ]
)

print(response.choices[0].message.content)

บทบาท system: การกำหนดพฤติกรรม

ข้อความ system คือคันโยกที่มีอิทธิพลมากที่สุด โดยกำหนดบุคลิก กฎ และรูปแบบของโมเดลก่อนที่ผู้ใช้จะพิมพ์แม้แต่คำเดียว ควรใช้เวลาเตรียมส่วนนี้ให้ดี เพราะจะกำหนดผลลัพธ์ทุกอย่าง ดูโค้ดได้เลย

system_prompt = '''You are a customer support agent for TechShop.
You help customers with: order tracking, returns, and product questions.
You do NOT discuss pricing changes or competitor products.
Always respond in 2-3 sentences maximum.
If you cannot help, say: 'Let me connect you with a human agent.'
'''

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'system', 'content': system_prompt},
        {'role': 'user', 'content': 'Where is my order #12345?'}
    ]
)

การจัดการบทสนทนาหลายช่วง

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

history = [
    {'role': 'system', 'content': 'You are a helpful assistant.'}
]

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

print(chat('My name is Alice.'))
print(chat('What is my name?'))  # model remembers 'Alice'

โครงสร้างของการตอบกลับจาก API

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

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': 'Say hello in one word.'}]
)

# Accessing response fields
print('Content:', response.choices[0].message.content)
print('Finish reason:', response.choices[0].finish_reason)  # 'stop'
print('Model:', response.model)  # exact version like gpt-4o-mini-2024-07-18
print('Prompt tokens:', response.usage.prompt_tokens)
print('Completion tokens:', response.usage.completion_tokens)
print('Total tokens:', response.usage.total_tokens)

ทำความเข้าใจ finish_reason

finish_reason จะบอกสาเหตุที่การสร้างข้อความหยุดลง ค่า 'stop' หมายถึงเสร็จสมบูรณ์ ส่วน 'length' หมายถึงถึงค่า max_tokens แล้วคำตอบจึงถูกตัดกลางคัน ควรตรวจสอบค่านี้เสมอ เพราะการถูกตัดอาจเป็นข้อผิดพลาดที่ไม่แสดงให้เห็น

def safe_completion(messages, max_tokens=500):
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=messages,
        max_tokens=max_tokens
    )
    choice = response.choices[0]
    
    if choice.finish_reason == 'length':
        print(f'WARNING: Response was truncated at {max_tokens} tokens!')
    elif choice.finish_reason == 'content_filter':
        print('WARNING: Response blocked by content filter!')
        return None
    
    return choice.message.content

การเลือกโมเดลที่เหมาะสม

เลือกโมเดลให้เหมาะกับงาน gpt-4o มีความสามารถสูงสำหรับการให้เหตุผลที่ซับซ้อน ส่วน gpt-4o-mini มีราคาถูกกว่ามากและรองรับงานส่วนใหญ่ได้ดี ควรเปรียบเทียบประสิทธิภาพก่อนสรุปว่าโมเดลที่ใหญ่กว่าจะดีกว่าเสมอ

# Model comparison guidance
models = {
    'gpt-4o': {
        'use_for': 'Complex reasoning, code generation, nuanced analysis',
        'input_cost_per_1M': 2.50,  # USD
        'output_cost_per_1M': 10.00
    },
    'gpt-4o-mini': {
        'use_for': 'Classification, extraction, summarization, Q&A',
        'input_cost_per_1M': 0.15,
        'output_cost_per_1M': 0.60
    }
}
# gpt-4o is ~17x more expensive on input tokens

ประเภทเนื้อหาในข้อความ

เนื้อหาของข้อความอาจไม่ได้มีเพียงข้อความเท่านั้น สำหรับโมเดลด้านการมองเห็นอย่าง gpt-4o คุณสามารถส่งรายการที่ผสมทั้งข้อความและรูปภาพได้ จึงสามารถถามคำถามเกี่ยวกับแผนภูมิหรือภาพหน้าจอได้

# Sending an image to a vision-capable model
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[
        {
            'role': 'user',
            'content': [
                {
                    'type': 'text',
                    'text': 'What is in this image? Describe in one sentence.'
                },
                {
                    'type': 'image_url',
                    'image_url': {'url': 'https://example.com/photo.jpg'}
                }
            ]
        }
    ]
)

พารามิเตอร์ n: การสร้างคำตอบหลายรายการ

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

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': 'Name the capital of Germany.'}],
    n=3,  # generate 3 independent completions
    temperature=0.5
)

for i, choice in enumerate(response.choices):
    print(f'Completion {i+1}: {choice.message.content}')

# Check if all completions agree (confidence signal)
answers = [c.message.content.strip() for c in response.choices]
print('All agree:', len(set(answers)) == 1)

การจัดการคำตอบในรูปแบบสตริง

หากต้องการดึงคำตอบออกมาเป็นข้อความ เส้นทางจะเป็น response.choices[0].message.content เสมอ ควรห่อการทำงานนี้ไว้ในฟังก์ชันช่วย และตรวจสอบค่า None ด้วย เพราะค่านี้อาจเกิดขึ้นเมื่อมีการเรียกใช้เครื่องมือหรือตัวกรอง

def get_completion(prompt, system='You are a helpful assistant.', model='gpt-4o-mini'):
    '''Simple helper that returns the response text as a string.'''
    response = client.chat.completions.create(
        model=model,
        messages=[
            {'role': 'system', 'content': system},
            {'role': 'user', 'content': prompt}
        ]
    )
    content = response.choices[0].message.content
    if content is None:
        raise ValueError(f'No content in response. Finish reason: {response.choices[0].finish_reason}')
    return content

result = get_completion('Explain recursion in one sentence.')
print(result)

การตรวจสอบคำขอและคำตอบดิบ

กำลังแก้ไขปัญหาคำตอบแปลก ๆ อยู่ใช่ไหมครับ/คะ ลองตรวจสอบคำขอและคำตอบดิบ การตั้งค่า OPENAI_LOG=debug จะแสดงเนื้อหาทั้งหมดในเทอร์มินัลของคุณ ซึ่งเป็นวิธีที่เร็วที่สุดในการดูว่ามีอะไรถูกส่งผ่านเครือข่าย

import json
import httpx

# Enable debug logging (shows full request/response)
import os
os.environ['OPENAI_LOG'] = 'debug'

# Or use a custom logging client:
class LoggingClient(httpx.Client):
    def send(self, request, *args, **kwargs):
        print('REQUEST:', request.method, request.url)
        print('BODY:', json.loads(request.content))
        response = super().send(request, *args, **kwargs)
        print('STATUS:', response.status_code)
        return response

การสร้างลูปสนทนาอย่างง่าย

ตอนนี้คุณสามารถสร้างลูปสนทนาอย่างง่ายได้แล้ว: เก็บรายการข้อความ ใช้ append เพิ่มแต่ละช่วง ส่งทั้งหมดไป แล้วทำซ้ำ รูปแบบเรียบง่ายนี้เป็นพื้นฐานของแอปสนทนาทุกตัวบน API ดูตัวอย่างได้ในโค้ด

import openai

client = openai.OpenAI()

SYSTEM_PROMPT = 'You are a helpful assistant. Be concise.'

def simple_chat_loop():
    messages = [{'role': 'system', 'content': SYSTEM_PROMPT}]
    print('Chat started. Type "quit" to exit.')

    while True:
        user_input = input('You: ').strip()
        if user_input.lower() == 'quit':
            break
        if not user_input:
            continue

        messages.append({'role': 'user', 'content': user_input})

        response = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=messages,
            max_tokens=500
        )

        assistant_reply = response.choices[0].message.content
        messages.append({'role': 'assistant', 'content': assistant_reply})
        print(f'Assistant: {assistant_reply}\n')

print('Example chat loop defined. Run simple_chat_loop() to start.')

ตรวจสอบความเข้าใจ

ทดสอบความเข้าใจแนวคิดวิศวกรรม AI จากบทเรียนนี้

ทบทวนบทเรียน

คุณได้เรียนรู้แกนหลักของการสนทนาแล้ว: อาร์เรย์ข้อความควบคุมบทสนทนา และการตอบกลับจะมีเนื้อหา finish_reason และจำนวนโทเคน ขั้นต่อไป: พารามิเตอร์

เริ่มต้นได้ฟรี

เรียนรู้ Python ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

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

บทเรียน “ปลายทางการเติมข้อความสนทนา” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “ปลายทางการเติมข้อความสนทนา”

ทำความเข้าใจอาร์เรย์ข้อความที่มีบทบาท system, user และ assistant สร้างพรอมต์แรกของคุณ และตีความออบเจ็กต์การตอบกลับที่ส่งกลับมาจาก API คุณปฏิบัติ AI Engineering Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Engineering Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Engineering Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “ปลายทางการเติมข้อความสนทนา” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Engineering Academy นี้ได้ไหม

ได้ บทเรียน AI Engineering Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตั้งค่าสภาพแวดล้อม Python
  2. ปลายทางการเติมข้อความสนทนา
  3. ควบคุมพฤติกรรมของโมเดลด้วยพารามิเตอร์
  4. การจัดการข้อผิดพลาดและขีดจำกัดอัตราการเรียกใช้
← กลับไปที่ AI Engineering Academy