본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

채팅 맥락

원문 보기 위키 갱신

채팅 맥락 (In-chat context)

이 패턴은 사용자가 채팅 상호작용 중에 에이전트에게 맥락을 제공하는 방법을 다룹니다. 외부 서비스 연결, 로컬 파일 업로드, 프롬프트에서의 자연어 맥락 제공 등 사용 사례를 다루며, 맥락이 어디에 있는지에 맞는 방법을 선택하고 이해된 내용을 확인하며 설정 마찰을 최소화하는 것을 강조합니다.

출처: 문서

본문

이 패턴은 사용자가 채팅 상호작용 중에 에이전트에게 맥락을 제공하는 방법을 다룹니다.

핵심 UX 개념 (Key UX concepts)

맥락 소스에 방법을 맞추세요 (Match the method to the context source)

맥락이 대화에 들어오는 방식은 그것이 어디에 있는지를 반영해야 합니다. 외부 또는 서드파티 서비스는 사용자 환경 밖의 인증(authorization)이 필요할 수 있습니다. 로컬 파일은 업로드 어포던스가 필요합니다. 사용자 머릿속의 지식은 자연어가 필요합니다.

무엇이 이해되었는지 확인하세요 (Confirm what was understood)

맥락이 제공된 후 에이전트는 받은 것과 그것을 어떻게 사용할지 인정해야 합니다. 이는 맥락이 올바르게 해석되었는지에 대한 신뢰를 구축하고, 사용자가 에이전트가 맥락에 따라 행동하기 전에 오해를 바로잡을 기회를 제공합니다.

설정 마찰을 최소화하세요 (Minimize setup friction)

맥락 추가는 폼을 작성하는 것 같은 느낌이 아니라 가볍게 느껴져야 합니다. 추론할 수 있는 것은 미리 채우고, 완료된 단계는 접고, 시스템이 이미 가진 정보를 묻지 마세요. 목표는 "사용자가 맥락을 가진 상태"에서 "에이전트가 맥락을 가진 상태"로 가능한 한 적은 상호작용으로 가는 것입니다.

일반적인 사용 사례 (Common use cases)

외부 서비스를 맥락으로 연결하기 (Connecting an external service as context)

사용자는 서드파티 서비스를 연결하여 에이전트가 기존 리소스에 접근할 수 있게 합니다. 다단계 인라인 흐름이 인증과 리소스 선택을 대화에서 직접 처리합니다.

Generative AI assistant

JD I have a repo. Connect my existing third-party repository so I can keep working on it in this chat. Great - let me connect to your third-party account so I can access your code.

Connect to repositorySuccessfully connected as John-Doe-Dev

I need permission to read your repositories. This is a one-time authorization.

Connect third-party account

import React, { useState } from 'react';
import ActionCard from '@cloudscape-design/components/action-card';
import Box from '@cloudscape-design/components/box';
import Button from '@cloudscape-design/components/button';
import ButtonGroup from '@cloudscape-design/components/button-group';
import Container from '@cloudscape-design/components/container';
import ExpandableSection from '@cloudscape-design/components/expandable-section';
import Header from '@cloudscape-design/components/header';
import ItemCard from '@cloudscape-design/components/item-card';
import PromptInput from '@cloudscape-design/components/prompt-input';
import SpaceBetween from '@cloudscape-design/components/space-between';
import StatusIndicator from '@cloudscape-design/components/status-indicator';
import ChatBubble from '@cloudscape-design/chat-components/chat-bubble';
import { genAiAvatar, genAiLoadingAvatar, genAiName, userAvatar, userName } from '../genai-common/avatars';
import '../genai-common/styles.scss';

