基于函数调用的流式输出
您已经看到,支持函数调用的 LLM 能解锁很多用例,并且它们有自己的事件类型。这对于在模型准备调用工具时向用户提供实时反馈,或用于记录日志以跟踪工具使用情况,都非常有用。
此前您已定义了用于在不同时区之间转换日期时间的 convert_timezone() 函数;同时还为 Responses API 准备好了包含该函数定义的 tools 列表。
本练习是课程的一部分
使用 OpenAI Responses API
练习说明
- 在流式上下文管理器中,调用
client.responses.create(),传入模型"gpt-5.4-mini"、prompt以及tools列表以完成设置。 - 在循环中,检查是否为
"function_call_arguments.delta"事件。 - 添加条件以检查
"function_call_arguments.done"事件。 - 最后添加条件以检查事件类型是否为
"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 ---")