Skip to content

Commit

Permalink
implement basic generate survey using AI
Browse files Browse the repository at this point in the history
  • Loading branch information
visrut-at-incubyte committed Sep 17, 2023
1 parent 1894dd0 commit 4696c4d
Show file tree
Hide file tree
Showing 13 changed files with 164 additions and 29 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
MONGODB_URI=mongodb://localhost:27017
SALT=kdjlsjflsjfaoesffdnfldsafasjeifjskfdlsfdjsl3982402sd
OPENAI_API_KEY=
33 changes: 33 additions & 0 deletions app/create-survey/ai/api/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { QuestionType } from '@/app/models/types'

export const SURVEY_CREATION_SYSTEM_PROMPT = `
You are a helpful survey creation assistant. You will be given survey title or description by the user and you have to generate 10 questions with it's type.
You have to only respond with questions and it's type seperated by new line. Don't provide any other text or explanation or even numberings for the questions.
Here are the types you can use for questions: "${QuestionType.MULTICHOICE}, ${QuestionType.SINGLECHOICE}, ${QuestionType.TEXT}, ${QuestionType.NUMBER}, ${QuestionType.DATE}, ${QuestionType.RATE_10}, ${QuestionType.STAR_5}, ${QuestionType.EMOJIS}, ${QuestionType.YES_OR_NO}"
You won't provide any other text or explanation than the questions and it's type.
User: I want to create a survey to get feedback about my website.
Assistant:
---
how would you rate your overall experience with our website?, ${QuestionType.RATE_10}
What was your first impression when you landed on our website?, ${QuestionType.TEXT}
Are you satisfied with the website?, ${QuestionType.YES_OR_NO}
Which sections did you like on the website?, ${QuestionType.MULTICHOICE}
What is your favorite feature of the website?, ${QuestionType.TEXT}
What is your least favorite feature of the website?, ${QuestionType.TEXT}
What can we do to improve your experience?, ${QuestionType.TEXT}
What is your preferred time to use the website?, ${QuestionType.SINGLECHOICE}
What is your preferred device to use the website?, ${QuestionType.SINGLECHOICE}
What additional services or amenities would you like to see on the website?, ${QuestionType.TEXT}
---
`

export const SURVEY_CREATION_ASSISTANT_PROMPT_1 = `
Yes, I will help you to create survey questions. I will generate 10 questions with it's type based on the survey title or description.
I won't provide any options for questions, just the questions and it's type.
I will provide you the questions in the following format:
---
question, type
---
`
51 changes: 51 additions & 0 deletions app/create-survey/ai/api/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { NextResponse } from 'next/server'
import { createHash, getClientIP } from '@/app/utils'
import clientPromise from '@/app/mongodb'
import openai from '@/app/openai'
import { SURVEY_CREATION_ASSISTANT_PROMPT_1, SURVEY_CREATION_SYSTEM_PROMPT } from './prompt'

export async function POST(request: Request) {
const ip = getClientIP(request)

const client = await clientPromise
const db = client.db('survey-db')

const hash = createHash(ip!)
const creatorHistory = await db.collection('open-ai-limit').findOne({ ipHash: hash })

if (creatorHistory === null) {
await db.collection('open-ai-limit').insertOne({ ipHash: hash, count: 1 })
} else {
const prevCount = creatorHistory.count

if (prevCount >= 3) {
return NextResponse.json({ error: 'API limit is reached to generate survey using OpenAI' }, { status: 429 })
}

await db.collection('open-ai-limit').updateOne({ ipHash: hash }, { $set: { count: prevCount + 1 } })
}

const userPrompt = (await request.json()).prompt

const response = await openai.chat.completions.create({
messages: [
{
role: 'system',
content: SURVEY_CREATION_SYSTEM_PROMPT
},
{
role: 'assistant',
content: SURVEY_CREATION_ASSISTANT_PROMPT_1
},
{
role: 'user',
content: `description for the survey: ${userPrompt}`
}
],
model: 'gpt-3.5-turbo',
max_tokens: 300,
temperature: 0.0
})

return NextResponse.json({ survey: response.choices[0].message.content }, { status: 201 })
}
57 changes: 57 additions & 0 deletions app/create-survey/ai/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use client'

