我正在尝试使用 Openai API 在 Google 表格中获取完整文章。在 A 列中,我只是提到了主题,并希望在 B 列中获得完整的文章。
这是我正在尝试的
/**
* Use GPT-3 to generate an article
*
* @param {string} topic - the topic for the article
* @return {string} the generated article
* @customfunction
*/
function getArticle(topic) {
// specify the API endpoint and API key
const api_endpoint = 'https://api.openai.com/v1/completions';
const api_key = 'YOUR_API_KEY';
// specify the API parameters
const api_params = {
prompt: topic,
max_tokens: 1024,
temperature: 0.7,
model: 'text-davinci-003',
};
// make the API request using UrlFetchApp
const response = UrlFetchApp.fetch(api_endpoint, {
method: 'post',
headers: {
Authorization: 'Bearer ' + api_key,
'Content-Type': 'application/json',
},
payload: JSON.stringify(api_params),
});
// retrieve the article from the API response
const json = JSON.parse(response.getContentText());
if (json.data && json.data.length > 0) {
const article = json.data[0].text;
return article;
} else {
return 'No article found for the given topic.';
}
}
如何获取文章?
最佳答案
修改点:
当我看到 OpenAI API 的官方文档时,在您的
https://api.openai.com/v1/completions
端点中,似乎返回了以下值。 Ref{ "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "text-davinci-003", "choices": [ { "text": "\n\nThis is indeed a test", "index": 0, "logprobs": null, "finish_reason": "length" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 } }
在
json.data
的情况下,似乎可能需要https://api.openai.com/v1/models
端点要使用的。 Ref而且,json.data[0].text
没有属性。
我认为这可能是您当前问题的原因。如果你想从https://api.openai.com/v1/completions
端点获取text
的值,下面的修改怎么样?
来自:
if (json.data && json.data.length > 0) {
const article = json.data[0].text;
return article;
} else {
return 'No article found for the given topic.';
}
收件人:
if (json.choices && json.choices.length > 0) {
const article = json.choices[0].text;
return article;
} else {
return 'No article found for the given topic.';
}
备注:
- 如果
response.getContentText()
的值不是您期望的值,则此修改可能无法使用。请注意这一点。
引用:
关于python - 使用 Openai 在 Google 表格中获取完整文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74667621/