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

每轮对话会发生一次互动。在互动期间,最终用户向 Dialogflow 发送输入,而 Dialogflow 发送响应。实现系统以处理互动时,您可从两个选项中选择:使用 API 或使用集成。

使用 API 时,您的系统需要处理以下操作:

  • 构建代理。
  • 为最终用户提供界面。
  • 为每轮会话调用 Dialogflow API,以向 API 发送最终用户输入。
  • 除非您的代理响应是完全静态的(不常见),否则您需要托管网络钩子服务,才能处理启用了网络钩子的 fulfillment

使用集成时,您的系统只需要处理以下操作:

  • 构建代理。
  • (可选)实现网络钩子服务。

下图显示了在会话的一轮对话中执行的步骤。

API 流图。

  1. 最终用户输入或说出某些内容(称为“最终用户输入”)。
  2. 您的界面或集成系统会收到输入,并在检测意图请求中将其转发到 Dialogflow API。
  3. Dialogflow API 会接收检测意图请求。它会将输入与意图或表单参数相匹配,根据需要设置参数,并更新会话状态。如果 Dialogflow API 需要调用启用了网络钩子的 fulfillment,它会向网络钩子服务发送网络钩子请求,否则将转到第 6 步。
  4. 您的网络钩子服务会收到网络钩子请求。您的服务会执行所有必要的操作,例如调用外部 API、查询或更新数据库等。
  5. 您的网络钩子服务构建一个响应,并将网络钩子响应发送回 Dialogflow。
  6. Dialogflow 会创建一个检测意图响应。如果调用了网络钩子,它将使用网络钩子响应中提供的响应。如果未调用网络钩子,则它将使用代理中定义的静态响应。Dialogflow 会向您的界面或集成系统发送检测意图响应。
  7. 您的界面或集成系统会收到检测意图响应,并将文本或音频响应转发给最终用户。
  8. 最终用户看到或听到响应。

指南用途

本指南介绍了如何针对未使用集成的代理在一轮对话中调用 API(上图中的第 2 步)。本指南介绍如何为最终用户实现界面。

准备工作

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

  1. 阅读 Dialogflow CX 基础知识
  2. 执行设置步骤
  3. 创建新代理或继续使用您在构建代理中创建的代理。

收集 ID

以下示例需要多个 ID 作为输入。如需查找项目 ID、区域 ID 和代理 ID,请执行以下操作:

  1. 打开 Dialogflow CX 控制台
  2. 选择您的 Google Cloud 项目以打开代理选择器。
  3. 点击列表中代理的选项 菜单。
  4. 点击复制名称 按钮。
  5. 此操作将复制代理的完整标识名称,其中包含您的项目 ID、区域 ID 和代理 ID,格式如下:
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

您还需要一个会话 ID。会话表示 Dialogflow 代理与最终用户之间的对话。您将在对话开始时创建唯一会话 ID,并在每轮对话中使用。为了试用 API,您可以使用任何最多 36 个字节的字符串 ID,如 test-session-123

调用检测意图

以下示例调用 Sessions.detectIntent 方法。

选择会话引用的协议和版本

协议 V3 V3beta1
REST 会话资源 会话资源
RPC 会话接口 会话接口
C++ SessionsClient 不可用
C# SessionsClient 不可用
Go SessionsClient 不可用
Java SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP 不可用 不可用
Python SessionsClient SessionsClient
Ruby 不可用 不可用

REST

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

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • AGENT_ID:您的代理 ID
  • REGION_ID:您的区域 ID
  • SESSION_ID:您的会话 ID
  • END_USER_INPUT:最终用户输入

HTTP 方法和网址:

POST https://REGION_ID-dialogflow.googleapis.com/v3/projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID/sessions/SESSION_ID:detectIntent

请求 JSON 正文:

{
  "queryInput": {
    "text": {
      "text": "END_USER_INPUT"
    },
    "languageCode": "en"
  },
  "queryParams": {
    "timeZone": "America/Los_Angeles"
  }
}

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

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

