The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Attempt to fix completion (#37787)
Saxon Fletcher7b941a0fd7f3
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex 9f3f8e0c174..12383978073 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -1,4 +1,3 @@-import { useCompletion } from '@ai-sdk/react'import type { Monaco } from '@monaco-editor/react'import { useQueryClient } from '@tanstack/react-query'import { ChevronUp, Loader2 } from 'lucide-react'@@ -453,22 +452,70 @@ export const SQLEditor = () => {closeDiff()}, [closeDiff, resetPrompt, sendEvent])- const {- complete,- completion,- isLoading: isCompletionLoading,- } = useCompletion({- api: `${BASE_PATH}/api/ai/code/complete`,- body: {- projectRef: project?.ref,- connectionString: project?.connectionString,- language: 'sql',- orgSlug: org?.slug,- },- onError: (error) => {- toast.error(`Failed to generate SQL: ${error.message}`)+ const [isCompletionLoading, setIsCompletionLoading] = useState<boolean>(false)++ const complete = useCallback(+ async (+ prompt: string,+ options?: {+ headers?: Record<string, string>+ body?: { completionMetadata?: any }+ }+ ) => {+ try {+ setIsCompletionLoading(true)++ const response = await fetch(`${BASE_PATH}/api/ai/code/complete`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(options?.headers ?? {}),+ },+ body: JSON.stringify({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ language: 'sql',+ orgSlug: org?.slug,+ ...(options?.body ?? {}),+ }),+ })++ if (!response.ok) {+ const errorText = await response.text()+ throw new Error(errorText || 'Failed to generate completion')+ }++ // API returns a JSON-encoded string+ const text: string = await response.json()++ const meta = options?.body?.completionMetadata ?? {}+ const beforeSelection: string = meta.textBeforeCursor ?? ''+ const afterSelection: string = meta.textAfterCursor ?? ''+ const selection: string = meta.selection ?? ''++ const original = beforeSelection + selection + afterSelection+ const modified = beforeSelection + text + afterSelection++ const formattedModified = formatSql(modified)+ setSourceSqlDiff({ original, modified: formattedModified })+ setSelectedDiffType(DiffType.Modification)+ setPromptState((prev) => ({ ...prev, isLoading: false }))+ setIsCompletionLoading(false)+ } catch (error: any) {+ toast.error(`Failed to generate SQL: ${error?.message ?? 'Unknown error'}`)+ setIsCompletionLoading(false)+ throw error+ }},- })+ [+ org?.slug,+ project?.connectionString,+ project?.ref,+ setPromptState,+ setSelectedDiffType,+ setSourceSqlDiff,+ ]+ )const handlePrompt = async (prompt: string,@@ -593,35 +640,6 @@ export const SQLEditor = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [snapV2.diffContent])- useEffect(() => {- if (!completion) {- return- }-- const original =- promptState.beforeSelection + promptState.selection + promptState.afterSelection- const modified = promptState.beforeSelection + completion + promptState.afterSelection-- if (isCompletionLoading) {- // Attempt to format the modified SQL in case the LLM left out indentation, etc- let formattedModified = formatSql(modified)-- setSourceSqlDiff({- original,- modified: formattedModified,- })- setSelectedDiffType(DiffType.Modification)- setPromptState((prev) => ({ ...prev, isLoading: false }))- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- completion,- promptState.beforeSelection,- promptState.selection,- promptState.afterSelection,- isCompletionLoading,- ])-// We want to check if the diff editor is mounted and if it is, we want to show the widget// We also want to cleanup the widget when the diff editor is closeduseEffect(() => {diff --git a/apps/studio/components/ui/AIEditor/index.tsx b/apps/studio/components/ui/AIEditor/index.tsxindex eb34c04b180..b27d47061e2 100644--- a/apps/studio/components/ui/AIEditor/index.tsx+++ b/apps/studio/components/ui/AIEditor/index.tsx@@ -1,5 +1,4 @@import Editor, { DiffEditor, Monaco, OnMount } from '@monaco-editor/react'-import { useCompletion } from '@ai-sdk/react'import { AnimatePresence, motion } from 'framer-motion'import { Command } from 'lucide-react'import { editor as monacoEditor } from 'monaco-editor'@@ -71,26 +70,64 @@ const AIEditor = ({})const [promptInput, setPromptInput] = useState(initialPrompt || '')- const {- complete,- completion,- isLoading: isCompletionLoading,- setCompletion,- } = useCompletion({- api: aiEndpoint || '',- body: aiMetadata,- onError: (error) => {- toast.error(`Failed to generate: ${error.message}`)+ const [isCompletionLoading, setIsCompletionLoading] = useState(false)++ const complete = useCallback(+ async (+ prompt: string,+ options?: {+ headers?: Record<string, string>+ body?: { completionMetadata?: any }+ }+ ) => {+ try {+ if (!aiEndpoint) throw new Error('AI endpoint is not configured')+ setIsCompletionLoading(true)++ const response = await fetch(aiEndpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(options?.headers ?? {}),+ },+ body: JSON.stringify({+ ...(aiMetadata ?? {}),+ ...(options?.body ?? {}),+ }),+ })++ if (!response.ok) {+ const errorText = await response.text()+ throw new Error(errorText || 'Failed to generate completion')+ }++ const text: string = await response.json()++ const meta = options?.body?.completionMetadata ?? {}+ const beforeSelection: string = meta.textBeforeCursor ?? ''+ const afterSelection: string = meta.textAfterCursor ?? ''+ const selection: string = meta.selection ?? ''++ const original = beforeSelection + selection + afterSelection+ const modified = beforeSelection + text + afterSelection++ setDiffValue({ original, modified })+ setIsDiffMode(true)+ } catch (error: any) {+ toast.error(`Failed to generate: ${error?.message ?? 'Unknown error'}`)+ } finally {+ setIsCompletionLoading(false)+ }},- })+ [aiEndpoint, aiMetadata]+ )const handleReset = useCallback(() => {- setCompletion('')setIsDiffMode(false)setPromptState((prev) => ({ ...prev, isOpen: false }))setPromptInput('')editorRef.current?.focus()- }, [setCompletion])+ }, [])const handleAcceptDiff = useCallback(() => {if (diffValue.modified) {@@ -269,20 +306,6 @@ const AIEditor = ({}}, [isDiffMode])- useEffect(() => {- if (!completion) {- setIsDiffMode(false)- return- }-- const original =- promptState.beforeSelection + promptState.selection + promptState.afterSelection- const modified = promptState.beforeSelection + completion + promptState.afterSelection-- setDiffValue({ original, modified })- setIsDiffMode(true)- }, [completion, promptState.beforeSelection, promptState.selection, promptState.afterSelection])-useEffect(() => {const handleKeyboard = (event: KeyboardEvent) => {if (event.key === 'Escape') {diff --git a/apps/studio/pages/api/ai/code/complete.ts b/apps/studio/pages/api/ai/code/complete.tsindex 157989ffdf5..13957ee1511 100644--- a/apps/studio/pages/api/ai/code/complete.ts+++ b/apps/studio/pages/api/ai/code/complete.ts@@ -1,5 +1,5 @@import pgMeta from '@supabase/pg-meta'-import { ModelMessage, stepCountIs, streamText } from 'ai'+import { ModelMessage, stepCountIs, generateText, Output } from 'ai'import { IS_PLATFORM } from 'common'import { source } from 'common-tags'import { executeSql } from 'data/sql/execute-sql-query'@@ -18,6 +18,7 @@ import { getTools } from 'lib/ai/tools'import apiWrapper from 'lib/api/apiWrapper'import { queryPgMetaSelfHosted } from 'lib/self-hosted'import { NextApiRequest, NextApiResponse } from 'next'+import { z } from 'zod/v4'export const maxDuration = 60@@ -148,14 +149,19 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {accessToken,})- const result = streamText({+ const { experimental_output } = await generateText({model,stopWhen: stepCountIs(5),+ experimental_output: Output.object({+ schema: z.object({+ code: z.string().describe('The modified code'),+ }),+ }),messages: coreMessages,tools,})- return result.pipeUIMessageStreamToResponse(res)+ return res.status(200).json(experimental_output?.code)} catch (error) {console.error('Completion error:', error)return res.status(500).json({