สร้างฟังก์ชัน get_response() แบบสอง prompt
แบบฝึกหัดต่อไปนี้จะอิงการเรียก endpoint chat.completions ของ OpenAI API โดยใช้ prompt สองรายการ ได้แก่ system prompt และ user prompt เพื่อเตรียมความพร้อม ในแบบฝึกหัดนี้จะสร้างฟังก์ชัน get_response() แบบสอง prompt ที่รับ prompt สองตัวเป็น input (system_prompt และ user_prompt) แล้วคืนค่า response เป็น output จากนั้นนำฟังก์ชันนี้ไปทดลองใช้กับตัวอย่างที่ต้องการ
แพ็กเกจ OpenAI ถูกโหลดไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Prompt Engineering กับ OpenAI API
คำแนะนำการฝึกหัด
- กำหนด role และ content ของแต่ละข้อความใน list
messages - ทดลองใช้ฟังก์ชันโดยส่ง
system_promptและuser_promptตามที่ต้องการ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
client = OpenAI(api_key="")
def get_response(system_prompt, user_prompt):
# Assign the role and content for each message
messages = [{"role": ____, "content": ____},
{"role": ____, "content": ____}]
response = client.chat.completions.create(
model="gpt-4o-mini", messages= messages, temperature=0)
return response.choices[0].message.content
# Try the function with a system and user prompts of your choice
response = get_response("____", "____")
print(response)