Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add ability to stop AI Assistant responses mid-stream (#37628)

Taishi81e1acc2d81d
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index c725519dcaa..3f085b23f7d 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -1,8 +1,8 @@
import type { UIMessage as MessageType } from '@ai-sdk/react'
-import { DefaultChatTransport } from 'ai'
import { useChat } from '@ai-sdk/react'
+import { DefaultChatTransport } from 'ai'
import { AnimatePresence, motion } from 'framer-motion'
-import { ArrowDown, Info, RefreshCw, Settings, X } from 'lucide-react'
+import { ArrowDown, Eraser, Info, Settings, X } from 'lucide-react'
import { useRouter } from 'next/router'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
@@ -19,6 +19,7 @@ import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useFlag } from 'hooks/ui/useFlag'
import { BASE_PATH, IS_PLATFORM } from 'lib/constants'
+import { tryParseJson } from 'lib/helpers'
import uuidv4 from 'lib/uuid'
import type { AssistantMessageType } from 'state/ai-assistant-state'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
@@ -146,10 +147,11 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const {
messages: chatMessages,
status: chatStatus,
+ error,
sendMessage,
setMessages,
addToolResult,
- error,
+ stop,
regenerate,
} = useChat({
id: snap.activeChatId,
@@ -216,6 +218,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
onFinish: handleChatFinish,
})
+ const formattedError = tryParseJson(error?.message ?? {})
const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming'
const updateMessage = useCallback(
@@ -245,7 +248,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
/>
)
}),
- [chatMessages, isChatLoading]
+ [chatMessages, isChatLoading, updateMessage]
)
const hasMessages = chatMessages.length > 0
@@ -362,7 +365,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
<ButtonTooltip
type="text"
size="tiny"
- icon={<Settings strokeWidth={1.5} size={14} />}
+ icon={<Settings strokeWidth={1.5} />}
onClick={() => setIsConfirmOptInModalOpen(true)}
className="h-7 w-7 p-0"
disabled={isChatLoading}
@@ -376,7 +379,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
<ButtonTooltip
type="text"
size="tiny"
- icon={<RefreshCw strokeWidth={1.5} size={14} />}
+ icon={<Eraser strokeWidth={1.5} />}
onClick={handleClearMessages}
className="h-7 w-7 p-0"
disabled={isChatLoading}
@@ -386,7 +389,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
type="text"
className="w-7 h-7"
onClick={snap.closeAssistant}
- icon={<X strokeWidth={1.5} size={14} />}
+ icon={<X strokeWidth={1.5} />}
tooltip={{ content: { side: 'bottom', text: 'Close assistant' } }}
/>
</div>
@@ -433,14 +436,40 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
<div className="w-full px-7 py-8 space-y-6">
{renderedMessages}
{error && (
- <div className="border rounded-md pl-2 pr-1 py-1 flex items-center justify-between">
- <div className="flex items-center gap-2 text-foreground-light text-sm">
- <Info size={16} />
- <p>Sorry, I'm having trouble responding right now</p>
+ <div className="border rounded-md px-2 py-2 flex items-center justify-between gap-x-4">
+ <div className="flex items-start gap-2 text-foreground-light text-sm">
+ <div>
+ <Info size={16} className="mt-0.5" />
+ </div>
+ <div>
+ <p>
+ Sorry, I'm having trouble responding right now. If the error persists while
+ retrying, you may try clearing the conversation's messages and try again.
+ </p>
+
+ <p className="text-foreground-lighter text-xs mt-1">
+ Error: {formattedError.message}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <Button
+ type="default"
+ size="tiny"
+ onClick={() => regenerate()}
+ className="text-xs"
+ >
+ Retry
+ </Button>
+ <ButtonTooltip
+ type="default"
+ size="tiny"
+ onClick={handleClearMessages}
+ className="w-7 h-7"
+ icon={<Eraser />}
+ tooltip={{ content: { side: 'bottom', text: 'Clear messages' } }}
+ />
</div>
- <Button type="text" size="tiny" onClick={() => regenerate()} className="text-xs">
- Retry
- </Button>
</div>
)}
<AnimatePresence>
@@ -586,6 +615,14 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
sendMessageToAssistant(finalMessage)
scrollToEnd()
}}
+ onStop={() => {
+ stop()
+ // to save partial responses from the AI
+ const lastMessage = chatMessages[chatMessages.length - 1]
+ if (lastMessage && lastMessage.role === 'assistant') {
+ handleChatFinish({ message: lastMessage })
+ }
+ }}
sqlSnippets={snap.sqlSnippets as SqlSnippet[] | undefined}
onRemoveSnippet={(index) => {
const newSnippets = [...(snap.sqlSnippets ?? [])]
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
index 52fadfb9d00..75bca4790a0 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
@@ -1,12 +1,12 @@
-'use client'
+import { ArrowUp, Loader2, Square } from 'lucide-react'
+import React, { ChangeEvent, memo, useRef } from 'react'
import { useBreakpoint } from 'common'
-import { ArrowUp, Loader2 } from 'lucide-react'
-import React, { ChangeEvent, memo, useRef } from 'react'
-import { Button, ExpandingTextArea } from 'ui'
+import { ExpandingTextArea } from 'ui'
import { cn } from 'ui/src/lib/utils'
-import { SnippetRow, getSnippetContent } from './SnippetRow'
+import { ButtonTooltip } from '../ButtonTooltip'
import { type SqlSnippet } from './AIAssistant.types'
+import { SnippetRow, getSnippetContent } from './SnippetRow'
export interface FormProps {
/* The ref for the textarea, optional. Exposed for the CommandsPopover to attach events. */
@@ -27,6 +27,10 @@ export interface FormProps {
* The function to handle the form submission
*/
onSubmit: (message: string) => void
+ /**
+ * The function to handle stopping the stream
+ */
+ onStop?: () => void
/* The placeholder of the textarea */
placeholder?: string
/* SQL snippets to display above the form - can be strings or objects with label and content */
@@ -48,6 +52,7 @@ const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(
textAreaRef,
onValueChange,
onSubmit,
+ onStop,
placeholder,
sqlSnippets,
onRemoveSnippet,
@@ -117,20 +122,32 @@ const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(
onKeyDown={handleKeyDown}
/>
<div className="absolute right-1.5 bottom-1.5 flex gap-3 items-center">
- {loading && (
- <Loader2 size={22} className="animate-spin w-7 h-7 text-muted" strokeWidth={1} />
+ {loading ? (
+ onStop ? (
+ <ButtonTooltip
+ type="outline"
+ aria-label="Stop response"
+ icon={<Square fill="currentColor" className="scale-75" />}
+ onClick={onStop}
+ className="w-7 h-7 rounded-full p-0 text-center flex items-center justify-center"
+ tooltip={{ content: { side: 'top', text: 'Stop response' } }}
+ />
+ ) : (
+ <Loader2 size={22} className="animate-spin size-7 text-muted" strokeWidth={1} />
+ )
+ ) : (
+ <ButtonTooltip
+ htmlType="submit"
+ aria-label="Send message"
+ icon={<ArrowUp />}
+ disabled={!canSubmit}
+ className={cn(
+ 'w-7 h-7 rounded-full p-0 text-center flex items-center justify-center',
+ !canSubmit ? 'opacity-50' : 'opacity-100'
+ )}
+ tooltip={{ content: { side: 'top', text: 'Send message' } }}
+ />
)}
- <Button
- htmlType="submit"
- aria-label="Send message"
- icon={<ArrowUp />}
- disabled={!canSubmit}
- className={cn(
- 'w-7 h-7 rounded-full p-0 text-center flex items-center justify-center',
- !canSubmit ? 'opacity-50' : 'opacity-100',
- loading && 'hidden'
- )}
- />
</div>
</form>
</div>
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index be2fade06ba..a50a11ddc39 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -81,6 +81,14 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
delete cleanedMsg.results
return cleanedMsg
}
+ // [Joshen] Am also filtering out any tool calls which state is "input-streaming"
+ // this happens when a user stops the assistant response while the tool is being called
+ if (msg && msg.role === 'assistant') {
+ const cleanedParts = msg.parts.filter((part: any) => {
+ return !(part.type.startsWith('tool-') && part.state === 'input-streaming')
+ })
+ return { ...msg, parts: cleanedParts }
+ }
return msg
})
@@ -172,6 +180,10 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
...convertToModelMessages(messages),
]
+ const abortController = new AbortController()
+ req.on('close', () => abortController.abort())
+ req.on('aborted', () => abortController.abort())
+
// Get tools
const tools = await getTools({
projectRef,
@@ -186,6 +198,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
stopWhen: stepCountIs(5),
messages: coreMessages,
tools,
+ abortSignal: abortController.signal,
})
result.pipeUIMessageStreamToResponse(res, {