지식 커넥터

지식 커넥터는 정의된 인텐트를 보완하며, 자동 응답을 찾도록 기술 문서(예: FAQ 또는 문서)를 파싱합니다. 지식 커넥터를 구성하려면 기술 문서 집합 형태의 기술 자료를 하나 이상 정의해야 합니다.

에이전트에 기술 자료를 사용 설정하면 모든 인텐트 감지 요청은 기술 자료를 사용하여 자동 응답을 찾을 수 있습니다. 또는 인텐트 인식 요청별로 기술 자료를 한 개 이상 지정할 수도 있습니다.

지식 커넥터를 사용하는 에이전트는 일반적으로 정의된 인텐트도 사용합니다. 지식 커넥터의 응답 정확도와 제어는 인텐트보다 낮습니다. 인텐트를 정의하여 복잡한 사용자 요청을 처리하고, 지식 커넥터는 단순한 요청을 처리하도록 해야 합니다.

지원되는 언어 목록은 언어 참조 페이지의 지식 커넥터 열을 참조하세요.

제한사항

지식 커넥터 기능은 global 리전에서만 사용할 수 있습니다.

베타 기능 사용 설정

베타 기능이 사용 설정되어 있는지 확인합니다.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 에이전트를 선택합니다.
  3. 에이전트 이름 옆에 있는 설정 버튼을 클릭합니다.
  4. 일반 탭에서 아래로 스크롤하여 베타 기능이 사용 설정되어 있는지 확인합니다.
  5. 변경을 마쳤으면 저장을 클릭합니다.

기술 자료 및 문서 만들기

기술 자료 사용 방법의 안내에 따라 기술 자료 및 문서를 만듭니다.

지식 커넥터 설정

에이전트에 대한 기술 자료를 사용 설정 또는 사용 중지할 수 있습니다. 인텐트 일치 요청에 기술 자료를 지정하지 않은 경우 사용 설정한 기술 자료가 반영됩니다. 기술 자료를 사용 설정 또는 사용 중지하려면 다음 단계를 따르세요.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 에이전트를 선택합니다.
  3. 왼쪽 사이드바 메뉴에서 기술을 클릭합니다.
  4. 목록에서 기술 자료를 하나 이상 선택합니다.
  5. 사용 설정 또는 사용 중지를 클릭합니다.

최종 사용자 표현식이 인텐트와 일치하는 경우 기술 결과의 선호도를 지정할 수 있습니다.

  1. 기술 결과 환경설정 조정 섹션까지 아래로 스크롤합니다.
  2. 슬라이더를 약하게(인텐트에 대한 우선권)에서 강하게(기술에 대한 우선권)로 조정합니다. 자세한 내용은 아래의 인텐트 응답 인식을 참조하세요.

응답 구성

기본적으로 기술 자료는 가장 일치하는 기술 답변으로 채워진 단일 기본 텍스트 응답으로 구성됩니다. 이 응답을 변경하고 리치 응답 메시지를 추가할 수 있습니다. 기술 응답에는 기술 자료별로 최대 3개의 답변이 포함될 수 있고 구성된 응답에서 이러한 답변을 참조할 수 있습니다. 응답을 추가하려면 다음 안내를 따르세요.

  1. 기술 페이지에서 기술 자료 이름을 클릭합니다.
  2. 아래로 스크롤하여 응답 섹션으로 이동하고 원하는 대로 응답을 추가합니다.
    1. 첫 번째 응답을 정의할 때 질문과 답변을 지정하는 $Knowledge.Question[1]$Knowledge.Answer[1]를 사용합니다.
    2. $Knowledge.Question$Knowledge.Answer의 색인은 1부터 시작하므로 응답을 추가할 때 이 색인 숫자를 늘립니다.
  3. 편집이 완료되었으면 저장을 클릭합니다.

응답을 정의할 때에는 다음과 같은 사항을 고려해야 합니다.

  • 정의된 응답의 수가 지식 커넥터 응답 일치 수인 N보다 크면 N개의 응답만 반환됩니다.
  • 명시적으로 정의된 인텐트 일치 항목보다 정확도가 낮을 수 있으므로 가능하다면 사용자에게 응답을 3개 제공하는 것이 좋습니다.

예를 들면 다음과 같습니다.

지식 커넥터 통합 스크린샷

기술 자료를 사용하여 인텐트 감지

