Streaming กับ Function Calls
เราได้เห็นแล้วว่า LLM ที่รองรับ function calling นั้นเปิดประตูสู่ use case มากมายเพียงใด และยังมี event types เฉพาะของตัวเองด้วย ความสามารถนี้มีประโยชน์มากสำหรับการแสดงผลแบบ real-time ให้ผู้ใช้เห็นขณะที่โมเดลกำลังเตรียมเรียกใช้ tool หรือสำหรับการ logging เพื่อติดตามการใช้งาน tool
ฟังก์ชัน convert_timezone() ที่ใช้แปลงวันและเวลาระหว่าง timezone ต่างๆ รวมถึง list tools ที่มี function definition สำหรับ Responses API ได้ถูกกำหนดไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำงานกับ OpenAI Responses API
คำแนะนำการฝึกหัด
- เติม context manager สำหรับ streaming โดยเรียก
client.responses.create()พร้อมส่งโมเดล"gpt-5.4-mini",prompt, และ listtools - ภายใน loop ให้ตรวจสอบ event ประเภท
"function_call_arguments.delta" - เพิ่มเงื่อนไขสำหรับตรวจสอบ event ประเภท
"function_call_arguments.done" - เพิ่มเงื่อนไขสุดท้ายเพื่อตรวจสอบว่าประเภท event คือ
"response.completed"แล้วพิมพ์ข้อความแจ้งว่าการทำงานเสร็จสมบูรณ์
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
prompt = "What time is 2:30pm on January 20th in New York in Tokyo time?"
# Open the streaming connection and enable tool-calling
with ____ as stream:
for event in stream:
# Filter for function call arguments delta events
if ____:
print(f"\nTool args streaming: {event.delta}")
# Filter for function call arguments complete events
elif ____:
print("Tool call args complete.")
# Filter for response completed events
elif ____:
print("\n--- Completed ---")