# Follow-up questions

Ways to request additional information from users to help generate more accurate and relevant responses.

## Key UX concepts

### Gather context at the right time

Decide whether to gather information before showing output or during the interaction. For high-impact decisions or when confidence is low, collect details first. When multiple questions are needed, collecting them sequentially reduces cognitive load and keeps each decision focused. For other scenarios, start with an initial response and ask follow-up questions to refine results.

### Streamline user choices

Provide clear options for users to proceed, skip, or exit at each step of the interaction. This ensures users feel in control of the experience and reduces friction. When structured options don't meet the user's needs, ensure they can always access the prompt input to provide open-ended context in their own words.

### Guide users to necessary information

Help users access information that isn't readily available. Provide links or instructions on where to find required data when appropriate. This ensures users can provide accurate information even when it's not immediately at hand.

## Criteria table

| **Information type** | **Input method** | **Examples** |
| --- | --- | --- |
| **Clarifying user intent** | Present sequential predefined choices in a dismissible dialog docked above prompt input. | Context is needed upfront to generate an accurate response. Multiple back-and forth exchanges would otherwise be required. |
| **Guiding a conversation** | Present recommended inputs with [support prompt group](/components/support-prompt-group/index.html.md)  . | The initial response applies broadly to multiple situations. A follow-up selection narrows it to the user's specific case. There are up to five valid choices. |

## Common use cases

### Clarifying user intent

When users provide ambiguous or incomplete information, or when a request requires additional information to generate an accurate response, a dismissible dialog collects structured input upfront, reducing back-and-forth exchanges in the thread.

### AI assistant

JD I need to optimize EC2 costs across multiple regions. I have a few questions to make sure I provide targeted recommendations to optimize your EC2 costs. What's your main goal?
- 1 of 2