인텐트 감지 요청을 수행할 때 가능한 응답에 기술 자료를 하나 이상 지정할 수 있습니다. 요청에서 기술 자료를 명시적으로 제공하면 사용 설정 또는 사용 중지된 기술 자료에 대한 설정이 재정의됩니다.

아래 샘플에서는 Dialogflow 콘솔, REST API(명령줄 포함), 클라이언트 라이브러리를 사용하여 인텐트를 감지하는 방법을 보여줍니다. API를 사용하려면 Sessions 유형의 detectIntent 메서드를 호출합니다.

웹 UI

Dialogflow 시뮬레이터를 통해 에이전트와 상호작용하고 지식 커넥터 응답을 받을 수 있습니다.

  1. 기술 자료를 사용 설정하려면 위의 단계를 따릅니다.
  2. 위의 단계에 따라 응답을 정의합니다.
  3. 시뮬레이터에 'How do I sign up?'을 입력합니다.

REST

Sessions 유형의 detectIntent 메서드를 호출하고 queryParams 필드에 기술 자료를 지정합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • KNOWLEDGE_BASE_ID: 기술 자료 ID

HTTP 메서드 및 URL:

POST https://dialogflow.googleapis.com/v2beta1/projects/PROJECT_ID/agent/sessions/123456789:detectIntent

JSON 요청 본문:

{
 "queryInput": {
   "text": {
     "text": "How do I sign up?",
     "languageCode": "en-US"
   }
 },
 "queryParams": {
   "knowledgeBaseNames": ["projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID"]
 }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  ...
  "queryResult": {
    "queryText": "How do I sign up?",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Sign up for Cloud Storage by turning on the Cloud Storage service in the Google Cloud Platform Console.",
    "intent": {
      "name": "projects/my-gcp-project/agent/intents/487c7242-a769-408a-a339-47b95e10dac4",
      "displayName": "Knowledge.KnowledgeBase.MzkzNTAyMDE3NDQxNDk3MDg4MA"
    },
    "intentDetectionConfidence": 0.99371547,
    "languageCode": "en-us",
    "knowledgeAnswers": {
      "answers": [
        {
          "answer": "Sign up for Cloud Storage by turning on the Cloud Storage service in the Google Cloud Platform Console.",
          "matchConfidenceLevel": "HIGH",
          "matchConfidence": 0.99371547
        },
        {
          "answer": "Certain types of content are not allowed on this service; please refer to the Terms of Services and Platform Policies for details. If you believe a piece of content is in violation of our policies, report it here (select See more products, then Google Cloud Storage and Cloud Bigtable).",
          "matchConfidenceLevel": "LOW",
          "matchConfidence": 0.0012244871
        },
        {
          "answer": "From the Cloud Storage documentation click \"Send feedback\" near the top right of the page. This will open a feedback form. Your comments will be reviewed by the Cloud Storage team.",
          "matchConfidenceLevel": "LOW",
          "matchConfidence": 0.0011537358
        }
      ]
    }
  }
}

Java

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest;
import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
import com.google.cloud.dialogflow.v2beta1.QueryInput;
import com.google.cloud.dialogflow.v2beta1.QueryParameters;
import com.google.cloud.dialogflow.v2beta1.QueryResult;
import com.google.cloud.dialogflow.v2beta1.SessionName;
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
import com.google.cloud.dialogflow.v2beta1.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntentKnowledge {

  // DialogFlow API Detect Intent sample with querying knowledge connector.
  public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
      String projectId,
      String knowledgeBaseName,
      String sessionId,
      String languageCode,
      List<String> texts)
      throws IOException, ApiException {
    // Instantiates a client
    Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of(projectId, sessionId);
      System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input
      for (String text : texts) {
        // Set the text and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        QueryParameters queryParameters =
            QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build();

        DetectIntentRequest detectIntentRequest =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build();
        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest);

        // Display the query result
        QueryResult queryResult = response.getQueryResult();

        System.out.format("Knowledge results:\n");
        System.out.format("====================\n");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format(
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format(
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");
        KnowledgeAnswers knowledgeAnswers = queryResult.getKnowledgeAnswers();
        for (Answer answer : knowledgeAnswers.getAnswersList()) {
          System.out.format(" - Answer: '%s'\n", answer.getAnswer());
          System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence());
        }

        KnowledgeAnswers answers = queryResult.getKnowledgeAnswers();
        allKnowledgeAnswers.put(text, answers);
      }
    }
    return allKnowledgeAnswers;
  }
}

