快速入门:通过 API 进行互动

如果您未使用集成,则必须编写代码以实现与最终用户互动。对于每轮会话,您的代码会调用 Dialogflow API 查询您的代理。本指南介绍了如何通过在命令行上使用 REST API 和通过使用客户端库与代理进行互动。

准备工作

如果您不打算使用 API,则可以跳过此快速入门。

在阅读本指南之前,请先完成以下事项:

  1. 了解 Dialogflow 基础知识
  2. 执行设置步骤
  3. 执行构建代理快速入门指南中的步骤。以下步骤将继续处理您在该指南中启动的代理。 如果您不再拥有该代理,则可以下载 build-agent-quickstart.zip导入文件

会话

会话表示 Dialogflow 代理与最终用户之间的对话。您可以在对话开始时创建会话,并在每轮对话中使用该会话。对话结束后,您将停止使用该会话。

在同一时间与不同最终用户进行对话时,不应使用同一个会话。Dialogflow 会为每个活跃会话维护当前活跃的上下文。会话数据将由 Dialogflow 存储 20 分钟。

每个会话均由系统生成的会话 ID 唯一确定。您可以在检测意图请求中提供新的会话 ID 来创建新会话。会话 ID 是一个字符串,最长 36 个字节。系统负责生成不重复的会话 ID。它们可以是随机数字、经过哈希处理的最终用户标识符或任何其他便于生成的值。

检测意图

使用 API 进行互动时,您的服务会直接与最终用户互动。对于每轮对话,您的服务均会调用 Sessions 类型的 detectIntentstreamingDetectIntent 方法将最终用户表述发送给 Dialogflow。Dialogflow 会使用与匹配意图、操作和参数相关的信息以及针对该意图定义的响应来做出响应。服务会根据需要执行操作(例如数据库查询或外部 API 调用),并向最终用户发送消息。此过程会一直持续到对话结束。

以下示例展示了如何检测意图。每个示例均接受以下输入内容的一部分:

  • 项目 ID:使用您在设置步骤中创建的项目的 ID。
  • 会话 ID:测试代理时,您可以使用任意会话 ID。例如,“123456789”是示例经常使用的一个 ID。
  • 文本:这是指一种最终用户表述或多种最终用户表述。如果提供了多种表述,则示例代码会针对每种表述调用检测意图。尝试输入“I know french”。
  • 语言代码:最终用户表述的语言代码。对于此示例代理,请使用“en-US”。

REST

如需检测 intent,请调用 Sessions 资源的 detectIntent 方法。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • SESSION_ID:会话 ID。

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

请求 JSON 正文:

{
  "query_input": {
    "text": {
      "text": "I know french",
      "language_code": "en-US"
    }
  }
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "responseId": "856510ca-f617-4e25-b0bb-a26c0a59e030-19db3199",
  "queryResult": {
    "queryText": "I know french",
    "parameters": {
      "language": "French",
      "language-programming": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Wow! I didn't know you knew French. How long have you known French?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Wow! I didn't know you knew French. How long have you known French?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/123456789/contexts/set-language-followup",
        "lifespanCount": 2,
        "parameters": {
          "language": "French",
          "language.original": "french",
          "language-programming": "",
          "language-programming.original": ""
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/fe45022f-e58a-484f-96e8-1cbd6628f648",
      "displayName": "set-language"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  }
}

关于响应,请注意以下事项:

  • queryResult.intent 字段包含匹配的意图。
  • queryResult.fulfillmentMessages 字段的值包含意图响应。这是您的系统应转发给最终用户的响应。
  • queryResult.parameters 字段的值包含从最终用户表达式中提取的参数。
  • queryResult.outputContext 字段包含有效的上下文。

Go

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
	ctx := context.Background()

	sessionClient, err := dialogflow.NewSessionsClient(ctx)
	if err != nil {
		return "", err
	}
	defer sessionClient.Close()

	if projectID == "" || sessionID == "" {
		return "", errors.New(fmt.Sprintf("Received empty project (%s) or session (%s)", projectID, sessionID))
	}

	sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
	textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
	queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
	queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
	request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

	response, err := sessionClient.DetectIntent(ctx, &request)
	if err != nil {
		return "", err
	}

	queryResult := response.GetQueryResult()
	fulfillmentText := queryResult.GetFulfillmentText()
	return fulfillmentText, nil
}

Java

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public class DetectIntentTexts {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntentTexts(
      String projectId, List<String> texts, String sessionId, String languageCode)
      throws IOException, ApiException {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    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 (hello) 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();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

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

        System.out.println("====================");
        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");

        queryResults.put(text, queryResult);
      }
    }
    return queryResults;
  }
}

Node.js

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * TODO(developer): UPDATE these variables before running the sample.
 */
// projectId: ID of the GCP project where Dialogflow agent is deployed
// const projectId = 'PROJECT_ID';
// sessionId: String representing a random number or hashed user identifier
// const sessionId = '123456';
// queries: A set of sequential queries to be send to Dialogflow agent for Intent Detection
// const queries = [
//   'Reserve a meeting room in Toronto office, there will be 5 of us',
//   'Next monday at 3pm for 1 hour, please', // Tell the bot when the meeting is taking place
//   'B'  // Rooms are defined on the Dialogflow agent, default options are A, B, or C
// ]
// languageCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates a session client
const sessionClient = new dialogflow.SessionsClient();

async function detectIntent(
  projectId,
  sessionId,
  query,
  contexts,
  languageCode
) {
  // The path to identify the agent that owns the created intent.
  const sessionPath = sessionClient.projectAgentSessionPath(
    projectId,
    sessionId
  );

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (contexts && contexts.length > 0) {
    request.queryParams = {
      contexts: contexts,
    };
  }

  const responses = await sessionClient.detectIntent(request);
  return responses[0];
}

async function executeQueries(projectId, sessionId, queries, languageCode) {
  // Keeping the context across queries let's us simulate an ongoing conversation with the bot
  let context;
  let intentResponse;
  for (const query of queries) {
    try {
      console.log(`Sending Query: ${query}`);
      intentResponse = await detectIntent(
        projectId,
        sessionId,
        query,
        context,
        languageCode
      );
      console.log('Detected intent');
      console.log(
        `Fulfillment Text: ${intentResponse.queryResult.fulfillmentText}`
      );
      // Use the context from this response for next queries
      context = intentResponse.queryResult.outputContexts;
    } catch (error) {
      console.log(error);
    }
  }
}
executeQueries(projectId, sessionId, queries, languageCode);

Python

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

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

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

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"session": session, "query_input": query_input}
        )

        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))

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Dialogflow 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Dialogflow 参考文档

Ruby 版:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Dialogflow 参考文档

生产化

在生产环境中运行代理之前,请务必实施生产化最佳做法