const functions = {
getCurrentTime: function(){
return new Date().toLocaleTimeString()
}
}
然后在ChatCompletion传入functions参数,写上getCurrentTime函数名以及描述,这个目的是让GPT知道我们有哪些函数可以使用。然后做第一次请求
const MODELS = {
gpt35Turbo0613: "gpt-3.5-turbo-0613",
gpt4Turbo0613: "gpt-4-0613",
}
const getChatCompletion = async ({messageList}: {
messageList: Array<ChatCompletionRequestMessage>
}) => {
if(!messageList) return;
let result = ``
const getCurrentTimeFunObj = {
name: `getCurrentTime`,
description: `Get the current time`,
parameters: {
type: `object`,
properties: {},
required: []
},
}
try {
const response = await openai.createChatCompletion({
model: MODELS.gpt35Turbo0613,
messages: messages,
functions: [getCurrentTimeFunObj],
temperature: 0,
})
const { choices } = response?.data || {}
result = choices[0].message || {}
} catch (e) {
console.log(`getChatCompletion error Info`, e)
}
return result
}
// prompt: "please tell me current time"
let messageList = [{
role: "user",
content: "现在几点了?"
}]
const firstResponse = await getChatCompletion({messageList})
当我们在messageList中出现询问当前时间的时候,由于在调用中含有functions,根据描述GPT判断可以使用function。GPT就会以 "function_call" 来终止并返回function_call字段,让我们调用 getCurrentTime方法。
{
id: `chatcmpl-1`,
object: 'chat.completion',
created: 1623662570,
model: 'gpt-3.5-turbo-0613',
choices: [{
index: 0,
message: {
role: 'assistant',
content: null,
function_call: { name: "getCurrentTime", argumentss: '{}' }
},
finish_reason: 'function_call',
}],
user: { prompt_tokens: 43, completion_tokens: 7, total_tokens: 50 },
}
const responseCallback = async ({respsone, messageList}: {
respsone: ChatCompletionResponse,
messageList: Array<ChatCompletionRequestMessage>
}) => {
let result = ``;
const { choices } = respsone?.data || {}
const {finish_reason, message} = choices?.[0] || {}
if(finish_reason == "function_call" && message?.function_call){
const {name: fnName, arguments} = message.function_call || {}
const fn = functions[fnName]
if(fn){
const fnResult = fn(arguments)
messageList.push({
role: 'assistant',
content: null,
function_call: { name: fnName, argumentss: arguments }
});
messageList.push({
role: 'function',
name: fnName,
content: JSON.stringify({result: fnResult}),
})
result = await openai.createChatCompletion({messageList})
}
}
return result
}
{
message: {
role: "assistant",
content: "现在时间是13:57:50",
}
}