-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Docs: Guide on how to add follow-up questions #8821
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FranciscoMoretti
wants to merge
2
commits into
vercel:main
Choose a base branch
from
FranciscoMoretti:guide-follow-up-questions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| --- | ||
| title: Follow-up questions | ||
| description: Learn how to use the AI SDK to add follow-up questions to your chat app. | ||
| tags: ['agents', 'chatbot'] | ||
| --- | ||
|
|
||
| # Add follow-up questions to your AI chat app | ||
|
|
||
| Follow-up questions keep users engaged in your AI app. They provide natural conversation starters when users hit a dead end. This guide shows you how to build them using [AI SDK](https://ai-sdk.dev/)'s streaming data parts feature. | ||
|
|
||
| You'll see code that streams suggestions as they're generated, thanks to the partial object streaming feature. The result feels smooth and professional. | ||
|
|
||
|
|
||
| ## Set up the backend suggestion generator | ||
|
|
||
| Create a function that takes your conversation history and asks the AI model to generate relevant follow-up questions. This function uses structured output to return an array of short, actionable questions. | ||
|
|
||
| ```typescript | ||
| import { streamObject, type ModelMessage } from 'ai' | ||
| import { z } from 'zod' | ||
|
|
||
| const DEFAULT_FOLLOWUP_SUGGESTIONS_MODEL = 'google/gemini-2.5-flash-lite' | ||
|
|
||
| function generateFollowupSuggestions(modelMessages: ModelMessage[]) { | ||
| const maxQuestionCount = 5 | ||
| const minQuestionCount = 3 | ||
| const maxCharactersPerQuestion = 80 | ||
|
|
||
| return streamObject({ | ||
| model: DEFAULT_FOLLOWUP_SUGGESTIONS_MODEL, | ||
| messages: [ | ||
| ...modelMessages, | ||
| { | ||
| role: 'user', | ||
| content: `What question should I ask next? Return an array of suggested questions (minimum ${minQuestionCount}, maximum ${maxQuestionCount}). Each question should be no more than ${maxCharactersPerQuestion} characters.`, | ||
| }, | ||
| ], | ||
| schema: z.object({ | ||
| suggestions: z.array(z.string()).min(minQuestionCount).max(maxQuestionCount), | ||
| }), | ||
| }) | ||
| } | ||
| ``` | ||
|
|
||
| These constraints are important. You want 3-5 questions maximum, each under 80 characters. For model selection, use a fast, inexpensive model here. Suggestions don't need your most powerful model, and users shouldn't have to wait for them. | ||
|
|
||
| ## Stream suggestions to the frontend | ||
|
|
||
| Build a streaming function that sends suggestions to your frontend as they're generated. This uses AI SDK's custom data parts feature to create type-safe parts. By reading from the `partialObjectStream`, we get a smooth user experience where suggestions appear in real-time, not in a batch after completion. By using the same `id` in the data, each time it writes a new chunk, it will replace the previous one. | ||
|
|
||
| Here's the streaming function that writes suggestions as they're created: | ||
|
|
||
| ```typescript | ||
| async function streamFollowupSuggestions({ | ||
| followupSuggestionsResult, | ||
| writer, | ||
| }: { | ||
| followupSuggestionsResult: ReturnType<typeof generateFollowupSuggestions> | ||
| writer: StreamWriter | ||
| }) { | ||
| const dataPartId = crypto.randomUUID() | ||
|
|
||
| for await (const chunk of followupSuggestionsResult.partialObjectStream) { | ||
| writer.write({ | ||
| id: dataPartId, | ||
| type: 'data-followupSuggestions', | ||
| data: { | ||
| suggestions: chunk.suggestions?.filter((suggestion) => suggestion !== undefined) ?? [], | ||
| }, | ||
| }) | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| You need to define the data type for your suggestions. Add this to the file that has your ChatMessage definition: | ||
|
|
||
| ```typescript | ||
| type FollowupSuggestions = { | ||
| suggestions: string[] | ||
| } | ||
|
|
||
| export type CustomUIDataTypes = { | ||
| // ... your existing types | ||
| followupSuggestions: FollowupSuggestions | ||
| } | ||
|
|
||
| export type ChatMessage = UIMessage<MessageMetadata, CustomUIDataTypes, ChatTools> | ||
| ``` | ||
|
|
||
| ## Create the UI components | ||
|
|
||
| Build React components that display the suggestions and handle user clicks. The components need to integrate with your existing chat state management and trigger new messages when users select a suggestion. | ||
|
|
||
| Create a new file `components/followup-suggestions.tsx`: | ||
|
|
||
| ```tsx | ||
| 'use client' | ||
|
|
||
| import type { ChatMessage } from '@/lib/ai/types' | ||
| import { useCallback } from 'react' | ||
| import { Button } from './ui/button' | ||
| import { Separator } from './ui/separator' | ||
|
|
||
| export function FollowUpSuggestions({ | ||
| message, | ||
| sendMessage, | ||
| }: { | ||
| message: ChatMessage | ||
| sendMessage: UseChatHelpers<ChatMessage>['sendMessage'] | ||
| }) { | ||
| const suggestions = message.parts.find((p) => p.type === 'data-followupSuggestions')?.data | ||
| .suggestions | ||
|
|
||
| const handleClick = useCallback( | ||
| (suggestion: string) => { | ||
| sendMessage({ text: suggestion }) | ||
| }, | ||
| [sendMessage] | ||
| ) | ||
|
|
||
| if (!suggestions || suggestions.length === 0) return null | ||
|
|
||
| return ( | ||
| <div className={'mb-2 mt-3 flex flex-col gap-2'}> | ||
| <div className="text-base font-medium">Related</div> | ||
| <div className="flex flex-wrap items-center gap-y-1"> | ||
| {suggestions.map((s, i) => ( | ||
| <div key={s} className="flex w-full flex-col"> | ||
| <button | ||
| type="button" | ||
| onClick={() => handleClick(s)} | ||
| className="w-full cursor-pointer py-2 text-left text-foreground hover:text-primary" | ||
| > | ||
| {s} | ||
| </button> | ||
| {i < suggestions.length - 1 && <hr className="h-px w-full border-0 bg-border" />} | ||
| </div> | ||
| ))} | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
| ``` | ||
|
|
||
| This component handles click interactions by creating a new message and sending it through your chat system. It preserves the current model selection and tool settings. | ||
|
|
||
| The component works with AI SDK's message parts system. It finds the right part by type and renders the suggestions. | ||
|
|
||
| Finally, add the component to your assistant message. This shows follow-up suggestions after each AI response. | ||
|
|
||
| ```tsx | ||
| import { FollowUpSuggestions } from './followup-suggestions' | ||
|
|
||
| const AssistantMessage = ({ | ||
| message, | ||
| sendMessage, | ||
| }: { | ||
| message: ChatMessage | ||
| sendMessage: UseChatHelpers<ChatMessage>['sendMessage'] | ||
| }) => { | ||
| return ( | ||
| <div className="relative flex flex-col gap-2"> | ||
| {/* ... render other parts of the message */} | ||
|
|
||
| <FollowUpSuggestions message={message} sendMessage={sendMessage} /> | ||
| </div> | ||
| ) | ||
| } | ||
| ``` | ||
|
|
||
| ## Integrate with your chat API | ||
|
|
||
| Connect everything in your chat route handler. After streaming the main AI response, generate and stream follow-up suggestions using the complete conversation context. This happens automatically without blocking the main response. | ||
|
|
||
| Update your chat POST handler by adding the `generateFollowupSuggestions` and `streamFollowupSuggestions` functions. The key changes are in the `execute` function: | ||
|
|
||
| ```typescript | ||
| const stream = createUIMessageStream<ChatMessage>({ | ||
| execute: async ({ writer: dataStream }) => { | ||
| const result = streamText({ | ||
| model: mainModel, | ||
| messages: modelMessages, | ||
| }) | ||
|
|
||
| dataStream.merge(result.toUIMessageStream()) | ||
|
|
||
| // Wait for the main response to complete | ||
| await result.consumeStream() | ||
|
|
||
| const response = await result.response | ||
| const responseMessages = response.messages | ||
|
|
||
| // Generate and stream follow-up suggestions | ||
| const followupSuggestionsResult = generateFollowupSuggestions([ | ||
| ...contextForLLM, | ||
| ...responseMessages, | ||
| ]) | ||
| await streamFollowupSuggestions({ | ||
| followupSuggestionsResult, | ||
| writer: dataStream, | ||
| }) | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| You must await the response first to let the main AI response finish streaming. Then you get the complete response messages and use them as context for generating suggestions. | ||
|
|
||
| This means users see the AI response first, then suggestions appear afterward. The suggestions have full context from both the conversation history and the AI's complete response. | ||
|
|
||
| That's it. Your follow-up questions will now stream in after each AI response, keeping users engaged and providing natural conversation starters. The entire system works end-to-end with type safety and smooth streaming. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
UseChatHelperstype is used without being imported from the AI SDK, which will cause a TypeScript compilation error.View Details
📝 Patch Details
Analysis
Missing import for UseChatHelpers type causes TypeScript compilation error
What fails: Component type definitions in
content/cookbook/00-guides/06-follow-up-questions.mdxreferenceUseChatHelpers<ChatMessage>['sendMessage']on lines 109 and 159 without importing the type from@ai-sdk/reactHow to reproduce:
# Run TypeScript compilation on the cookbook file npx tsc --noEmit content/cookbook/00-guides/06-follow-up-questions.mdxResult: TypeScript error: "Cannot find name 'UseChatHelpers'"
Expected: Type should be properly imported from
@ai-sdk/reactpackage, as confirmed by the AI SDK React source code whereUseChatHelpersis exportedFix: Added
import type { UseChatHelpers } from '@ai-sdk/react'to the component imports