I'm trying to get full article in Google Sheet using Openai API. In column A I just mention the topic and want to get full article in column B.
Here is what I'm trying
/**
* 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.';
}
}
How can I get the article?
When I saw the official document of OpenAI API, in your endpoint of https://api.openai.com/v1/completions
, it seems that the following value is returned. 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
}
}
In the case of json.data
, it seems that the endpoint of https://api.openai.com/v1/models
might be required to be used. Ref And, there is no property of json.data[0].text
.
I thought that this might be the reason for your current issue. If you want to retrieve the values of text
from the endpoint of https://api.openai.com/v1/completions
, how about the following modification?
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()
is not your expected values, this modification might not be able to be used. Please be careful about this.