通过 API 进行互动

将 API 用于 CX 与将 API 用于 ES 的方法类似。不同之处在于为了适应新类型、方法和字段而修改了某些资源路径和方法。

您的系统需要处理以下任务:

  • Dialogflow CX 尚不支持任何集成,因此您的系统必须提供一个界面来直接与最终用户互动。
  • 您还必须为每轮对话调用 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. 最终用户看到或听到响应。

向 CX API 发送最终用户输入以进行处理与 ES API 非常相似。以下示例调用 Sessions 资源的 detectIntent 方法。

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

协议 V3beta1
REST 会话资源
RPC 会话界面
Java SessionsClient
Node.js SessionsClient
Python SessionsClient

REST 和命令行

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

  • project-id:您的 GCP 项目 ID
  • agent-id:您的代理 ID
  • session-id:您的会话 ID
  • end-user-input:最终用户输入

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v3beta1/projects/project-id/locations/us/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/us/agents/027ac861-f275-45ed-a879-92aeb554df4e/pages/48d4352f-c995-4e46-8857-999709882959",
      "displayName": "Collect Customer Info"
    },
    "intent": {
      "name": "projects/project-id/locations/us/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.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 {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // 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');
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"
    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_client = SessionsClient()
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")

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