import { useRouter } from 'next/navigation'
import React, { useState } from 'react'
import { useAppContext } from '@/app/context/AppContext'

const GenerateWithAi = () => {
const router = useRouter()

const { setQuestions } = useAppContext()

const [surveyDescription, setSurveyDescription] = useState('')

const generateUsingAi = async (event: React.FormEvent) => {
event.preventDefault()
const response = await fetch('ai/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: surveyDescription })
})
const { survey }: { survey: string } = await response.json()

const surveyQuestions: any[] = survey
.trim()
.split('\n')
.map((question_and_type) => {
const [question, type] = question_and_type.split(',')
return { question: question.trim(), type: type.trim() }
})

setQuestions([...surveyQuestions])
router.push('/create-survey')
}

return (
<form className='h-screen flex flex-col items-center justify-center gap-y-4' onSubmit={generateUsingAi}>
<label htmlFor='survey-description' className='text-2xl'>
Enter survey topic or description
</label>
<textarea
className='textarea w-96 h-64'
autoFocus
name='survey-description'
id='survey-description'
placeholder="Conducting a market research survey for a new fitness app. We want to understand people's fitness goals, preferred workout routines, and pain points in existing fitness apps. Our target audience is health-conscious individuals aged 18-45, both beginners and experienced fitness enthusiasts. The survey should help us design features that cater to their specific needs and preferences."
onChange={(e) => setSurveyDescription(e.target.value)}
/>
<button type='submit' className='btn btn-primary'>
Let&apos;s Go
</button>
</form>
)
}

export default GenerateWithAi
2 changes: 2 additions & 0 deletions app/create-survey/components/MultiChoice/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ type MultiChoiceProps = {
}

const MultiChoice = ({ choices, setChoices, setAnswer }: MultiChoiceProps) => {
if (choices === undefined) return <></>

const [checkboxStates, setCheckboxStates] = useState<boolean[]>(choices.map(() => false))

const handleChoiceChange = (index: number, newValue: string) => {
Expand Down
4 changes: 4 additions & 0 deletions app/create-survey/components/SingleChoice/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ type SingleChoiceProps = {
}

const SingleChoice = ({ choices, setChoices, setAnswer }: SingleChoiceProps) => {
if (choices === undefined) {
return <></>
}

const handleChoiceChange = (index: number, newValue: string) => {
const updatedChoices = [...choices]
updatedChoices[index] = newValue
Expand Down
8 changes: 0 additions & 8 deletions app/create-survey/loading.tsx

This file was deleted.

19 changes: 0 additions & 19 deletions app/generate-with-ai/page.tsx

This file was deleted.

6 changes: 6 additions & 0 deletions app/loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use client'
import LoadingSpinner from './components/LoadingSpinner'

export default function Spinner() {
return <LoadingSpinner />
}
7 changes: 7 additions & 0 deletions app/openai.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import OpenAI from 'openai'

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
})

export default openai
2 changes: 1 addition & 1 deletion app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function Home() {
<Link className='btn btn-primary' href='/create-survey'>
Create Manually
</Link>
<Link className='btn btn-gradient border-none' href='/generate-with-ai'>
<Link className='btn btn-gradient border-none' href='/create-survey/ai'>
Generate with AI
</Link>
<Link
Expand Down
1 change: 0 additions & 1 deletion app/survey/[id]/components/AnswerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ const AnswerForm = () => {

const setAnswer = (answer: Answer) => {
setAnswers([...answers, answer])
console.log([...answers, answer])
moveToNextQuestion()
}

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
"@types/react": "18.2.18",
"@types/react-dom": "18.2.7",
"autoprefixer": "10.4.14",
"encoding": "^0.1.13",
"eslint-config-next": "13.4.12",
"framer-motion": "^10.16.0",
"mongodb": "^5.7.0",
"next": "13.4.12",
"openai": "^4.6.0",
"postcss": "8.4.27",
"react": "18.2.0",
"react-dom": "18.2.0",
Expand Down

0 comments on commit 4696c4d

Please sign in to comment.