client.chat.completions.create
方法中的 tools
参数说明
在 OpenAI 的最新 API(适用于 gpt-4-turbo
和 gpt-3.5-turbo
)中,tools
取代了 functions
,用于支持 Function Calling(函数调用),使 GPT 可以调用外部 API 或执行特定功能。
1. tools
参数作用
tools
允许 GPT 识别特定功能(API 调用、数据库查询等),并根据用户输入 自动调用合适的工具。
区别
functions
和tools
:
functions
已 被tools
取代,功能基本相同,但tools
适用于更通用的工具调用。tools
适用于 函数调用(API 调用)、代码执行、数据库查询等。
2. tools
参数格式
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "查询天气的城市"
}
},
"required": ["city"]
}
}
}
]
type
:"function"
表示调用的是一个函数(未来可能支持更多类型)function
: 定义了可供 GPT 调用的 APIname
: 函数名称description
: 说明函数的作用parameters
: 规定函数的入参格式(JSON 结构)
3. tools
在 client.chat.completions.create
方法中的用法
示例:调用 get_weather
API
import openai
import json
import requests
openai.api_key = "your-api-key"
# 定义工具(Tools)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type"