Interaksi dengan API

Untuk setiap giliran percakapan, terjadi interaksi. Selama interaksi, pengguna akhir mengirimkan input ke Dialogflow CX, dan Dialogflow CX mengirimkan respons. Anda memiliki dua opsi saat menerapkan sistem untuk menangani interaksi: menggunakan API atau menggunakan integrasi.

Saat menggunakan API, sistem Anda harus menangani hal berikut:

  • Membangun agen.
  • Menyediakan antarmuka pengguna untuk pengguna akhir.
  • Memanggil Dialogflow API untuk setiap giliran percakapan guna mengirimkan input pengguna akhir ke API.
  • Kecuali jika respons agen Anda murni statis (tidak umum), Anda harus menghosting layanan webhook untuk menangani fulfillment yang diaktifkan webhook.

Saat menggunakan integrasi, sistem Anda hanya perlu menangani hal berikut:

  • Membangun agen.
  • Secara opsional, menerapkan layanan webhook.

Diagram berikut menunjukkan langkah-langkah yang terjadi untuk satu giliran percakapan sesi.

Diagram alur API.

  1. Pengguna akhir mengetik atau mengatakan sesuatu, yang dikenal sebagai input pengguna akhir.
  2. Sistem integrasi atau antarmuka pengguna Anda menerima input dan meneruskannya ke Dialogflow API dalam permintaan deteksi intent.
  3. Dialogflow API menerima permintaan deteksi intent. API ini mencocokkan input dengan parameter intent atau formulir, menetapkan parameter sesuai kebutuhan, dan memperbarui status sesi. Jika perlu memanggil fulfillment yang diaktifkan webhook, API akan mengirimkan permintaan webhook ke layanan webhook Anda. Jika tidak, lanjutkan ke langkah 6.
  4. Layanan webhook Anda menerima permintaan webhook. Layanan Anda melakukan tindakan yang diperlukan, seperti memanggil API eksternal, membuat kueri atau memperbarui database, dll.
  5. Layanan webhook Anda membuat respons dan mengirimkan respons webhook kembali ke Dialogflow CX.
  6. Dialogflow CX membuat respons deteksi intent. Jika webhook dipanggil, Dialogflow CX akan menggunakan respons yang diberikan dalam respons webhook. Jika tidak ada webhook yang dipanggil, Dialogflow CX akan menggunakan respons statis yang ditentukan di agen. Dialogflow CX mengirimkan respons deteksi intent ke sistem integrasi atau antarmuka pengguna Anda.
  7. Sistem integrasi atau antarmuka pengguna Anda menerima respons deteksi intent dan meneruskan respons teks atau audio ke pengguna akhir.
  8. Pengguna akhir melihat atau mendengar respons.

Tujuan

Pelajari cara memanggil API untuk satu giliran percakapan untuk agen tanpa menggunakan integrasi. Panduan ini tidak menunjukkan cara menerapkan antarmuka pengguna untuk pengguna akhir.

Sebelum memulai

Sebelum membaca panduan ini, lakukan hal berikut:

Mengumpulkan ID

Contoh berikut memerlukan beberapa ID sebagai input. Temukan project ID, ID wilayah, dan agent ID Anda menggunakan salah satu metode berikut:

Konsol Dialogflow CX

  1. Buka konsol Dialogflow CX.
  2. Pilih project Anda.
  3. Klik menu opsi untuk agen dalam daftar.
  4. Klik tombol salin nama .
  5. Tindakan ini akan menyalin nama identifikasi lengkap agen Anda, yang mencakup project ID, ID wilayah, dan agent ID dalam bentuk:
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

Builder Aplikasi AI Generatif

  1. Buka Builder Aplikasi AI Generatif:

    Builder Aplikasi AI Generatif

  2. Project ID Anda ditampilkan di bagian atas konsol.

  3. Kolom Location menampilkan region ID.

  4. Pilih aplikasi.

  5. Segmen jalur URL browser setelah agents/ berisi ID aplikasi agen.

Anda juga memerlukan ID sesi. Sesi mewakili percakapan antara agen Dialogflow CX dan pengguna akhir. Buat ID sesi unik di awal percakapan dan gunakan untuk setiap giliran percakapan. Untuk menguji API, Anda dapat menggunakan ID string apa pun yang berukuran maksimal 36 byte, seperti test-session-123.

Memanggil deteksi intent

Contoh berikut memanggil metode Sessions.detectIntent.

Pilih protokol dan versi untuk referensi Sesi:

Protokol V3 V3beta1
REST Resource sesi Resource sesi
RPC Antarmuka sesi Antarmuka sesi
C++ SessionsClient Tidak tersedia
C# SessionsClient Tidak tersedia
Go SessionsClient Tidak tersedia
Java SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP Tidak tersedia Tidak tersedia
Python SessionsClient SessionsClient
Ruby Tidak tersedia Tidak tersedia

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID Google Cloud Anda
  • AGENT_ID: agent ID Anda
  • REGION_ID: ID wilayah Anda
  • SESSION_ID: session ID Anda
  • END_USER_INPUT: input pengguna akhir

Metode HTTP dan URL:

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

Meminta isi JSON:

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

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

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

Untuk melakukan autentikasi ke Dialogflow CX, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk melakukan autentikasi ke Dialogflow CX, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk melakukan autentikasi ke Dialogflow CX, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Produksi

Sebelum menjalankan agen dalam produksi, ikuti Praktik terbaik produksi.