
回复
近日,OpenAI 推出了全新的 AI Agent 智能体 Function Calling 2.0 使用指南,此次更新使得文档篇幅缩减了一半,并且引入了一系列关键的最佳实践。作为打造高效 AI Agent 智能体的核心技能之一,正确运用Function Calling 对于开发强大的 AI Agent 智能体应用具有至关重要的作用。因此,今天我就来为大家揭秘这次更新的精华内容!
文章中清晰地阐述了 Function Calling 的两个核心应用场景:
第一、数据获取(Fetching Data)
第二、执行动作(Taking Action)
此次更新最为关键的是推出了一系列实用的最佳实践,下面我们来聚焦于其中的几项:
第一、编写明确的函数定义
# 好的示例
def get_weather(location: str):
"""获取指定位置的当前温度
Args:
location: 城市和国家,例如:'北京, 中国'
"""
pass
# 糟糕的示例
def toggle_light_switch(on: bool, off: bool):
"""这个设计允许无效状态的存在"""
pass
第二、遵循软件工程的最佳实践指南
第三、尽可能减少大模型的负担
# 不推荐
def get_orders(user_id: str):
pass
# 推荐
def get_orders():
# 在代码中传递user_id
pass
第四、精简函数数量,维持高效性;
第一、工具选择模式(tool_choice)
# 自动模式(默认)
tool_choice="auto" # 可以调用零个、一个或多个函数
# 强制模式
tool_choice="required" # 必须调用至少一个函数
# 指定函数
tool_choice={
"type": "function",
"function": {"name": "get_weather"}
} # 强制调用特定函数
第二、严格模式(Strict Mode)
{
"type": "function",
"function": {
"name": "get_weather",
"strict": True, # 启用严格模式
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string"
},
"units": {
"type": ["string", "null"], # 可选参数
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location", "units"],
"additionalProperties": false
}
}
}
OpenAI 进一步提升了流式处理的能力,使得能够即时展现函数调用的实时过程。
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京今天天气如何?"}],
tools=tools,
stream=True
)
for chunk in stream:
delta = chunk.choices[0].delta
print(delta.tool_calls) # 实时显示函数调用进度
此次更新主要目的是分享了一系列最佳实践。随着 o1-mini 即将实现对Function Calling 的支持(已获官方确认),昨日还推出了 tasks 功能。因此,可以展望在2025年见证真正的 AI Agent 智能体的诞生。
本文转载自公众号玄姐聊AGI 作者:玄姐