gpt4 book ai didi

javascript - chatGPT API函数调用

转载 作者:行者123 更新时间:2023-12-02 22:47:20 29 4
gpt4 key购买 nike

我正在尝试设置函数来调用我最近一直在从事的一个项目,但我似乎无法让它工作

我查找了文档,但只找到了无法很好地解释它的 YouTube 视频。我尝试过运行各种示例,但没有任何效果对我有用。这就是我所拥有的:与 API 的基本通信有效,但函数调用不返回任何内容。如果有人可以提供帮助,我们将不胜感激。

<!DOCTYPE html>
<html>


<head>

<script>
function sendRequest() {

// API endpoint URL
const apiUrl = 'https://api.openai.com/v1/chat/completions';

// Your API key
const apiKey = 'API_Key';

// Get the user input
const userInput = document.getElementById('userInput').value;


async function lookupTime() {
fetch("http://worldtimeapi.org/api/timezone/America/Chicago")
.then(response => response.json())
.then(data => {
const currentTime = new Date(data.datetime);
const timeString = currentTime.toLocaleTimeString();
console.log(timeString);
Current_Time = timeString;
})
.catch(error => {
console.error("Error fetching time:", error);
});
}

// Request payload
const payload = {
model: 'gpt-3.5-turbo-0613',
messages: [{
role: 'system',
content: 'be a helpfull assistant'
}, {
role: 'user',
content: userInput
}],
functions: [{
name: "lookupTime",
description: "get the current time",
parameters: {
type: "object", // specify that the parameter is an object
properties: {
TimeInput: {
type: "string", // specify the parameter type as a string
description: "The Current_Time variable"
}
},
required: ["TimeInput"] // specify that the location parameter is required
}
}],

max_tokens: 100,
temperature: 0.7
};

// Make the API call
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(payload)
})
.then(response => response.json())
.then(data => {
// Handle the response
console.log(data);

// Show the response in the output element
const outputElement = document.getElementById('output');
outputElement.textContent = data.choices[0].message.content;
})
.catch(error => {
// Handle any errors
console.error(error);
});
}
</script>
</head>

<body>
<input type="text" id="userInput" placeholder="Type your message...">
<button onclick="sendRequest()">Send Request</button>
<div id="output"></div>


</body>

</html>

它输出以下信息,但没有文本响应:

(finish_reason: "function_call", index: 0, message: content: null, function_call: arguments: "{\n "TimeInput": "Current_Time"\n}", name: "lookupTime").

但是,它实际上并没有调用该函数。如果我问它一个问题,它会正确输出所需的文本,并填充内容字段。

最佳答案

您的代码包含两个问题:

  1. 代码不处理 GPT 想要调用您指定的函数的情况。在这种情况下,响应不包含“content”属性,因此您会收到运行时错误。
  2. lookupTime 函数的函数签名(对我来说)没有意义,并且与 JavaScript 实现的定义不匹配。实际函数不带参数,但您提供的 GPT 签名描述了一个参数。

我已经更正了您的代码并对其进行了一些更改,以便它可以完成有用的工作。然而,实现仍然不完整,并且缺乏任何严重的错误处理等。

新的lookupTime函数需要一个城市作为参数并返回该城市的时间。请注意,它只接受与美洲地区的时区数据库名称相匹配的少数城市(例如菲尼克斯)。

async function lookupTime(city) {
try {
const response = await fetch(`http://worldtimeapi.org/api/timezone/America/${city}`);
const data = await response.json();
const currentTime = new Date(data.datetime);
const timeString = currentTime.toLocaleTimeString();
console.log(timeString);
return timeString;
}
catch (error) {
console.error("Error fetching time:", error);
}
}

然后更改可供 GPT 使用的函数签名以反射(reflect)新参数:

async function sendRequest() {
const apiUrl = 'https://api.openai.com/v1/chat/completions';
const apiKey = 'YOUR API KEY';
const userInput = document.getElementById('userInput').value;

let payload = {
model: 'gpt-3.5-turbo-0613',
messages: [{
role: 'system',
content: 'You are a helpful assistant.'
}, {
role: 'user',
content: userInput
}],
functions: [{
name: "lookupTime",
description: "get the current time",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "The city for which the current time is to be retrieved."
}
},
required: ["city"]
}
}],

max_tokens: 100,
temperature: 0.7
};

最后,我们需要更改与 GPT 通信的处理方式。首先,我们需要发送初始请求。然后我们需要响应GPT的响应。如果它想要调用一个函数,我们必须解释该响应,调用该函数,然后使用 (a) 先前的消息和 (b) 包含函数调用响应的新消息再次调用 GPT。只有这样 GPT 才会知道结果并返回预期的响应。

因此,我们需要调用 API 两次。最简单的方法是将 API 调用移至函数 chatWithGpt 并允许该函数递归调用自身:

    async function chatWithGpt() {
console.log(payload);
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(payload)
});

const data = await response.json();
console.log(data);
const choice = data.choices[0];

if (choice.finish_reason === 'function_call' && choice.message.function_call.name === 'lookupTime') {
const arguments = JSON.parse(choice.message.function_call.arguments);
const timeString = await lookupTime(arguments.city);
payload.messages.push({
role: "function",
name: "lookupTime",
content: JSON.stringify({ time: timeString })
});
return chatWithGpt();
}
else {
const outputElement = document.getElementById('output');
outputElement.textContent = data.choices[0].message.content;
}
}
try {
chatWithGpt();
}
catch (error) {
console.error(error);
}
}

为了获得更好的重现性,我将温度更改为 0。然后您将收到给定问题的以下答案:

Q: What time is it in Phoenix?

A: The current time in Phoenix is 02:11:08.

调用该函数来获取上下文信息甚至是明智的:

Q: Do I need a flashlight out in Phoenix now?

A: Based on the current time in Phoenix (02:13 AM), it is nighttime. If you are planning to go outside, it is recommended to have a flashlight with you for better visibility in the dark.

有关进一步的解释,我建议阅读 blog entry OpenAI 关于新函数 API 以及 API documentation .

关于javascript - chatGPT API函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76561836/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com