Node.js

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Dialogflow client library
const dialogflow = require('@google-cloud/dialogflow').v2beta1;
// Instantiate a DialogFlow client.
const sessionClient = new dialogflow.SessionsClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'ID of GCP project associated with your Dialogflow agent';
// const sessionId = `user specific ID of session, e.g. 12345`;
// const languageCode = 'BCP-47 language code, e.g. en-US';
// const knowledgeBaseId = `the ID of your KnowledgeBase`;
// const query = `phrase(s) to pass to detect, e.g. I'd like to reserve a room for six people`;

// Define session path
const sessionPath = sessionClient.projectAgentSessionPath(
  projectId,
  sessionId
);
const knowledgeBasePath =
  'projects/' + projectId + '/knowledgeBases/' + knowledgeBaseId + '';

// The audio query request
const request = {
  session: sessionPath,
  queryInput: {
    text: {
      text: query,
      languageCode: languageCode,
    },
  },
  queryParams: {
    knowledgeBaseNames: [knowledgeBasePath],
  },
};

const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
console.log(`Query text: ${result.queryText}`);
console.log(`Detected Intent: ${result.intent.displayName}`);
console.log(`Confidence: ${result.intentDetectionConfidence}`);
console.log(`Query Result: ${result.fulfillmentText}`);
if (result.knowledgeAnswers && result.knowledgeAnswers.answers) {
  const answers = result.knowledgeAnswers.answers;
  console.log(`There are ${answers.length} answer(s);`);
  answers.forEach(a => {
    console.log(`   answer: ${a.answer}`);
    console.log(`   confidence: ${a.matchConfidence}`);
    console.log(`   match confidence level: ${a.matchConfidenceLevel}`);
  });
}

Python

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def detect_intent_knowledge(
    project_id, session_id, language_code, knowledge_base_id, texts
):
    """Returns the result of detect intent with querying Knowledge Connector.

    Args:
    project_id: The GCP project linked with the agent you are going to query.
    session_id: Id of the session, using the same `session_id` between requests
              allows continuation of the conversation.
    language_code: Language of the queries.
    knowledge_base_id: The Knowledge base's id to query against.
    texts: A list of text queries to send.
    """
    from google.cloud import dialogflow_v2beta1 as dialogflow

    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session_path))

    for text in texts:
        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path(
            project_id, knowledge_base_id
        )

        query_params = dialogflow.QueryParameters(
            knowledge_base_names=[knowledge_base_path]
        )

        request = dialogflow.DetectIntentRequest(
            session=session_path, query_input=query_input, query_params=query_params
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
        print("Knowledge results:")
        knowledge_answers = response.query_result.knowledge_answers
        for answers in knowledge_answers.answers:
            print(" - Answer: {}".format(answers.answer))
            print(" - Confidence: {}".format(answers.match_confidence))

인텐트 응답 인식

Sessions 유형 detectIntent 메서드의 응답은 DetectIntentResponse입니다. 응답 필드가 입력되는 방식은 여러 요인의 영향을 받습니다.

정의된 인텐트와 기술 자료에 모두 잠재적 일치 항목이 있는 경우 각 항목의 일치 신뢰도와 기술 결과 환경설정(지식 커넥터 설정 참조)을 사용하여 어떤 일치 항목을 선택할지 판단합니다. 선택된 일치 항목은 DetectIntentResponse.queryResult 필드에 입력되고 다른 잠재적 일치 항목은 DetectIntentResponse.alternativeQueryResults 필드에 입력됩니다. 두 필드 모두에 QueryResult 메시지가 포함됩니다.

기술 자료가 잠재적 일치 항목을 제공하는 경우:

  • 일치 신뢰도를 기준으로 내림차순으로 정렬된 잠재적 지식 답변 목록이 QueryResult.knowledgeAnswers에 입력됩니다.
  • 기술 자료에 리치 응답이 정의된 경우 QueryResult.fulfillmentMessages에 리치 응답 메시지가 입력됩니다.

인텐트 인식 요청을 수행하는 경우 지식 쿼리가 실패할 수 있습니다. 이 경우 인텐트 인식 요청이 전체적으로 실패하지 않도록 정의된 인텐트가 선택됩니다. DetectIntentResponse.alternativeQueryResults[i].diagnosticInfo 필드에서 지식 쿼리 오류 정보를 찾을 수 있습니다.

기술 자료 관리

기술 자료 관리에 대한 자세한 내용은 기술 자료 관리를 참조하세요.