|
昨天OpenAI发布了全新的Function Calling指南,这次更新不仅让文档缩短了50%,还带来了一些重要的最佳实践。作为Agent的核心能力之一,Function Calling的正确使用对于构建强大的AI Agents应用至关重要。所以今天给家人们分享一下这次更新的重点内容! Function Calling的两大核心应用文中明确指出,Function Calling主要有两个核心应用场景:
#好的示例 defget_weather(location:str): """获取指定位置的当前温度 Args: location:城市和国家,例如:'北京, 中国' """ pass
#糟糕的示例 deftoggle_light_switch(on:bool,off:bool): """这个设计允许无效状态的存在""" pass
- 让函数直观且符合最小惊讶原则(维基百科上叫:Principle of least astonishment, https://en.wikipedia.org/wiki/Principle_of_least_astonishment)
- 通过"实习生测试":如果一个实习生只看函数定义就能正确使用,说明设计的不错
#不推荐 defget_orders(user_id:str): pass
#推荐 defget_orders(): #在代码中传递user_id pass
重要的配置选项
 #自动模式(默认) tool_choice="auto"#可以调用零个、一个或多个函数
#强制模式 tool_choice="required"#必须调用至少一个函数
#指定函数 tool_choice={ "type":"function", "function":{"name":"get_weather"} }#强制调用特定函数
{ "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 )
forchunkinstream: delta=chunk.choices[0].delta print(delta.tool_calls)#实时显示函数调用进度
最后这次的更新,主要是提供了一些的最佳实践。随着o1-mini即将支持Function Calling(官方确认),昨天还开始发布了tasks的功能,可以期待在2025年看到真正的Agents |