export default function ContextEnrichmentExternalService() {
  const [prompt, setPrompt] = useState('');
  const [expanded, setExpanded] = useState(true);
  const [connected, setConnected] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [repoCardReady, setRepoCardReady] = useState(false);
  const [repoExpanded, setRepoExpanded] = useState(true);
  const [repoSelected, setRepoSelected] = useState(false);
  const [generatingRepo, setGeneratingRepo] = useState(false);
  const [finalGenerating, setFinalGenerating] = useState(false);

  const handleConnect = () => {
    setConnected(true);
    window.setTimeout(() => {
      setExpanded(false);
      setGenerating(true);
    }, 800);
    window.setTimeout(() => {
      setGenerating(false);
      setRepoCardReady(true);
    }, 4000);
  };

  const handleSelectRepo = () => {
    setRepoSelected(true);
    window.setTimeout(() => {
      setRepoExpanded(false);
      setGeneratingRepo(true);
    }, 800);
    window.setTimeout(() => {
      setGeneratingRepo(false);
      setFinalGenerating(true);
    }, 4000);
  };

  return (
    <Container
      header={<Header variant="h3">Generative AI assistant</Header>}
      footer={
        <PromptInput
          value={prompt}
          onChange={({ detail }) => setPrompt(detail.value)}
          actionButtonIconName="send"
          actionButtonAriaLabel="Send message"
          disableSecondaryActionsPaddings
          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' },
                ]}
                variant="icon"
              />
            </Box>
          }
        />
      }
    >
      <div role="region" aria-label="Chat" style={{ minHeight: 280 }}>
        <SpaceBetween size="xs">
          <ChatBubble type="outgoing" ariaLabel={`${userName} at 2:15pm`} avatar={userAvatar}>
            I have a repo. Connect my existing third-party repository so I can keep working on it in this chat.
          </ChatBubble>

          <ChatBubble
            type="incoming"
            ariaLabel={`${genAiName} at 2:15pm`}
            avatar={generating || generatingRepo || finalGenerating ? genAiLoadingAvatar : genAiAvatar}
          >
            Great - let me connect to your third-party account so I can access your code.
          </ChatBubble>

          <div className="chat-bubble-indentation">
            <ItemCard variant="embedded">
              <ExpandableSection
                variant="inline"
                expanded={expanded}
                onChange={({ detail }) => setExpanded(detail.expanded)}
                headerText={
                  <SpaceBetween direction="horizontal" size="xs" alignItems="center">
                    <Box fontSize="heading-xs" fontWeight="bold">
                      Connect to repository
                    </Box>
                    
                      <StatusIndicator type="success">Successfully connected as John-Doe-Dev</StatusIndicator>
                    
                  </SpaceBetween>
                }
                headingTagOverride="h4"
              >
                {connected ? (
                  <Box color="text-body-secondary">Connected as John-Doe-Dev via third-party OAuth.</Box>
                ) : (
                  <SpaceBetween size="s">
                    <Box variant="p">
                      I need permission to read your repositories. This is a one-time authorization.
                    </Box>
                    <Button iconName="external" iconAlign="right" onClick={handleConnect} disabled={connected}>
                      Connect third-party account
                    </Button>
                  </SpaceBetween>
                )}
              </ExpandableSection>
            </ItemCard>
          </div>

          {generating && (
            <ChatBubble type="incoming" ariaLabel={`${genAiName} at 2:16pm`} avatar={genAiAvatar} hideAvatar>
              <Box color="text-status-inactive">Generating a response</Box>
            </ChatBubble>
          )}

          {repoCardReady && (
            <div className="chat-bubble-indentation">
              <ItemCard variant="embedded">
                <ExpandableSection
                  variant="inline"
                  expanded={repoExpanded}
                  onChange={({ detail }) => setRepoExpanded(detail.expanded)}
                  headerText={
                    <SpaceBetween direction="horizontal" size="xs" alignItems="center">
                      <Box fontSize="heading-xs" fontWeight="bold">
                        Select repository
                      </Box>
                      
                        <StatusIndicator type="success">Connected to repository</StatusIndicator>
                      
                    </SpaceBetween>
                  }
                  headingTagOverride="h4"
                >
                  <SpaceBetween size="xs">
                    <ActionCard
                      variant="embedded"
                      header={
                        <Box
                          fontSize="body-m"
                          fontWeight="bold"
                          color={repoSelected ? 'text-status-inactive' : undefined}
                        >
                          freelancerhub-landing
                        </Box>
                      }
                      description="Next.js landing page with waitlist · 2 days ago"
                      onClick={handleSelectRepo}
                      disabled={repoSelected}
                    />
                    <ActionCard
                      variant="embedded"
                      header={
                        <Box fontSize="body-m" fontWeight="bold" color="text-status-inactive">
                          freelancerhub-api
                        </Box>
                      }
                      description="Backend API (WIP) · 1 week ago"
                      disabled
                    />
                    <ActionCard
                      variant="embedded"
                      header={
                        <Box fontSize="body-m" fontWeight="bold" color="text-status-inactive">
                          personal-site
                        </Box>
                      }
                      description="Portfolio website · 3 weeks ago"
                      disabled
                    />
                  </SpaceBetween>
                </ExpandableSection>
              </ItemCard>
            </div>
          )}

          {generatingRepo && (
            <ChatBubble type="incoming" ariaLabel={`${genAiName} at 2:17pm`} avatar={genAiAvatar} hideAvatar>
              <Box color="text-status-inactive">Generating a response</Box>
            </ChatBubble>
          )}

          {finalGenerating && (
            <ChatBubble type="incoming" ariaLabel={`${genAiName} at 2:18pm`} avatar={genAiAvatar} hideAvatar>
              <Box color="text-status-inactive">Generating a response</Box>
            </ChatBubble>
          )}
        </SpaceBetween>
      </div>
    </Container>
  );
}

로컬 파일을 맥락으로 업로드하기 (Uploading local files as context)

