Skip to content

Commit

Permalink
try fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
giridhar7632 committed Apr 1, 2024
1 parent 96560e0 commit bc99634
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 25 deletions.
37 changes: 28 additions & 9 deletions app/(protected)/create/Prompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import toast, { CheckmarkIcon } from 'react-hot-toast'
import Spinner from '@/components/Spinner'
import { extractAndParseJson } from '@/utils/extractAndParseJson'
import Input from '@/components/Input'
import { PageData } from '@/types/types'

const Prompt = () => {
const formRef = useRef<HTMLFormElement>(null)
Expand All @@ -26,18 +27,39 @@ const Prompt = () => {
const [creatingTable, setCreatingTable] = useState('pending')
const [addingPage, setAddingPage] = useState('pending')

async function fn(res: any, cnt = 0): Promise<any> {
console.log('trail', cnt)
try {
res = await generateJson(res)
return extractAndParseJson(res)
} catch (error) {
console.log(error)
if (cnt < 5) {
return await fn(res, cnt + 1) // Use 'await' here
} else {
throw new Error(
'Sorry! Gemini was unable to generate the form at the moment 😕'
)
}
}
}

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
console.log('prompt:', prompt)
setLoading(true)
try {
if (prompt !== '') {
setGeneratingForm('started')
let res = await generateJson(prompt)
res = extractAndParseJson(res)
let res = (await fn(prompt)) as PageData

console.log({ parsed: res })
setGeneratingForm('completed')
setCreatingTable('started')
const table = generateSlug(data?.user.id as string, res.title)
const table = generateSlug(
data?.user.id as string,
title ? title : res.title ?? 'untitled'
)
if (res.fields.length === 0)
throw new Error('Add at least one field 😁')
let tableRes
Expand All @@ -47,21 +69,18 @@ const Prompt = () => {
tableRes = await updateTable(table, res.fields)
}
setCreatingTable('completed')

console.log({ tableRes })

setAddingPage('started')
if (tableRes.status === 'completed') {
await addPage(table, title, description, res)
await addPage(table, title, description, res, prompt)
setAddingPage('completed')
router.push(`/form/${table}`)
} else {
throw new Error('Something went wrong when creating your form! 😕')
}
}
} catch (error) {
} catch (error: any) {
console.log(error)
toast.error('Something went wrong! 😕')
toast.error(error.message ?? 'Something went wrong! 😕')
} finally {
setGeneratingForm('pending')
setCreatingTable('pending')
Expand Down
6 changes: 4 additions & 2 deletions app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export async function createTable(table: string, fields: FormField[]) {
})

if (schemaData.status !== 'completed') {
await dbReq({ method: 'DELETE', path: `/tables/${table}` })
await dbReqWithoutBody({ method: 'DELETE', path: `/tables/${table}` })
}
console.log('schemaData', schemaData)

Expand Down Expand Up @@ -181,7 +181,8 @@ export async function addPage(
table: string,
title: string,
description: string,
input: PageData
input: PageData,
prompt?: string
) {
const session = await getSession()
if (session) {
Expand All @@ -191,6 +192,7 @@ export async function addPage(
page: input,
createdBy: session?.user?.id,
slug: table,
prompt,
})
return res
}
Expand Down
2 changes: 1 addition & 1 deletion lib/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function model(old: Object, input: string) {

const parts = [
{
text: `understand and generate a parsable json file in the format given (do not include submit button) from the given description:\nformat:\nexport type FormData = {\n title: string\n action: 'create' | 'update' | 'delete' // understand what user wanted to do\n fields: FormField[]\n}\n\nexport type FormField = {\n id?: string\n field: string // html element\n type: string // type of form element\n name: string\n label: string\n value?: string\n placeholder?: string\n disabled?: boolean\n required?: boolean\n options?: {\n  value: string\n  label: string\n  name?: string\n }[]\n}\n\ndescription: "${input}" \n comeup with atleast one field \n\nold: "${JSON.stringify(
text: `understand and generate a parsable json file in the format given (do not include submit button) from the given description:\nformat:\nexport type FormData = {\n title: string\n action: 'create' | 'update' | 'delete' // understand what user wanted to do\n fields: FormField[]\n}\n\nexport type FormField = {\n id?: string\n field: string // html element\n type: string // type of form element\n name: string\n label: string\n value?: string\n placeholder?: string\n disabled?: boolean\n required?: boolean\n options?: {\n value: string\n label: string\n name?: string\n }[]\n}\n\ndescription: "${input}" \n comeup with title, description and atleast one field \n\nold: "${JSON.stringify(
old
)}"`,
},
Expand Down
20 changes: 7 additions & 13 deletions utils/extractAndParseJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,19 @@ export function extractAndParseJson(input: string): Object {
// )

function tryParseJSON(jsonString: string) {
try {
const fixedJsonString = fixJSONFormatting(jsonString)
if (fixedJsonString) {
return JSON.parse(jsonString)
} catch (error) {
const fixedJsonString = fixJSONFormatting(jsonString)
if (fixedJsonString) {
return JSON.parse(fixedJsonString)
}

throw error
}
}

function fixJSONFormatting(jsonString: string) {
jsonString = jsonString
.replace(/\n/g, ' ')
.replace(/\r/g, ' ')
.replace(/\t/g, ' ')
jsonString = jsonString.replace(/,\s*}/g, '}')
jsonString = jsonString.replace(/([\{,])\s*([^"'\{\}\[\]:]+)\s*:/g, '$1"$2":')
jsonString = jsonString.replace(
/([^"'\{\}\[\]:,])\s*([^"'\{\}\[\]:]+)/g,
'$1"$2":'
)
jsonString = jsonString.replace('\n', ' ')
jsonString = jsonString.replace('\n ', ' ')
jsonString = jsonString.replace(' ', ' ')

Expand Down

0 comments on commit bc99634

Please sign in to comment.