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中文網其他相關文章!