Created
May 5, 2023 20:15
-
-
Save rossmartin/fab247746840431713155b6f42316a35 to your computer and use it in GitHub Desktop.
Server side handler for ios app store review scraper that does analysis on them with chatgpt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction | |
import { NextApiRequest, NextApiResponse } from 'next'; | |
import { getReviews } from 'app-store-scraper-reviews'; | |
import { Configuration, OpenAIApi } from 'openai'; | |
const configuration = new Configuration({ | |
apiKey: process.env.OPENAI_API_KEY, | |
}); | |
const openai = new OpenAIApi(configuration); | |
const sleep = (time: number) => | |
new Promise((resolve) => setTimeout(resolve, time)); | |
export default async function handler( | |
req: NextApiRequest, | |
res: NextApiResponse | |
) { | |
const { country, appId, appName, numberOfReviews } = req.body; | |
const reviews = await getReviews({ | |
country, | |
appId, | |
appName, | |
numberOfReviews, | |
}); | |
const blockTokenSize = 2500; | |
const blocks: Array<string> = ['']; | |
let currentBlock = 0; | |
for (const review of reviews) { | |
if ( | |
review.attributes.review.length + blocks[currentBlock]?.length >= | |
blockTokenSize | |
) { | |
currentBlock++; | |
blocks[currentBlock] = review.attributes.review; | |
} else { | |
blocks[currentBlock] += `${review.attributes.review}`; | |
} | |
} | |
const suggestions: string[] = []; | |
for (const block of blocks) { | |
try { | |
const completion = await openai.createChatCompletion({ | |
model: 'gpt-3.5-turbo', | |
max_tokens: 300, | |
n: 1, | |
messages: [ | |
{ | |
role: 'system', | |
content: | |
'You are an AI language model trained to analyze ios app reviews and create suggestions for improvements.', | |
}, | |
{ | |
role: 'user', | |
content: `You must respond ONLY with JSON as an array of strings and no extra text. Based on the following reviews, suggest 5 improvements: ${block}`, | |
}, | |
], | |
}); | |
const result = JSON.parse( | |
completion.data.choices[0].message?.content || '' | |
); | |
if (Array.isArray(result)) { | |
result.forEach((s: string) => suggestions.push(s)); | |
} | |
} catch (error) { | |
console.log('error: ', error); | |
} finally { | |
await sleep(500); | |
} | |
} | |
return res.status(200).json(suggestions); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment