前言
6月13日,Openai发布了一次重大更新,具体更新大纲如下
- Chat Completions API 中的新函数调用功能
- gpt-4和gpt-3.5-turbo的更新更易于操纵的版本
- 新的 16k 上下文版本gpt-3.5-turbo(与标准 4k 版本相比)
- 我们最先进的嵌入模型的成本降低了 75%
- gpt-3.5-turbo模型价格降低了25%,输入令牌的成本降低
- gpt-3.5-turbo-0301和gpt-4-0314模型宣布弃用时间表
最大的更新内容!
众所周知,之前AutoGPT的横空出世引起了很多人的轰动!它是通过GPT来进行一些任务的执行,其核心的原理是通过给GPT设置一个完善的Prompt(类似合约)来完成的,但是实际的作用并不理想!
但这次官方的API更新,可以说几乎可以完整的使用这个功能,API支持通过函数调用的方式,来让AI根据场景决定是否需要执行某些函数,比如查询天气,查询机票,酒店等等!
什么是函数调用
根据OpenAi的官方文档,可以通过调用API的时候,按照约定的格式,将支持的函数列表传递,AI会根据消息内容,自行决定是否需要调用函数来完成一些任务。
具体的对接案例
接下来我们使用国内的API反代来对接尝试!下面是一个简单的查询天气的对接的案例!
//定义获取天气的函数
function get_current_weather(params){
return {
location:params.location,
temperature: 72
}
}
//第一步,执行函数请求
fetch('https://api.mxcks.com/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'sk-************************',
},
body: JSON.stringify({
model: 'gpt-3.5-turbo', // 模型唯一标识
functions: [
{
name: 'get_current_weather',
description: 'Get the current weather in a given location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city and state, e.g. San Francisco, CA',
},
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['location'],
},
}
],
messages: [
{
role: 'user', // 只可以传 user 或者 assistant,表示是谁说的话
content: '北京今日天气', // 消息内容
},
],
}),
}).then(async (response) => {
if (response.status === 200) {
const result = await response.json()
console.log(result)
//返回体内容
// {
// statusCode: 200,
// data: {
// role: 'assistant',
// content: null,
// function_call: {
// name: 'get_current_weather',
// arguments: '{\n "location": "Beijing"\n}'
// }
// }
// }
//判断返回正常并且需要执行函数调用
if(result.statusCode === 200 && result.data.function_call){
//执行函数调用
const function_response = get_current_weather(JSON.parse(result.data.function_call.arguments))
const second_response = await fetch('https://api.mxcks.com/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'sk-************************',
},
body: JSON.stringify({
model: 'gpt-3.5-turbo', // 模型唯一标识
messages: [
{
role: 'user', // 只可以传 user 或者 assistant,表示是谁说的话
content: '北京今日天气', // 消息内容
},
{
role: 'function', // 函数执行的内容需要传递function
content: JSON.stringify(function_response), // 函数执行完毕的内容,必须要为JSON字符串
name:'get_current_weather' //执行的函数名称,当role为function时,这里必传!
},
],
}),
})
}
} else {
console.log(await response.json()); //获取报错信息
}
});