1 Reduce costs for development environments 2 Optimize production workload spending Something else Skip Use of this service is subject to the [AWS Responsible AI Policy](https://aws.amazon.com/machine-learning/responsible-ai/policy/)
```gen-ai-followup-question-dialog.tsx
import React, { useState } from 'react';
import Badge from '@cloudscape-design/components/badge';
import Box from '@cloudscape-design/components/box';
import Button from '@cloudscape-design/components/button';
import ChatBubble from '@cloudscape-design/chat-components/chat-bubble';
import Container from '@cloudscape-design/components/container';
import Dialog from '@cloudscape-design/components/dialog';
import Header from '@cloudscape-design/components/header';
import Input from '@cloudscape-design/components/input';
import OptionList, { OptionListProps } from '@cloudscape-design/components/option-list';
import Pagination from '@cloudscape-design/components/pagination';
import SpaceBetween from '@cloudscape-design/components/space-between';
import StatusIndicator from '@cloudscape-design/components/status-indicator';
import PromptInput from '@cloudscape-design/components/prompt-input';
import ButtonGroup from '@cloudscape-design/components/button-group';
import Link from '@cloudscape-design/components/link';
import { IconProps } from '@cloudscape-design/components/icon';
import Avatar from '@cloudscape-design/chat-components/avatar';

const CustomGenAIChatFooter = ({
  actionButtonIconName,
  actionButtonAriaLabel,
  message,
  onSendMessage,
  onAction,
}: {
  actionButtonIconName: IconProps.Name;
  actionButtonAriaLabel: string;
  message?: string;
  onSendMessage?: (text: string) => void;
  onAction?: (text: string) => void;
}) => {
  return (
    <SpaceBetween size="xs">
      <PromptInput
        value={message ?? ''}
        onChange={({ detail }) => onSendMessage?.(detail.value)}
        onAction={({ detail }) => onAction?.(detail.value)}
        disableSecondaryActionsPaddings
        actionButtonAriaLabel={actionButtonAriaLabel}
        actionButtonIconName={actionButtonIconName}
        secondaryActions={
          <Box padding={{ left: 'xxs', top: 'xs' }}>
            <ButtonGroup
              ariaLabel="Additional chat input actions"
              items={[
                {
                  type: 'icon-button',
                  id: 'upload-files',
                  iconName: 'upload',
                  text: 'Upload files',
                },
                {
                  type: 'icon-button',
                  id: 'add-reference',
                  iconName: 'at-symbol',
                  text: 'Add reference or citation',
                },
              ]}
              variant="icon"
            />
          </Box>
        }
      />
      <Box fontSize="body-s" color="text-body-secondary">
        Use of this service is subject to the{' '}
        <Link external variant="primary" href="https://aws.amazon.com/machine-learning/responsible-ai/policy/">
          AWS Responsible AI Policy
        </Link>
      </Box>
    </SpaceBetween>
  );
};

const userName = 'John Doe';
const genAiName = 'AI assistant';
const genAiAvatarAriaLabel = 'Avatar of AI assistant';

const userAvatar = <Avatar ariaLabel={`Avatar of ${userName}`} initials="JD" tooltipText={userName} />;

const genAiAvatar = (
  <Avatar ariaLabel={genAiAvatarAriaLabel} color="gen-ai" iconName="gen-ai" tooltipText={genAiName} />
);

const toOptions = (labels: string[]): OptionListProps.Option[] =>
  labels.map((label, index) => ({ value: label, label, icon: <Badge>{index + 1}</Badge> }));

const questions = [
  {
    header: "What's your main goal?",
    options: toOptions(['Reduce costs for development environments', 'Optimize production workload spending']),
  },
  {
    header: 'Any specific constraints I should know about?',
    options: toOptions(['Must maintain high availability', 'Need to keep certain instances running 24/7']),
  },
];

export default function GenAiFollowUpQuestionDialog() {
  const [answers, setAnswers] = useState<Record<number, ReadonlyArray<OptionListProps.Option>>>({});
  const [questionNumber, setQuestionNumber] = useState(1);
  const [showDialog, setShowDialog] = useState(true);
  const [editingCustomAnswer, setEditingCustomAnswer] = useState(false);
  const [customAnswerDraft, setCustomAnswerDraft] = useState('');
  const [customAnswers, setCustomAnswers] = useState<Record<number, string>>({});
  const [prompt, setPrompt] = useState('');
  const question = questions[questionNumber - 1];
  const isLastQuestion = questionNumber === questions.length;
  const customAnswer = customAnswers[questionNumber];

  // Answering a question moves to the next one, or sends the answers on the last question.
  const advance = () => {
    if (isLastQuestion) {
      setShowDialog(false);
    } else {
      setQuestionNumber(questionNumber + 1);
    }
  };

  // A question has one answer, so a custom answer replaces the selected option.
  const saveCustomAnswer = () => {
    setCustomAnswers({ ...customAnswers, [questionNumber]: customAnswerDraft });
    setAnswers({ ...answers, [questionNumber]: [] });
    setEditingCustomAnswer(false);
    advance();
  };

  const editCustomAnswer = () => {
    setCustomAnswerDraft(customAnswer ?? '');
    setEditingCustomAnswer(true);
  };

  // Sending a prompt restarts the follow-up questions.
  const sendPrompt = () => {
    setPrompt('');
    setAnswers({});
    setCustomAnswers({});
    setEditingCustomAnswer(false);
    setQuestionNumber(1);
    setShowDialog(true);
  };

  return (
    <Container
      header={<Header variant="h3">AI assistant</Header>}
      footer={
        <SpaceBetween size="xs">
          {showDialog && (
            <Dialog
              header={question.header}
              onDismiss={() => setShowDialog(false)}
              i18nStrings={{ dismissAriaLabel: 'Close dialog' }}
              headerActions={
                <Pagination
                  pagesVariant="compact"
                  currentPageIndex={questionNumber}
                  pagesCount={questions.length}
                  onChange={({ detail }) => {
                    setQuestionNumber(detail.currentPageIndex);
                    setEditingCustomAnswer(false);
                  }}
                  i18nStrings={{
                    pagesCompactText: ({ currentPage, pagesCount }) => `${currentPage} of ${pagesCount}`,
                  }}
                  ariaLabels={{
                    nextPageLabel: 'Next question',
                    previousPageLabel: 'Previous question',
                    paginationLabel: 'Questions',
                  }}
                />
              }
              footer={
                <>
                  <Box float="left">
                    {editingCustomAnswer ? (
                      <SpaceBetween direction="horizontal" size="xxs" alignItems="center">
                        <Input
                          autoFocus
                          value={customAnswerDraft}
                          onChange={({ detail }) => setCustomAnswerDraft(detail.value)}
                          ariaLabel="Something else"
                        />
                        <Button
                          variant="inline-icon"
                          iconName="close"
                          ariaLabel="Cancel"
                          onClick={() => setEditingCustomAnswer(false)}
                        />
                        <Button
                          variant="inline-icon"
                          iconName="check"
                          ariaLabel="Save answer"
                          onClick={saveCustomAnswer}
                        />
                      </SpaceBetween>
                    ) : customAnswer ? (
                      <SpaceBetween direction="horizontal" size="xs" alignItems="center">
                        <StatusIndicator type="success">{customAnswer}</StatusIndicator>
                        <Button
                          variant="inline-icon"
                          iconName="edit"
                          ariaLabel="Edit answer"
                          onClick={editCustomAnswer}
                        />
                      </SpaceBetween>
                    ) : (
                      <Button variant="link" iconName="edit" iconAlign="right" onClick={editCustomAnswer}>
                        Something else
                      </Button>
                    )}
                  </Box>
                  <Box float="right">
                    <Button onClick={advance}>{isLastQuestion ? 'Send' : 'Skip'}</Button>
                  </Box>
                </>
              }
            >
              <OptionList
                ariaLabel={question.header}
                selectionType="single"
                options={question.options}
                selectedOptions={answers[questionNumber] ?? []}
                onChange={({ detail }) => {
                  setAnswers({ ...answers, [questionNumber]: detail.selectedOptions });
                  setCustomAnswers({ ...customAnswers, [questionNumber]: '' });
                  advance();
                }}
                i18nStrings={{ selectedAriaLabel: 'Selected' }}
              />
            </Dialog>
          )}
          <CustomGenAIChatFooter
            actionButtonIconName="send"
            actionButtonAriaLabel="Send message"
            message={prompt}
            onSendMessage={setPrompt}
            onAction={sendPrompt}
          />
        </SpaceBetween>
      }
    >
      <SpaceBetween size="xs">
        <ChatBubble avatar={userAvatar} type="outgoing" ariaLabel={`${userName} at 05:37:30pm`}>
          I need to optimize EC2 costs across multiple regions.
        </ChatBubble>
        <ChatBubble avatar={genAiAvatar} type="incoming" ariaLabel={`${genAiName} at 05:37:40pm`}>
          I have a few questions to make sure I provide targeted recommendations to optimize your EC2 costs.
        </ChatBubble>
      </SpaceBetween>
    </Container>
  );
}
```

### Guiding a conversation

When an initial response applies broadly but a follow-up selection can tailor it to the user's specific situation, a [support prompt group](/components/support-prompt-group/index.html.md) presents a constrained set of options after the response.

### AI assistant

JD I need to choose between AWS Fargate and ECS on EC2 for my containerized application. Both are great options for running containers. Here are the key differences:

AWS Fargate:

[1]

1. Serverless - no need to manage infrastructure
2. Pay only for resources used by containers
3. Easier to get started and maintain

ECS on EC2:

[2]

1. More control over underlying infrastructure
2. Better cost optimization for consistent workloads
3. Access to instance-level customization

Sources [[1] Simplify compute management with AWS Fargate](https://docs.aws.amazon.com/eks/latest/userguide/fargate.html) [[2] What is Amazon EC2?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) To provide a more tailored recommendation, what's your primary concern when choosing a container orchestration solution?

Minimize management overhead Maximize control over infrastructure Optimize cost
```gen-ai-followup-guided-selection.tsx
import React, { type CSSProperties } from 'react';
import Box from '@cloudscape-design/components/box';
import ChatBubble from '@cloudscape-design/chat-components/chat-bubble';
import Container from '@cloudscape-design/components/container';
import Header from '@cloudscape-design/components/header';
import SupportPromptGroup from '@cloudscape-design/chat-components/support-prompt-group';
import SpaceBetween from '@cloudscape-design/components/space-between';
import TextContent from '@cloudscape-design/components/text-content';
import ExpandableSection from '@cloudscape-design/components/expandable-section';
import Link from '@cloudscape-design/components/link';
import Avatar from '@cloudscape-design/chat-components/avatar';
import ButtonGroup from '@cloudscape-design/components/button-group';
import StatusIndicator from '@cloudscape-design/components/status-indicator';
import Popover from '@cloudscape-design/components/popover';
import { spaceScaledXs } from '@cloudscape-design/design-tokens/index.js';

type Sources = Array<{ href: string; description: string }>;

const ExpandableSources = ({ sources }: { sources: Sources }) => (
  <ExpandableSection headerText="Sources">
    {sources.map(({ href, description }, index) => (
      <div key={index}>
        <Link href={href} external variant="primary">
          [{index + 1}] {description}
        </Link>
      </div>
    ))}
  </ExpandableSection>
);

const userName = 'John Doe';
const genAiName = 'AI assistant';
const genAiAvatarAriaLabel = 'Avatar of AI assistant';

const userAvatar = <Avatar ariaLabel={`Avatar of ${userName}`} initials="JD" tooltipText={userName} />;

const genAiAvatar = (
  <Avatar ariaLabel={genAiAvatarAriaLabel} color="gen-ai" iconName="gen-ai" tooltipText={genAiName} />
);

const chatBubbleActions = (
  <ButtonGroup
    ariaLabel="Chat bubble actions"
    variant="icon"
    items={[
      {
        type: 'group',
        text: 'Feedback',
        items: [
          {
            type: 'icon-button',
            id: 'helpful',
            iconName: 'thumbs-up',
            text: 'Helpful',
          },
          {
            type: 'icon-button',
            id: 'not-helpful',
            iconName: 'thumbs-down',
            text: 'Not helpful',
          },
        ],
      },
      {
        type: 'icon-button',
        id: 'copy',
        iconName: 'copy',
        text: 'Copy',
        popoverFeedback: <StatusIndicator type="success">Message copied</StatusIndicator>,
      },
    ]}
  />
);

const CitationPopover = ({ count, href }: { count: number; href: string }) => (
  <Box color="text-status-info" display="inline">
    <Popover
      header="Source"
      content={
        <Link href={href} external variant="primary">
          {href}
        </Link>
      }
      position="right"
    >
      [{count}]
    </Popover>
  </Box>
);

/**
 * Aligns content placed under a chat bubble (actions, artifacts, follow-up prompts) with
 * the bubble text: the avatar width (28px) plus the gap between avatar and bubble.
 */
const chatBubbleIndentationStyle: CSSProperties = {
  marginInlineStart: `calc(28px + ${spaceScaledXs})`,
};

const sources: Sources = [
  {
    href: 'https://docs.aws.amazon.com/eks/latest/userguide/fargate.html',
    description: 'Simplify compute management with AWS Fargate',
  },
  {
    href: 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html',
    description: 'What is Amazon EC2?',
  },
];

export default function GenAiFollowUpClarifyIntent() {
  return (
    <Container header={<Header variant="h3">AI assistant</Header>}>
      <SpaceBetween size="xs">
        <ChatBubble avatar={userAvatar} type="outgoing" ariaLabel={`${userName} at 05:37:30pm`}>
          I need to choose between AWS Fargate and ECS on EC2 for my containerized application.
        </ChatBubble>
        <ChatBubble
          avatar={genAiAvatar}
          type="incoming"
          ariaLabel="AI assistant at 05:37:40pm"
          actions={chatBubbleActions}
        >
          <TextContent>
            <p>Both are great options for running containers. Here are the key differences:</p>
            <p>
              AWS Fargate: <CitationPopover count={1} href={sources[0].href} />
            </p>
            <ol>
              <li>Serverless - no need to manage infrastructure</li>
              <li>Pay only for resources used by containers</li>
              <li>Easier to get started and maintain</li>
            </ol>
            <p>
              ECS on EC2: <CitationPopover count={2} href={sources[1].href} />
            </p>
            <ol>
              <li>More control over underlying infrastructure</li>
              <li>Better cost optimization for consistent workloads</li>
              <li>Access to instance-level customization</li>
            </ol>
          </TextContent>
          <Box padding={{ top: 'xs' }}>
            <ExpandableSources sources={sources} />
          </Box>
        </ChatBubble>
        <ChatBubble avatar={genAiAvatar} type="incoming" ariaLabel="AI assistant at 05:37:50pm">
          <Box variant="p">
            To provide a more tailored recommendation, what&apos;s your primary concern when choosing a container
            orchestration solution?
          </Box>
        </ChatBubble>
        <div style={chatBubbleIndentationStyle}>
          <SupportPromptGroup
            ariaLabel="Proposed prompts"
            onItemClick={() => null}
            items={[
              { id: 'minmize-management-overhead', text: 'Minimize management overhead' },
              { id: 'maxmimize-control-over-infrastructure', text: 'Maximize control over infrastructure' },
              { id: 'optimize-cost', text: 'Optimize cost' },
            ]}
          />
        </div>
      </SpaceBetween>
    </Container>
  );
}
```

## General guidelines

### Do

- Use structured input methods to collect follow-up information instead of open-ended text prompts.
- To avoid overwhelming the user, limit follow-up questions to 5 or fewer per workflow.
- Order options by relevance, with the most likely match first.

### Don't

- Avoid requiring users to formulate free-text responses when predefined choices or structured inputs can capture the same information more efficiently.
- Don't ask for information already provided or data that can be retrieved automatically through APIs.

## Writing guidelines

### General writing guidelines

- Use sentence case, but continue to capitalize proper nouns and brand names correctly in context.
- Use end punctuation, except in [headers](/components/header/index.html.md)   and [buttons](/components/button/index.html.md)   . Don't use exclamation points.
- Use present-tense verbs and active voice.
- Don't use *please*   , *thank you*   , ellipsis ( *...*   ), ampersand ( *&*   ), *e.g.*   , *i.e.*   , or *etc.*   in writing.
- Avoid directional language.  

  - For example: use *previous*     not *above*     , use *following*     not *below*    .
- Use device-independent language.  

  - For example: use *choose*     or *select*     not *click*    .

### Component-specific guidelines

#### Dialog title

- Be specific and action-oriented. Dialog titles should clearly indicate the action being performed or the purpose of the dialog, often by combining an action verb with the resource or concept involved.  

  - For example: *Any specific constraints I should know about?*

#### Placeholder text

- Use placeholder text to provide a brief example or hint of the expected input format, not as a replacement for a label.
- Keep placeholder text concise and descriptive enough to guide the user without cluttering the input field.

#### Button text

- If the button performs the primary action indicated in the dialog title, the verb used in the button label should match the verb in the title.
- Follow the writing guidelines for [button](/components/button/index.html.md)  .

#### Support prompts

- Limit support prompt labels to less than 72 characters.  

  - Follow writing guidelines for [support prompt group](/components/support-prompt-group/index.html.md)

## Accessibility guidelines

### General accessibility guidelines

- Follow the guidelines on alternative text and Accessible Rich Internet Applications (ARIA) regions for each component.
- Make sure to define ARIA labels aligned with the language context of your application.
- Don't add unnecessary markup for roles and landmarks. Follow the guidelines for each component.
- Provide keyboard functionality to all available content in a logical and predictable order. The flow of information should make sense.






## Search Cloudscape