Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Generate response-based follow up questions

Blue Mouse821f4db8393c
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index 2a696c1dd..6940c4fcb 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -176,6 +176,8 @@ export class AiController {
let toolCallCount = 0
let toolResultCount = 0
let textDeltaCount = 0
+ let assistantText = ''
+ let streamErrored = false
try {
for await (const part of result.fullStream) {
if (clientClosed) {
@@ -190,6 +192,7 @@ export class AiController {
if (part.type === 'text-delta') {
hasContent = true
textDeltaCount++
+ assistantText += part.text
res.write(
`data: ${JSON.stringify({ type: 'text', content: part.text })}\n\n`,
)
@@ -238,6 +241,7 @@ export class AiController {
`data: ${JSON.stringify({ type: 'reasoning', content: part.text })}\n\n`,
)
} else if (part.type === 'error') {
+ streamErrored = true
this.logger.error(
{ error: part.error, pid, uid },
'Error event during AI stream',
@@ -317,6 +321,7 @@ export class AiController {
'AI stream completed - summary',
)
} catch (streamError) {
+ streamErrored = true
this.logger.error(
{ error: streamError, pid, uid },
'Exception during AI stream iteration',
@@ -333,6 +338,34 @@ export class AiController {
}
}
+ // Generate follow-up suggestions only when the assistant produced a real
+ // textual answer and the client is still connected. Capped with a short
+ // timeout so a slow model never delays the `done` event.
+ if (!clientClosed && !streamErrored && assistantText.trim().length > 0) {
+ try {
+ const FOLLOW_UPS_TIMEOUT_MS = 5_000
+ const followUps = await Promise.race([
+ this.aiService.generateFollowUps(
+ [...messages, { role: 'assistant', content: assistantText }],
+ project,
+ ),
+ new Promise<string[]>((resolve) =>
+ setTimeout(() => resolve([]), FOLLOW_UPS_TIMEOUT_MS),
+ ),
+ ])
+ if (!clientClosed && followUps.length > 0) {
+ res.write(
+ `data: ${JSON.stringify({ type: 'followUps', data: followUps })}\n\n`,
+ )
+ }
+ } catch (err) {
+ this.logger.warn(
+ { err, pid, uid },
+ 'Follow-up suggestion generation threw',
+ )
+ }
+ }
+
res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`)
res.end()
diff --git a/backend/apps/cloud/src/ai/ai.service.ts b/backend/apps/cloud/src/ai/ai.service.ts
index 1dd3e722a..d465ac45c 100644
--- a/backend/apps/cloud/src/ai/ai.service.ts
+++ b/backend/apps/cloud/src/ai/ai.service.ts
@@ -129,6 +129,107 @@ export class AiService {
return result
}
+ /**
+ * Generates 0-3 short, project-specific follow-up prompts based on the just-completed
+ * assistant turn. Uses TITLE_MODEL so it doesn't add noticeable latency.
+ * Always resolves; on failure returns an empty array.
+ */
+ async generateFollowUps(
+ messages: ModelMessage[],
+ project: Project,
+ ): Promise<string[]> {
+ if (!process.env.OPENROUTER_API_KEY) {
+ return []
+ }
+
+ if (!messages || messages.length === 0) {
+ return []
+ }
+
+ // Take the tail of the conversation to keep the prompt cheap
+ const tail = messages.slice(-8)
+ const transcript = tail
+ .map((m) => {
+ const role =
+ m.role === 'user'
+ ? 'User'
+ : m.role === 'assistant'
+ ? 'Assistant'
+ : m.role === 'system'
+ ? 'System'
+ : 'Tool'
+ const raw = m.content
+ let content: string
+ if (typeof raw === 'string') {
+ content = raw
+ } else if (Array.isArray(raw)) {
+ content = raw
+ .map((part: any) => {
+ if (typeof part === 'string') return part
+ if (part?.type === 'text' && typeof part.text === 'string')
+ return part.text
+ return ''
+ })
+ .join(' ')
+ } else {
+ content = ''
+ }
+ content = content.trim().replace(/\s+/g, ' ')
+ if (content.length > 800) content = `${content.slice(0, 800)}...`
+ return `${role}: ${content}`
+ })
+ .filter((line) => line.length > line.indexOf(':') + 2)
+ .join('\n\n')
+
+ if (!transcript) return []
+
+ try {
+ const { text } = await generateText({
+ model: this.openrouter.chat(TITLE_MODEL),
+ system:
+ 'Given this analytics conversation, suggest up to 3 short follow-up questions the user might naturally ask next. Each must be a complete question under 70 chars, specific to the data discussed, and answerable by the same toolset (analytics, performance, errors, goals, funnels, sessions, profiles, feature flags, A/B experiments, custom events). Avoid duplicates and avoid restating questions the user already asked. Return STRICT JSON: {"followUps": string[]}. Do not wrap in markdown.',
+ prompt: `Project: "${project.name}"\n\nConversation:\n${transcript}`,
+ temperature: 0.4,
+ })
+
+ const cleaned = (text || '').trim().replace(/^```(?:json)?|```$/g, '')
+ const jsonStart = cleaned.indexOf('{')
+ const jsonEnd = cleaned.lastIndexOf('}')
+ if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
+ return []
+ }
+
+ let parsed: { followUps?: unknown }
+ try {
+ parsed = JSON.parse(cleaned.slice(jsonStart, jsonEnd + 1))
+ } catch {
+ return []
+ }
+
+ if (!Array.isArray(parsed?.followUps)) return []
+
+ const seen = new Set<string>()
+ const followUps: string[] = []
+ for (const item of parsed.followUps) {
+ if (typeof item !== 'string') continue
+ const trimmed = item.trim().replace(/\s+/g, ' ')
+ if (!trimmed || trimmed.length > 120) continue
+ const key = trimmed.toLowerCase()
+ if (seen.has(key)) continue
+ seen.add(key)
+ followUps.push(trimmed)
+ if (followUps.length === 3) break
+ }
+ return followUps
+ } catch (error) {
+ this.logger.warn(
+ { error, pid: project.id },
+ 'Failed to generate follow-up suggestions',
+ )
+ return []
+ }
+ }
+
/**
* Generates a short, descriptive chat title from the first user message
* using a small/fast model so it doesn't slow down the main response.
diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.ts
index 7f9f0a578..ccbcb3162 100644
--- a/backend/apps/cloud/src/ai/dto/chat.dto.ts
+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts
@@ -34,6 +34,18 @@ class ChatMessageDto {
@IsString()
@MaxLength(MAX_MESSAGE_LENGTH)
content: string
+
+ @ApiProperty({
+ required: false,
+ type: [String],
+ description: 'AI-suggested follow-up prompts for this assistant message',
+ })
+ @IsOptional()
+ @IsArray()
+ @ArrayMaxSize(3)
+ @IsString({ each: true })
+ @MaxLength(140, { each: true })
+ followUps?: string[]
}
export class ChatDto {
diff --git a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
index c4d3651f3..9a4a7ef80 100644
--- a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
+++ b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
@@ -14,6 +14,7 @@ import { User } from '../../user/entities/user.entity'
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
+ followUps?: string[]
}
@Entity('ai_chat')
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 0216dd770..f49e41265 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -8,6 +8,7 @@ interface AIStreamCallbacks {
onToolCall?: (toolName: string, args: unknown) => void
onToolResult?: (toolName: string, result: unknown) => void
onReasoning?: (chunk: string) => void
+ onFollowUps?: (suggestions: string[]) => void
onComplete: () => void
onError: (error: Error) => void
}
@@ -73,6 +74,14 @@ export const askAI = async (
callbacks.onToolResult?.(parsed.toolName, parsed.result)
} else if (parsed.type === 'reasoning') {
callbacks.onReasoning?.(parsed.content)
+ } else if (parsed.type === 'followUps') {
+ if (Array.isArray(parsed.data)) {
+ callbacks.onFollowUps?.(
+ parsed.data.filter(
+ (item: unknown): item is string => typeof item === 'string',
+ ),
+ )
+ }
} else if (parsed.type === 'error') {
callbacks.onError(new Error(parsed.content))
} else if (parsed.type === 'done') {
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 9f962654d..e16d1284a 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -10,6 +10,7 @@ import {
WarningCircleIcon,
ArrowDownIcon,
ArrowLeftIcon,
+ ArrowUpRightIcon,
ChartBarIcon,
TargetIcon,
GitBranchIcon,
@@ -70,6 +71,7 @@ interface Message {
reasoning?: string
toolCalls?: Array<{ toolName: string; args: unknown; completed?: boolean }>
parts?: MessagePart[]
+ followUps?: string[]
}
interface AskAIViewProps {
@@ -509,6 +511,8 @@ const AssistantMessage = ({
onFeedback,
feedback,
canRegenerate,
+ followUps,
+ onFollowUpClick,
}: {
message: Message
isStreaming?: boolean
@@ -516,6 +520,8 @@ const AssistantMessage = ({
onFeedback?: (rating: 'good' | 'bad') => void
feedback?: 'good' | 'bad' | null
canRegenerate?: boolean
+ followUps?: string[]
+ onFollowUpClick?: (prompt: string) => void
}) => {
const { t } = useTranslation('common')
const [userToggled, setUserToggled] = useState(false)
@@ -614,6 +620,33 @@ const AssistantMessage = ({
</>
)}
+ {!isStreaming &&
+ hasContent &&
+ followUps &&
+ followUps.length > 0 &&
+ onFollowUpClick ? (
+ <div
+ role='group'
+ aria-label={t('project.askAi.followUps.title')}
+ className='mt-4 border-t border-gray-200/80 dark:border-slate-800/80'
+ >
+ {_map(followUps, (suggestion, idx) => (
+ <button
+ key={`${idx}-${suggestion}`}
+ type='button'
+ onClick={() => onFollowUpClick(suggestion)}
+ className='group/row flex w-full items-center justify-between gap-4 border-b border-gray-200/80 py-2.5 text-left text-sm text-gray-600 transition-colors last:border-b-0 hover:text-gray-900 dark:border-slate-800/80 dark:text-gray-400 dark:hover:text-white'
+ >
+ <span className='flex-1 leading-snug'>{suggestion}</span>
+ <ArrowUpRightIcon
+ weight='bold'
+ className='h-4 w-4 shrink-0 text-gray-300 transition-all group-hover/row:translate-x-0.5 group-hover/row:-translate-y-0.5 group-hover/row:text-gray-700 dark:text-slate-600 dark:group-hover/row:text-gray-200'
+ />
+ </button>
+ ))}
+ </div>
+ ) : null}
+
{!isStreaming && hasContent ? (
<div className='mt-1 flex items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100'>
<button
@@ -845,7 +878,11 @@ const getSuggestionPrompts = (t: any) => [
interface AIChat {
id: string
name: string | null
- messages: { role: 'user' | 'assistant'; content: string }[]
+ messages: {
+ role: 'user' | 'assistant'
+ content: string
+ followUps?: string[]
+ }[]
isOwner?: boolean
branched?: boolean
created: string
@@ -910,6 +947,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
>([])
const streamingPartsRef = useRef<MessagePart[]>([])
const currentTextPartRef = useRef('')
+ const streamingFollowUpsRef = useRef<string[] | null>(null)
const generateMessageId = () =>
`msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
@@ -1010,6 +1048,12 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
id: generateMessageId(),
role: m.role,
content: m.content,
+ followUps:
+ m.role === 'assistant' &&
+ Array.isArray(m.followUps) &&
+ m.followUps.length > 0
+ ? m.followUps
+ : undefined,
})),
)
setCurrentChatId(chat.id)
@@ -1035,11 +1079,26 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
[loadChat],
)
+ const serialiseMessageForApi = (m: Message) => {
+ const base: {
+ role: 'user' | 'assistant'
+ content: string
+ followUps?: string[]
+ } = {
+ role: m.role,
+ content: m.content,
+ }
+ if (m.role === 'assistant' && m.followUps && m.followUps.length > 0) {
+ base.followUps = m.followUps
+ }
+ return base
+ }
+
const updateChatMessages = useCallback(
(chatId: string, messagesToSave: Message[]) => {
const apiMessages = messagesToSave
.filter((m) => m.content.trim().length > 0)
- .map((m) => ({ role: m.role, content: m.content }))
+ .map(serialiseMessageForApi)
if (apiMessages.length === 0) return
@@ -1057,7 +1116,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
(firstMessages: Message[]) => {
const apiMessages = firstMessages
.filter((m) => m.content.trim().length > 0)
- .map((m) => ({ role: m.role, content: m.content }))
+ .map(serialiseMessageForApi)
if (apiMessages.length === 0) return
@@ -1250,6 +1309,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
streamingToolCallsRef.current = []
streamingPartsRef.current = []
currentTextPartRef.current = ''
+ streamingFollowUpsRef.current = null
abortControllerRef.current = new AbortController()
@@ -1335,6 +1395,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
},
)
},
+ onFollowUps: (suggestions) => {
+ streamingFollowUpsRef.current = suggestions
+ },
onComplete: () => {
const finalContent = streamingContentRef.current
@@ -1349,6 +1412,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
finalContent.trim() ||
streamingToolCallsRef.current.length > 0
) {
+ const followUps = streamingFollowUpsRef.current
const assistantMessage: Message = {
id: generateMessageId(),
role: 'assistant',
@@ -1356,6 +1420,8 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
reasoning: streamingReasoningRef.current,
toolCalls: streamingToolCallsRef.current,
parts: streamingPartsRef.current,
+ followUps:
+ followUps && followUps.length > 0 ? followUps : undefined,
}
setMessages((prev) => {
const updatedMessages = [...prev, assistantMessage]
@@ -1516,6 +1582,30 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
inputRef.current?.focus()
}
+ const handleFollowUpClick = useCallback(
+ async (prompt: string) => {
+ if (isLoading) return
+ const trimmed = prompt.trim()
+ if (!trimmed) return
+
+ const userMessage: Message = {
+ id: generateMessageId(),
+ role: 'user',
+ content: trimmed,
+ }
+ const newMessages = [...messages, userMessage]
+ setMessages(newMessages)
+ setInput('')
+
+ if (!currentChatIdRef.current) {
+ createChatWithMessage(newMessages)
+ }
+
+ await runChatTurn(newMessages)
+ },
+ [createChatWithMessage, isLoading, messages, runChatTurn],
+ )
+
const handleCopyLink = () => {
const baseUrl = window.location.origin + window.location.pathname
const chatParam = currentChatId ? `&chat=${currentChatId}` : ''
@@ -1725,6 +1815,17 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
}
feedback={feedbackMap[msg.id] ?? null}
canRegenerate={isLastAssistant && !isLoading}
+ followUps={
+ isLastAssistant &&
+ !isLoading &&
+ !streamingMessage &&
+ !isWaitingForResponse
+ ? msg.followUps
+ : undefined
+ }
+ onFollowUpClick={
+ isLastAssistant ? handleFollowUpClick : undefined
+ }
/>
)
})
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index e16542f65..2de675d0c 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2170,6 +2170,9 @@
"mobilePerformance": "How does my site perform on mobile?",
"deviceTypesChart": "Create a pie chart of most common device types"
},
+ "followUps": {
+ "title": "You might also ask"
+ },
"dismiss": "Dismiss",
"stop": "Stop",
"loadMore": "Load more",