OpenAI发布全新函数调用指南,助开发者扩展模型能力!此指南整合了用户反馈,篇幅缩短50%,内容更清晰,并包含最佳实践、文档内函数生成以及使用天气API的完整示例。OpenAI致力于简化AI工具,使其更易于开发者使用,从而更有效地利用函数调用功能。
OpenAI发布全新函数调用指南!
我们根据您的反馈做出了重要改进:
– 篇幅缩短50%,更清晰易懂 – 新增最佳实践(详情见下文?) – 支持文档内函数生成! – 提供使用天气API的完整功能示例
查看指南并分享您的想法… pic.twitter.com/Id89E9PEff
— ilan bigio (@ilanbigio) January 13, 2025
函数调用允许OpenAI模型与开发者定义的工具交互,使其能够执行超出文本或音频生成的更多任务。以下是简化的流程:
该图片展示了开发者和AI模型之间函数调用的流程。以下是分步说明:
另请阅读:支持函数调用的6大顶级LLM
让我们来看一个使用get_weather函数的实际示例。此函数检索给定坐标的当前温度。
<code>import requests def get_weather(latitude, longitude): response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m") data = response.json() return data['current']['temperature_2m']</code>
<code>from openai import OpenAI import json client = OpenAI(api_key="sk-api_key”) tools = [{ "type": "function", "function": { "name": "get_weather", "description": "获取提供的坐标(摄氏度)的当前温度。", "parameters": { "type": "object", "properties": { "latitude": {"type": "number"}, "longitude": {"type": "number"} }, "required": ["latitude", "longitude"], "additionalProperties": False }, "strict": True } }] messages = [{"role": "user", "content": "今天巴黎的天气怎么样?"}] completion = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, )</code>
<code>tool_call = completion.choices[0].message.tool_calls[0] args = json.loads(tool_call.function.arguments) result = get_weather(args["latitude"], args["longitude"])</code>
<code># 附加模型的工具调用消息 messages.append(completion.choices[0].message) # 将结果消息作为字符串附加 messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps({"temperature": result}) # 将结果转换为JSON字符串 }) # 创建第二个聊天完成 completion_2 = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, )</code>
<code>print(completion_2.choices[0].message.content)</code>
输出:
<code>巴黎目前的温度是-2.8°C。</code>
为了帮助您充分利用函数调用,以下是一些专业技巧:
了解更多信息,请访问OpenAI。
OpenAI改进后的函数调用指南使开发者能够无缝集成自定义工具,使AI更易于访问和使用。通过简化流程、提供清晰的示例以及优先考虑用户反馈,OpenAI使开发者能够进行创新并构建利用AI全部潜力的解决方案,从而推动现实世界的应用和创造力。
以上是签署OpenAI函数调用指南的详细内容。更多信息请关注PHP中文网其他相关文章!