{
  "responseId": "38e8f23d-eed2-445e-a3e7-149b242dd669",
  "queryResult": {
    "text": "I want to buy a shirt",
    "languageCode": "en",
    "responseMessages": [
      {
        "text": {
          "text": [
            "Ok, let's start a new order."
          ]
        }
      },
      {
        "text": {
          "text": [
            "I'd like to collect a bit more information from you."
          ]
        }
      },
      {
        "text": {
          "text": [
            "What color would you like?"
          ]
        }
      },
      {}
    ],
    "currentPage": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/flows/00000000-0000-0000-0000-000000000000/pages/ce0b88c4-9292-455c-9c59-ec153dad94cc",
      "displayName": "New Order"
    },
    "intent": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
      "displayName": "order.new"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": { ... },
    "match": {
      "intent": {
        "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
        "displayName": "order.new"
      },
      "resolvedInput": "I want to buy a shirt",
      "matchType": "INTENT",
      "confidence": 1
    }
  }
}

Java

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


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

public class DetectIntent {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntent(
      String projectId,
      String locationId,
      String agentId,
      String sessionId,
      List<String> texts,
      String languageCode)
      throws IOException, ApiException {
    SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder();
    if (locationId.equals("global")) {
      sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443");
    } else {
      sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443");
    }
    SessionsSettings sessionsSettings = sessionsSettingsBuilder.build();

    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client.

    // Note: close() needs to be called on the SessionsClient object to clean up resources
    // such as threads. In the example below, try-with-resources is used,
    // which automatically calls close().
    try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
      // Set the session name using the projectID (my-project-id), locationID (global), agentID
      // (UUID), and sessionId (UUID).
      SessionName session =
          SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId);

      // TODO : Uncomment if you want to print session path
      // System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input.
      for (String text : texts) {
        // Set the text (hello) for the query.
        TextInput.Builder textInput = TextInput.newBuilder().setText(text);

        // Build the query with the TextInput and language code (en-US).
        QueryInput queryInput =
            QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build();

        // Build the DetectIntentRequest with the SessionName and QueryInput.
        DetectIntentRequest request =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .build();

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

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

        // TODO : Uncomment if you want to print queryResult
        // System.out.println("====================");
        // System.out.format("Query Text: '%s'\n", queryResult.getText());
        // System.out.format(
        //     "Detected Intent: %s (confidence: %f)\n",
        //     queryResult.getIntent().getDisplayName(),
        //         queryResult.getIntentDetectionConfidence());

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

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const location = 'global';
// const agentId = 'my-agent';
// const query = 'Hello';
// const languageCode = 'en'

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const location = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient();

async function detectIntentText() {
  const sessionId = Math.random().toString(36).substring(7);
  const sessionPath = client.projectLocationAgentSessionPath(
    projectId,
    location,
    agentId,
    sessionId
  );
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  for (const message of response.queryResult.responseMessages) {
    if (message.text) {
      console.log(`Agent Response: ${message.text.text}`);
    }
  }
  if (response.queryResult.match.intent) {
    console.log(
      `Matched Intent: ${response.queryResult.match.intent.displayName}`
    );
  }
  console.log(
    `Current Page: ${response.queryResult.currentPage.displayName}`
  );
}

detectIntentText();

Python

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

def run_sample():
    # TODO(developer): Replace these values when running the function
    project_id = "YOUR-PROJECT-ID"
    # For more information about regionalization see https://cloud.google.com/dialogflow/cx/docs/how/region
    location_id = "YOUR-LOCATION-ID"
    # For more info on agents see https://cloud.google.com/dialogflow/cx/docs/concept/agent
    agent_id = "YOUR-AGENT-ID"
    agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
    # For more information on sessions see https://cloud.google.com/dialogflow/cx/docs/concept/session
    session_id = uuid.uuid4()
    texts = ["Hello"]
    # For more supported languages see https://cloud.google.com/dialogflow/es/docs/reference/language
    language_code = "en-us"

    detect_intent_texts(agent, session_id, texts, language_code)

def detect_intent_texts(agent, 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."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    for text in texts:
        text_input = session.TextInput(text=text)
        query_input = session.QueryInput(text=text_input, language_code=language_code)
        request = session.DetectIntentRequest(
            session=session_path, query_input=query_input
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print(f"Query text: {response.query_result.text}")
        response_messages = [
            " ".join(msg.text.text) for msg in response.query_result.response_messages
        ]
        print(f"Response text: {' '.join(response_messages)}\n")

生产化

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