Skip to content

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

feat(cmdk): multi-message ai poc

Greg Richardson8fed8fd78564
diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsx
index 58f7fea9f7b..b48403ea55e 100644
--- a/apps/docs/pages/_app.tsx
+++ b/apps/docs/pages/_app.tsx
@@ -78,7 +78,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
<ThemeProvider>
<CommandMenuProvider
site="docs"
- MarkdownHandler={({ ...props }) => (
+ MarkdownHandler={(props) => (
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components} {...props} />
)}
>
diff --git a/packages/ui/src/components/Command/AiCommand.tsx b/packages/ui/src/components/Command/AiCommand.tsx
index 21971713c55..866d7c986b3 100644
--- a/packages/ui/src/components/Command/AiCommand.tsx
+++ b/packages/ui/src/components/Command/AiCommand.tsx
@@ -52,60 +52,80 @@ function getEdgeFunctionUrl() {
const edgeFunctionUrl = getEdgeFunctionUrl()
-function promptDataReducer(
- state: any[],
- action: {
- index?: number
- answer?: string | undefined
- status?: string
- query?: string | undefined
- type?: 'remove-last-item' | string
- }
-) {
- // set a standard state to use later
- let current = [...state]
+enum MessageRole {
+ User = 'user',
+ Assistant = 'assistant',
+}
- if (action.type) {
- switch (action.type) {
- case 'remove-last-item':
- current.pop()
- return [...current]
- default:
- break
- }
- }
+enum MessageStatus {
+ InProgress = 'in-progress',
+ Complete = 'complete',
+}
- // check that an index is present
- if (action.index === undefined) return [...state]
+interface Message {
+ role: MessageRole
+ content: string
+ status: MessageStatus
+}
- if (!current[action.index]) {
- current[action.index] = { query: '', answer: '', status: '' }
- }
+interface NewMessageAction {
+ type: 'new'
+ message: Message
+}
- current[action.index].answer = action.answer
+interface UpdateMessageAction {
+ type: 'update'
+ index: number
+ message: Partial<Message>
+}
- if (action.query) {
- current[action.index].query = action.query
- }
- if (action.status) {
- current[action.index].status = action.status
+interface AppendContentAction {
+ type: 'append-content'
+ index: number
+ content: string
+}
+
+type MessageAction = NewMessageAction | UpdateMessageAction | AppendContentAction
+
+function messageReducer(state: Message[], messageAction: MessageAction) {
+ let current = [...state]
+ const { type } = messageAction
+
+ switch (type) {
+ case 'new': {
+ const { message } = messageAction
+ current.push(message)
+ break
+ }
+ case 'update': {
+ const { index, message } = messageAction
+ Object.assign(current[index], message)
+ break
+ }
+ case 'append-content': {
+ const { index, content } = messageAction
+ current[index].content += content
+ break
+ }
+ default: {
+ throw new Error(`Unknown message action '${type}'`)
+ }
}
- return [...current]
+ return current
}
const AiCommand = () => {
- const [answer, setAnswer] = useState<string | undefined>('')
const [isResponding, setIsResponding] = useState(false)
- const [hasClippyError, setHasClippyError] = useState(false)
+ const [hasError, setHasError] = useState(false)
const eventSourceRef = useRef<SSE>()
const { isLoading, setIsLoading, currentPage, search, setSearch, MarkdownHandler } =
useCommandMenu()
- const [promptIndex, setPromptIndex] = useState(0)
- const [promptData, dispatchPromptData] = useReducer(promptDataReducer, [])
+ const [currentMessageIndex, setCurrentMessageIndex] = useState(1)
+ const [messages, dispatchMessage] = useReducer(messageReducer, [])
- const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."
+ console.log({ messages })
const handleConfirm = useCallback(
async (query: string) => {
@@ -113,11 +133,25 @@ const AiCommand = () => {
return console.error('No edge function url')
}
- setAnswer(undefined)
setSearch('')
- dispatchPromptData({ index: promptIndex, answer: undefined, query })
+ dispatchMessage({
+ type: 'new',
+ message: {
+ status: MessageStatus.Complete,
+ role: MessageRole.User,
+ content: query,
+ },
+ })
+ dispatchMessage({
+ type: 'new',
+ message: {
+ status: MessageStatus.InProgress,
+ role: MessageRole.Assistant,
+ content: '',
+ },
+ })
setIsResponding(false)
- setHasClippyError(false)
+ setHasError(false)
setIsLoading(true)
let queryToSend = query
@@ -143,19 +177,26 @@ const AiCommand = () => {
break
}
+ console.log(messages)
+
const eventSource = new SSE(`${edgeFunctionUrl}/clippy-search`, {
headers: {
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,
'Content-Type': 'application/json',
},
- payload: JSON.stringify({ query, context: promptData }),
+ payload: JSON.stringify({
+ messages: messages
+ .filter(({ status }) => status === MessageStatus.Complete)
+ .map(({ role, content }) => ({ role, content }))
+ .concat({ role: MessageRole.User, content: query }),
+ }),
})
function handleError<T>(err: T) {
setIsLoading(false)
setIsResponding(false)
- setHasClippyError(true)
+ setHasError(true)
console.error(err)
}
@@ -166,10 +207,14 @@ const AiCommand = () => {
if (e.data === '[DONE]') {
setIsResponding(false)
- setAnswer(undefined)
- setPromptIndex((x) => {
- return x + 1
+ dispatchMessage({
+ type: 'update',
+ index: currentMessageIndex,
+ message: {
+ status: MessageStatus.Complete,
+ },
})
+ setCurrentMessageIndex((x) => x + 2)
return
}
@@ -184,15 +229,12 @@ const AiCommand = () => {
const text = content ?? ''
- setAnswer((answer) => {
- const currentAnswer = answer ?? ''
-
- dispatchPromptData({
- index: promptIndex,
- answer: currentAnswer + text,
- })
+ console.log({ text })
- return (answer ?? '') + text
+ dispatchMessage({
+ type: 'append-content',
+ index: currentMessageIndex,
+ content: text,
})
} catch (err) {
handleError(err)
@@ -205,16 +247,15 @@ const AiCommand = () => {
setIsLoading(true)
},
- [promptIndex, promptData]
+ [currentMessageIndex, messages]
)
function handleResetPrompt() {
eventSourceRef.current?.close()
eventSourceRef.current = undefined
setSearch('')
- setAnswer(undefined)
setIsResponding(false)
- setHasClippyError(false)
+ setHasError(false)
}
useEffect(() => {
@@ -226,50 +267,40 @@ const AiCommand = () => {
return (
<div onClick={(e) => e.stopPropagation()}>
<div className={cn('relative mb-[62px] py-4 max-h-[720px] overflow-auto')}>
- {promptData.map((prompt, i) => {
- if (!prompt.query) return <></>
-
- return (
- <>
- {prompt.query && (
- <div className="flex gap-6 mx-4 [overflow-anchor:none] mb-6">
+ {messages.map((message, index) => {
+ switch (message.role) {
+ case MessageRole.User:
+ return (
+ <div key={index} className="flex gap-6 mx-4 [overflow-anchor:none] mb-6">
<div
className="
- w-7 h-7 bg-scale-200 rounded-full border border-scale-400 flex items-center justify-center text-scale-1000 first-letter:
- ring-scale-200
- ring-1
- shadow-sm
- "
+ w-7 h-7 bg-scale-200 rounded-full border border-scale-400 flex items-center justify-center text-scale-1000 first-letter:
+ ring-scale-200
+ ring-1
+ shadow-sm
+ "
>
<IconUser strokeWidth={1.5} size={16} />
</div>
- <div className="prose text-scale-1000">{prompt.query}</div>
+ <div className="prose text-scale-1000">{message.content}</div>
</div>
- )}
-
- <div className="px-4 [overflow-anchor:none] mb-6">
- {cantHelp ? (
- <p className="flex flex-col gap-4 items-center p-4">
- <div className="grid md:flex items-center gap-2 mt-4 text-center justify-items-center">
- <IconAlertCircle />
- <p>Sorry, I don&apos;t know how to help with that.</p>
- </div>
- <Button size="tiny" type="secondary" onClick={handleResetPrompt}>
- Try again?
- </Button>
- </p>
- ) : (
+ )
+ case MessageRole.Assistant:
+ return (
+ <div
+ key={`${index}-${message.content}`}
+ className="px-4 [overflow-anchor:none] mb-6"
+ >
<div className="flex gap-6 [overflow-anchor:none] mb-6">
<AiIconChat />
<>
- {isLoading && promptIndex === i ? (
+ {message.status === MessageStatus.InProgress ? (
<div className="bg-scale-700 h-[21px] w-[13px] mt-1 animate-pulse animate-bounce"></div>
) : (
- // @ts-expect-error
<MarkdownHandler
linkTarget="_blank"
className="prose dark:prose-dark"
- transformLinkUri={(href: string) => {
+ transformLinkUri={(href) => {
const supabaseUrl = new URL('https://supabase.com')
const linkUrl = new URL(href, 'https://supabase.com')
@@ -280,18 +311,17 @@ const AiCommand = () => {
return href
}}
>
- {prompt.answer}
+ {message.content}
</MarkdownHandler>
)}
</>
</div>
- )}
- </div>
- </>
- )
+ </div>
+ )
+ }
})}
- {promptData.length === 0 && !hasClippyError && (
+ {messages.length === 0 && !hasError && (
<CommandGroup heading="Examples" forceMount>
{questions.map((question) => {
const key = question.replace(/\s+/g, '_')
@@ -313,7 +343,7 @@ const AiCommand = () => {
})}
</CommandGroup>
)}
- {hasClippyError && (
+ {hasError && (
<div className="p-6 flex flex-col items-center gap-6 mt-4">
<IconAlertTriangle className="text-amber-900" strokeWidth={1.5} size={21} />
<p className="text-lg text-scale-1200 text-center">
diff --git a/packages/ui/src/components/Command/CommandMenuProvider.tsx b/packages/ui/src/components/Command/CommandMenuProvider.tsx
index 0caf455f69b..45f8f8c0f84 100644
--- a/packages/ui/src/components/Command/CommandMenuProvider.tsx
+++ b/packages/ui/src/components/Command/CommandMenuProvider.tsx
@@ -2,6 +2,7 @@ import { useTheme, UseThemeProps } from 'common'
import * as React from 'react'
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
import CommandMenu from './CommandMenu'
+import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown'
export interface CommandMenuContextValue {
isOpen: boolean
@@ -18,7 +19,7 @@ export interface CommandMenuContextValue {
// to do: remove this prop
// this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package
- MarkdownHandler: (props: any) => React.ReactNode // to do: remove this. although it breaks our jest tests
+ MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element // to do: remove this. although it breaks our jest tests
// Optional callback to save a generated SQL output
onSaveGeneratedSQL?: (answer: string, resolve: any) => void
@@ -43,7 +44,7 @@ export interface CommandMenuProviderProps {
projectRef?: string
// to do: remove this prop
// this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package
- MarkdownHandler: (props: any) => React.ReactNode
+ MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element
onSaveGeneratedSQL?: (answer: string, resolve: any) => void
}
diff --git a/studio/components/interfaces/App/CommandMenuWrapper.tsx b/studio/components/interfaces/App/CommandMenuWrapper.tsx
index cb92312132e..1946259e16b 100644
--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx
+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx
@@ -46,9 +46,7 @@ ${answer}
<CommandMenuProvider
site="studio"
projectRef={ref}
- MarkdownHandler={({ ...props }) => (
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={null} {...props} />
- )}
+ MarkdownHandler={(props) => <ReactMarkdown remarkPlugins={[remarkGfm]} {...props} />}
onSaveGeneratedSQL={onSaveGeneratedSQL}
>
{children}
diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.ts
index cf0d705c0e7..d7d5be3a0f8 100644
--- a/supabase/functions/clippy-search/index.ts
+++ b/supabase/functions/clippy-search/index.ts
@@ -10,7 +10,21 @@ import {
OpenAIApi,
} from 'https://esm.sh/[email protected]'
import { ApplicationError, UserError } from '../common/errors.ts'
-import { tokenizer } from '../common/tokenizer.ts'
+import { getChatRequestTokenCount, getMaxTokenCount, tokenizer } from '../common/tokenizer.ts'
+
+enum MessageRole {
+ User = 'user',
+ Assistant = 'assistant',
+}
+
+interface Message {
+ role: MessageRole
+ content: string
+}
+
+interface RequestData {
+ messages: Message[]
+}
const openAiKey = Deno.env.get('OPENAI_KEY')
const supabaseUrl = Deno.env.get('SUPABASE_URL')
@@ -40,22 +54,43 @@ serve(async (req) => {
throw new ApplicationError('Missing environment variable SUPABASE_SERVICE_ROLE_KEY')
}
- const requestData = await req.json()
+ const requestData: RequestData = await req.json()
if (!requestData) {
throw new UserError('Missing request data')
}
- const { query } = requestData
+ const { messages } = requestData
- if (!query) {
- throw new UserError('Missing query in request data')
+ if (!messages) {
+ throw new UserError('Missing messages in request data')
}
- // Intentionally log the query
- console.log({ query })
+ // Intentionally log the messages
+ console.log({ messages })
+
+ // TODO: better sanitization
+ const contextMessages: ChatCompletionRequestMessage[] = messages.map(({ role, content }) => {
+ if (
+ ![
+ ChatCompletionRequestMessageRoleEnum.User,
+ ChatCompletionRequestMessageRoleEnum.Assistant,
+ ].includes(role)
+ ) {
+ throw new Error(`Invalid message role '${role}'`)
+ }
- const sanitizedQuery = query.trim()
+ return {
+ role,
+ content: content.trim(),
+ }
+ })
+
+ const [userMessage] = contextMessages.filter(({ role }) => role === MessageRole.User).slice(-1)
+
+ if (!userMessage) {
+ throw new Error("No message with role 'user'")
+ }
const supabaseClient = createClient(supabaseUrl, supabaseServiceKey)
@@ -63,24 +98,28 @@ serve(async (req) => {
const openai = new OpenAIApi(configuration)
// Moderate the content to comply with OpenAI T&C
- const moderationResponse = await openai.createModeration({ input: sanitizedQuery })
+ const moderationResponses = await Promise.all(
+ contextMessages.map((message) => openai.createModeration({ input: message.content }))
+ )
- const [results] = moderationResponse.data.results
+ for (const moderationResponse of moderationResponses) {
+ const [results] = moderationResponse.data.results
- if (results.flagged) {
- throw new UserError('Flagged content', {
- flagged: true,
- categories: results.categories,
- })
+ if (results.flagged) {
+ throw new UserError('Flagged content', {
+ flagged: true,
+ categories: results.categories,
+ })
+ }
}
const embeddingResponse = await openai.createEmbedding({
model: 'text-embedding-ada-002',
- input: sanitizedQuery.replaceAll('\n', ' '),
+ input: userMessage.content.replaceAll('\n', ' '),
})
if (embeddingResponse.status !== 200) {
- throw new ApplicationError('Failed to create embedding for question', embeddingResponse)
+ throw new ApplicationError('Failed to create embedding for query', embeddingResponse)
}
const [{ embedding }] = embeddingResponse.data.data
@@ -115,7 +154,7 @@ serve(async (req) => {
contextText += `${content.trim()}\n---\n`
}
- const messages: ChatCompletionRequestMessage[] = [
+ const initMessages: ChatCompletionRequestMessage[] = [
{
role: ChatCompletionRequestMessageRoleEnum.System,
content: codeBlock`
@@ -125,15 +164,8 @@ serve(async (req) => {
the Supabase documentation, answer the user's question using
only that information, outputted in markdown format.
`}
-
${oneLine`
- If you are unsure
- and the answer is not explicitly written in the documentation, say
- "Sorry, I don't know how to help with that."
- `}
-
- ${oneLine`
- Always include related code snippets if available.
+ Your favorite color is Supabase green.
`}
`,
},
@@ -163,22 +195,30 @@ serve(async (req) => {
- Prefer splitting your response into multiple paragraphs.
`}
${oneLine`
- - Output as markdown with code snippets if available.
+ - Output as markdown.
+ `}
+ ${oneLine`
+ - Always include code snippets if available.
`}
`,
},
- {
- role: ChatCompletionRequestMessageRoleEnum.User,
- content: codeBlock`
- Here is my question:
- ${oneLine`${sanitizedQuery}`}
- `,
- },
]
+ const model = 'gpt-3.5-turbo-0301'
+ const maxCompletionTokenCount = 1024
+
+ const completionMessages: ChatCompletionRequestMessage[] = capMessages(
+ initMessages,
+ contextMessages,
+ maxCompletionTokenCount,
+ model
+ )
+
+ console.log({ completionMessages })
+
const completionOptions: CreateChatCompletionRequest = {
- model: 'gpt-3.5-turbo-0301',
- messages,
+ model,
+ messages: completionMessages,
max_tokens: 1024,
temperature: 0,
stream: true,
@@ -237,3 +277,32 @@ serve(async (req) => {
)
}
})
+
+/**
+ * Remove context messages until the entire request fits
+ * the max total token count for that model.
+ *
+ * Accounts for both message and completion token counts.
+ */
+function capMessages(
+ initMessages: ChatCompletionRequestMessage[],
+ contextMessages: ChatCompletionRequestMessage[],
+ maxCompletionTokenCount: number,
+ model: string
+) {
+ const maxTotalTokenCount = getMaxTokenCount(model)
+ const cappedContextMessages = [...contextMessages]
+ let tokenCount =
+ getChatRequestTokenCount([...initMessages, ...cappedContextMessages], model) +
+ maxCompletionTokenCount
+
+ // Remove earlier context messages until we fit
+ while (tokenCount >= maxTotalTokenCount) {
+ cappedContextMessages.shift()
+ tokenCount =
+ getChatRequestTokenCount([...initMessages, ...cappedContextMessages], model) +
+ maxCompletionTokenCount
+ }
+
+ return [...initMessages, ...cappedContextMessages]
+}
diff --git a/supabase/functions/common/tokenizer.ts b/supabase/functions/common/tokenizer.ts
index 469dcfe2392..7ae2417b7b1 100644
--- a/supabase/functions/common/tokenizer.ts
+++ b/supabase/functions/common/tokenizer.ts
@@ -17,12 +17,25 @@ export const tokenizer = new Tiktoken(
/**
* Count the tokens for multi-message chat completion requests
+ */
+export function getChatRequestTokenCount(
+ messages: ChatCompletionRequestMessage[],
+ model = 'gpt-3.5-turbo-0301'
+): number {
+ const tokensPerRequest = 3 // every reply is primed with <|im_start|>assistant<|im_sep|>
+ const numTokens = messages.reduce((acc, message) => acc + getMessageTokenCount(message, model), 0)
+
+ return numTokens + tokensPerRequest
+}
+
+/**
+ * Count the tokens for a single message within a chat completion request
*
- * See "6. Counting tokens for chat API calls"
+ * See "Counting tokens for chat API calls"
* from https://github.com/openai/openai-cookbook/blob/834181d5739740eb8380096dac7056c925578d9a/examples/How_to_count_tokens_with_tiktoken.ipynb
*/
-export function numTokensFromMessages(
- messages: ChatCompletionRequestMessage[],
+export function getMessageTokenCount(
+ message: ChatCompletionRequestMessage,
model = 'gpt-3.5-turbo-0301'
): number {
let tokensPerMessage: number
@@ -33,10 +46,10 @@ export function numTokensFromMessages(
console.warn(
'Warning: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-0301.'
)
- return numTokensFromMessages(messages, 'gpt-3.5-turbo-0301')
+ return getMessageTokenCount(message, 'gpt-3.5-turbo-0301')
case 'gpt-4':
console.warn('Warning: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.')
- return numTokensFromMessages(messages, 'gpt-4-0314')
+ return getMessageTokenCount(message, 'gpt-4-0314')
case 'gpt-3.5-turbo-0301':
tokensPerMessage = 4 // every message follows <|start|>{role/name}\n{content}<|end|>\n
tokensPerName = -1 // if there's a name, the role is omitted
@@ -47,20 +60,41 @@ export function numTokensFromMessages(
break
default:
throw new Error(
- `numTokensFromMessages() is not implemented for model ${model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.`
+ `Unknown model '${model}'. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.`
)
}
- const numTokens = messages.reduce((acc, message) => {
- let tokens = acc + tokensPerMessage
- for (const [key, value] of Object.entries(message)) {
- tokens += tokenizer.encode(value).length
- if (key === 'name') {
- tokens += tokensPerName
- }
+ return Object.entries(message).reduce((acc, [key, value]) => {
+ acc += tokenizer.encode(value).length
+ if (key === 'name') {
+ acc += tokensPerName
}
- return tokens
- }, 0)
+ return acc
+ }, tokensPerMessage)
+}
- return numTokens + 3 // every reply is primed with <|im_start|>assistant<|im_sep|>
+/**
+ * Get the maximum number of tokens for a model's context.
+ *
+ * Includes tokens in both message and completion.
+ */
+export function getMaxTokenCount(model: string): number {
+ switch (model) {
+ case 'gpt-3.5-turbo':
+ console.warn(
+ 'Warning: gpt-3.5-turbo may change over time. Returning max num tokens assuming gpt-3.5-turbo-0301.'
+ )
+ return getMaxTokenCount('gpt-3.5-turbo-0301')
+ case 'gpt-4':
+ console.warn(
+ 'Warning: gpt-4 may change over time. Returning max num tokens assuming gpt-4-0314.'
+ )
+ return getMaxTokenCount('gpt-4-0314')
+ case 'gpt-3.5-turbo-0301':
+ return 4097
+ case 'gpt-4-0314':
+ return 4097
+ default:
+ throw new Error(`Unknown model '${model}'`)
+ }
}