사용자는 프롬프트와 함께 로컬 파일을 첨부하여 에이전트가 설정 파일, 문서, 이미지 같은 관련 콘텐츠에 즉시 접근할 수 있게 합니다.

Generative AI assistant

What can I help you with? JD I need help setting up a deployment pipeline for my project. I can help with that! Do you have any configuration files you can share for context?

  • buildspec.yaml 2.4 KB

I'm working on a deployment pipeline and need help configuring it. Use these files as context for this project.

import React, { useRef, useState } from 'react';
import Box from '@cloudscape-design/components/box';
import ButtonGroup from '@cloudscape-design/components/button-group';
import Container from '@cloudscape-design/components/container';
import FileTokenGroup from '@cloudscape-design/components/file-token-group';
import Header from '@cloudscape-design/components/header';
import PromptInput from '@cloudscape-design/components/prompt-input';
import SpaceBetween from '@cloudscape-design/components/space-between';
import ChatBubble from '@cloudscape-design/chat-components/chat-bubble';
import { genAiAvatar, genAiName, userAvatar, userName } from '../genai-common/avatars';

export default function ContextEnrichmentLocalFiles() {
  const [prompt, setPrompt] = useState(
    "I'm working on a deployment pipeline and need help configuring it. Use these files as context for this project."
  );
  const [files, setFiles] = useState<File[]>([
    new File(['x'.repeat(2457)], 'buildspec.yaml', { type: 'application/x-yaml' }),
  ]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleDismiss = (index: number) => {
    setFiles(files.filter((_, i) => i !== index));
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const newFiles = Array.from(e.target.files);
      setFiles(prev => [...prev, ...newFiles]);
    }
    e.target.value = '';
  };

  return (
    <Container
      header={<Header variant="h3">Generative AI assistant</Header>}
      footer={
        <>
          <input type="file" ref={fileInputRef} onChange={handleFileChange} multiple style={{ display: 'none' }} />
          <PromptInput
            value={prompt}
            onChange={({ detail }) => setPrompt(detail.value)}
            actionButtonIconName="send"
            actionButtonAriaLabel="Send message"
            placeholder="Ask a question"
            disableSecondaryActionsPaddings
            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' },
                  ]}
                  onItemClick={({ detail }) => {
                    if (detail.id === 'upload-files') {
                      fileInputRef.current?.click();
                    }
                  }}
                  variant="icon"
                />
              </Box>
            }
            secondaryContent={
              files.length > 0 ? (
                <FileTokenGroup
                  items={files.map(file => ({ file, loading: false }))}
                  onDismiss={({ detail }) => handleDismiss(detail.fileIndex)}
                  showFileSize
                  showFileThumbnail
                  i18nStrings={{
                    removeFileAriaLabel: (_index, fileName) => `Remove file ${fileName}`,
                    formatFileSize: sizeInBytes => `${(sizeInBytes / 1024).toFixed(1)} KB`,
                  }}
                  alignment="horizontal"
                />
              ) : undefined
            }
          />
        </>
      }
    >
      <div role="region" aria-label="Chat" style={{ minHeight: 280 }}>
        <SpaceBetween size="xs">
          <ChatBubble type="incoming" ariaLabel={`${genAiName} at 2:45pm`} avatar={genAiAvatar}>
            What can I help you with?
          </ChatBubble>

          <ChatBubble type="outgoing" ariaLabel={`${userName} at 3:00pm`} avatar={userAvatar}>
            I need help setting up a deployment pipeline for my project.
          </ChatBubble>

          <ChatBubble type="incoming" ariaLabel={`${genAiName} at 3:00pm`} avatar={genAiAvatar}>
            I can help with that! Do you have any configuration files you can share for context?
          </ChatBubble>
        </SpaceBetween>
      </div>
    </Container>
  );
}

프롬프트에서 맥락 제공하기 (Providing context in the prompt)

사용자는 요청과 함께 프로젝트 세부정보, 환경설정 또는 제약을 자연어로 진술합니다. 에이전트는 이해한 것을 확인하고 앞으로 그것을 적용합니다. 맥락이 제공된 후 추가 세부정보를 명확히 하거나 수집하려면 후속 질문을 사용하세요.

Generative AI assistant

What can I help you with? JD I need help setting up CI/CD. Our stack is React, TypeScript, and DynamoDB. We use a monorepo with packages under /apps and follow conventional commits. Generating a response

import React, { useState } from 'react';
import Box from '@cloudscape-design/components/box';
import ButtonGroup from '@cloudscape-design/components/button-group';
import Container from '@cloudscape-design/components/container';
import Header from '@cloudscape-design/components/header';
import PromptInput from '@cloudscape-design/components/prompt-input';
import SpaceBetween from '@cloudscape-design/components/space-between';
import ChatBubble from '@cloudscape-design/chat-components/chat-bubble';
import { genAiAvatar, genAiLoadingAvatar, genAiName, userAvatar, userName } from '../genai-common/avatars';

