import { zodResolver } from '@hookform/resolvers/zod' import { X } from 'lucide-react' import { SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'sonner' import * as z from 'zod' import { useParams } from 'common/hooks/useParams' import { useEdgeFunctionDeployMutation } from 'data/edge-functions/edge-functions-deploy-mutation' import { useSecretsCreateMutation } from 'data/secrets/secrets-create-mutation' import { Button, ExpandingTextArea, FormControl_Shadcn_, FormField_Shadcn_, Form_Shadcn_, Input_Shadcn_, Separator, SheetClose, SheetFooter, SheetHeader, SheetSection, SheetTitle, Switch, cn, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { generateFunctionCode } from './utils' const FORM_ID = 'create-ai-completion-function' const FormSchema = z.object({ prompt: z.string().default(''), apiUrl: z.string().url('Must be a valid URL'), apiKey: z.string().min(1, 'API key is required'), name: z.string().min(1, 'Name is required'), stream: z.boolean().default(false), verifyJwt: z.boolean().default(false), }) interface NewAiCompletionFunctionDialogProps { onClose: () => void } export const DeployAiCompletionFunctionSheetContent = ({ onClose, }: NewAiCompletionFunctionDialogProps) => { const { ref: projectRef } = useParams() const form = useForm>({ resolver: zodResolver(FormSchema), defaultValues: { prompt: '', apiUrl: 'https://api.openai.com/v1', apiKey: '', name: '', stream: false, verifyJwt: false, }, }) const { mutateAsync: deployEdgeFunction, isLoading: isDeploying } = useEdgeFunctionDeployMutation() const { mutateAsync: createSecret, isLoading: isSavingSecret } = useSecretsCreateMutation() const onSubmit: SubmitHandler> = async (values) => { const toastId = toast.loading('Deploying function...') try { const content = generateFunctionCode(values.prompt, values.apiUrl, 'gpt-4o', values.stream) console.log(content) const deployResult = await deployEdgeFunction({ projectRef: projectRef!, metadata: { entrypoint_path: 'index.ts', name: values.name, verify_jwt: values.verifyJwt, }, files: [{ name: 'index.ts', content }], }) console.log(deployResult) toast.loading('Saving the API key as a secret...', { id: toastId }) createSecret({ projectRef, secrets: [{ name: 'OPENAI_API_KEY', value: values.apiKey }] }) toast.success('Edge function deployed successfully', { id: toastId }) onClose() } catch (error) { console.error(error) toast.dismiss(toastId) } } return ( <>
Close Create AI Completion Function
( )} />
( )} /> ( )} /> ( The function will be accessible at{' '} /v1/{field.value} } > )} />
( )} /> ( )} />
) }