การผสานรวม Function-Calling Tools
คุณได้สร้างเครื่องมือแปลงเขตเวลาโดยใช้ฟังก์ชัน convert_timezone() และกำหนดรูปแบบไว้ในรูปแบบ tool ของ OpenAI แล้ว ขั้นตอนต่อไปคือการ implement workflow การเรียกฟังก์ชันให้ครบสมบูรณ์ โดย client ได้รับการ initialize ไว้แล้ว และลิสต์ tools มีนิยามของเครื่องมือแปลงเขตเวลาอยู่แล้ว รวมถึงฟังก์ชัน convert_timezone() ก็พร้อมใช้งานแล้วเช่นกัน
ลิสต์ messages ได้ถูกสร้างไว้แล้วพร้อม input จากผู้ใช้ที่ต้องการข้อมูลเขตเวลาจากเครื่องมือ convert_timezone ของคุณ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำงานกับ OpenAI Responses API
คำแนะนำการฝึกหัด
- วนลูปผ่าน output items ของ response จาก Responses request แรก เพื่อตรวจสอบว่ามี
'function_call'ที่เรียกไปยัง'convert_timezone'หรือไม่ จากนั้นเรียกใช้convert_timezone()พร้อม unpack อาร์กิวเมนต์จาก item แล้วเก็บผลลัพธ์ไว้ในtimezone_result - เพิ่มข้อความที่มี type เป็น
'function_call_output'เข้าไปในลิสต์ messages โดยใส่ผลลัพธ์ที่ได้จากconvert_timezone() - สร้าง Responses request สุดท้ายโดยส่ง messages ที่มีผลลัพธ์ของฟังก์ชัน พร้อมส่งลิสต์
toolsเข้าไปด้วยเช่นเดิม
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
messages = [{"role": "user", "content": "What time is 2:30pm on January 20th in New York in Tokyo time?"}]
response = client.responses.create(model="gpt-5.4-mini", input=messages, tools=tools)
messages += response.output
# Process function calls and execute the timezone conversion
for item in response.output:
if item.type == "____":
if item.name == "____":
timezone_result = ____(**json.loads(item.arguments))
# Append function output to messages
messages.append({"type": "____", "call_id": item.call_id, "output": json.dumps({"convert_timezone": ____})})
# Make second API request with function results
response = client.responses.create(model="gpt-5.4-mini", input=____, tools=____)
print(response.output_text)