export default function ContextEnrichmentPrompt() {
  const [prompt, setPrompt] = useState('');

  return (
    <Container
      header={<Header variant="h3">Generative AI assistant</Header>}
      footer={
        <PromptInput
          value={prompt}
          onChange={({ detail }) => setPrompt(detail.value)}
          actionButtonIconName="send"
          actionButtonAriaLabel="Send message"
          placeholder="Ask a question"
          disableSecondaryActionsPaddings
          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' },
                ]}
                variant="icon"
              />
            </Box>
          }
        />
      }
    >
      <div role="region" aria-label="Chat" style={{ minHeight: 280 }}>
        <SpaceBetween size="xs">
          <ChatBubble type="incoming" ariaLabel={`${genAiName} at 4:00pm`} avatar={genAiAvatar}>
            What can I help you with?
          </ChatBubble>

          <ChatBubble type="outgoing" ariaLabel={`${userName} at 4:01pm`} avatar={userAvatar}>
            I need help setting up CI/CD. Our stack is React, TypeScript, and DynamoDB. We use a monorepo with packages
            under /apps and follow conventional commits.
          </ChatBubble>

          <ChatBubble type="incoming" ariaLabel={`${genAiName} at 4:01pm`} avatar={genAiLoadingAvatar}>
            <Box color="text-status-inactive">Generating a response</Box>
          </ChatBubble>
        </SpaceBetween>
      </div>
    </Container>
  );
}

일반 지침 (General guidelines)

권장 사항 (Do)

  • 단계가 완료된 후 접어서 대화가 다음에 올 것에 집중하게 하고 세로 공간을 절약하세요.
  • 맥락이 제공된 후 명확히 하거나 추가 세부정보를 수집하려면 후속 질문을 사용하세요.
  • 인증과 리소스 선택 같은 다단계 맥락 흐름에는 인라인 채팅 상호작용을 사용하세요.

금지 사항 (Don't)

  • 대화 맥락을 별도의 설정 페이지에서 구성하도록 사용자가 대화를 떠나게 하지 마세요.
  • 여러 맥락 추가 단계를 동시에 보여주지 마세요. 하나를 완료한 후 다음을 제시하세요.

작성 지침 (Writing guidelines)

일반 작성 지침 (General writing guidelines)

  • 문장형 대소문자(sentence case)를 사용하되, 문맥에 따라 고유 명사와 브랜드 이름은 올바르게 대문자로 표기하세요.

  • 헤더와 버튼을 제외하고는 끝 구두점을 사용하세요. 느낌표는 사용하지 마세요.

  • 현재 시제 동사와 능동태를 사용하세요.

  • 글에서 please, thank you, 줄임표( ... ), 앰퍼샌드( & ), e.g., i.e., etc. 를 사용하지 마세요.

  • 방향을 나타내는 언어는 피하세요.

    • 예: 위(above) 대신 이전(previous), 아래(below) 대신 다음(following) 을 사용하세요.
  • 기기에 독립적인 언어를 사용하세요.

    • 예: 클릭(click) 대신 선택(choose) 또는 select를 사용하세요.

컴포넌트별 지침 (Component-specific guidelines)

Expandable section 헤더 (Expandable section header)

  • 사용자가 무엇을 해야 하는지 설명하는 짧고 행동 지향적인 레이블을 사용하세요.

    • 예: Connect to repository 또는 Select repository.

성공 표시기 (Success indicator)

  • 어떤 맥락이 연결되거나 추가되었는지 확인하세요. 식별 세부정보를 포함하여 사용자가 에이전트가 이제 어떤 맥락을 가졌는지 정확히 알 수 있게 하세요. 작성 지침을 따르세요.

    • 예: Successfully connected as John-Doe-Dev 또는 Connected to repository.

인증 프롬프트 (Authorization prompt)

  • 어떤 권한이 왜 필요한지 한 문장으로 설명하세요.

    • 예: I need permission to read your repositories. This is a one-time authorization.

접근성 지침 (Accessibility guidelines)

일반 접근성 지침 (General accessibility guidelines)

  • 각 컴포넌트의 대체 텍스트(alternative text)와 ARIA 영역 지침을 따르세요.
  • 애플리케이션의 언어 컨텍스트에 맞춰 ARIA 레이블을 정의해야 합니다.
  • 역할(roles)과 랜드마크에 불필요한 마크업을 추가하지 마세요. 각 컴포넌트의 지침을 따르세요.
  • 논리적이고 예측 가능한 순서로 모든 사용 가능한 콘텐츠에 키보드 기능을 제공하세요. 정보 흐름은 이해하기 쉬워야 합니다.

더 알아보기 (Learn more)