OpenAI API wrapper for Google Apps Scripts
You can use OpenAIApp.gs as a part of your project.
All parameters names are the same as in the official documentation - https://platform.openai.com/docs/api-reference/introduction. Wrap the method parameters in a js-object and pass it to the method as only one parameter.
varapi_key='**************************************************';varopenai=newOpenAIApp(api_key);varresult=openai.Chat().CreateChatCompletion({model: 'gpt-3.5-turbo',messages: [{role: 'user',content: 'Tell me a joke'}]});Logger.log(result.choices[0].message.content.replace(/^\n\n/,''));To save the context, you can use caching in the script:
functioncache_context(question){varcache=CacheService.getScriptCache();varcache_str=cache.get('cache');varmessages=[];if(cache_str==null){messages=[{"role": "user","content": question}];}else{messages=JSON.parse(cache_str);messages[messages.length]={"role": "user","content": question};}varanswer=openai.Chat().CreateChatCompletion({model: 'gpt-3.5-turbo',messages: messages}).choices[0].message.content.replace(/^\n\n/,'');messages[messages.length]={"role": "assistant","content": answer};while(JSON.stringify(messages).length>100000){vartodelete=messages.shift();}cache.put('cache',JSON.stringify(messages),300);returnanswer;}varapi_key='**************************************************';varopenai=newOpenAIApp(api_key);varresult=openai.Images().CreateImage({prompt: 'Fat black cat'})Logger.log(result.data[0].url);
