通过 API 进行互动

对于每个对话回合,均会发生互动。在互动期间,最终用户向 Dialogflow 发送输入,而 Dialogflow 发送响应。实现系统以处理互动时,有两种方式供您选择:使用 API 或使用集成。

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

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

使用集成时,系统只需要处理以下项:

  • 构建代理。
  • (可选)实现 Webhook 服务。

下图显示了会话中进行一轮对话需要完成的步骤。

API 流图。

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

指南用途

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

收集 ID

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

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

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

调用检测意图

以下示例会调用 Sessions 类型的 detectIntent 方法。

为会话参考选择协议和版本

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

REST 和命令行

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

  • PROJECT_ID:您的 GCP 项目 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": "89dd432b-1df4-48c4-be6b-d6550c3422b0",
  "queryResult": {
    "text": "I want to ask about data plans for international travel.",
    "languageCode": "en",
    "responseMessages": [
      {
        "text": {
          "text": [
            "Sure! I can help with that. "
          ]
        }
      },
      {
        "text": {
          "text": [
            "I need to ask a few questions before I can find the best option for you."
          ]
        }
      },
      {
        "text": {
          "text": [
            "What's your name?"
          ]
        }
      }
    ],
    "currentPage": {
      "name": "projects/PROJECT_ID/locations/REGION_ID/agents/027ac861-f275-45ed-a879-92aeb554df4e/pages/48d4352f-c995-4e46-8857-999709882959",
      "displayName": "Collect Customer Info"
    },
    "intent": {
      "name": "projects/PROJECT_ID/locations/REGION_ID/agents/027ac861-f275-45ed-a879-92aeb554df4e/intents/d48acf76-10f6-491f-be0c-cb58e1ce74d6",
      "displayName": "Data Plan Intent"
    },
    "intentDetectionConfidence": 1
  }
}

Java


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
    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.of(projectId, locationId, agentId, sessionId);
      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();

        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

/**
 * 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
  );
  console.info(sessionPath);

  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  console.log(`User Query: ${query}`);
  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

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