אינטראקציות עם ה-API

בכל תור בשיחה מתרחשת אינטראקציה. במהלך אינטראקציה, משתמש קצה שולח קלט ל-Dialogflow CX, ו-Dialogflow CX שולח תגובה. יש שתי אפשרויות להטמעת המערכת לטיפול באינטראקציות: שימוש ב-API או שימוש בשילוב.

כשמשתמשים ב-API, המערכת צריכה לטפל בפעולות הבאות:

  • ליצור סוכן.
  • לספק ממשק משתמש למשתמשי קצה.
  • שולחים קריאה ל-Dialogflow API בכל תור בשיחה כדי לשלוח את הקלט של משתמש הקצה ל-API.
  • אלא אם התשובות של הסוכן שלכם הן סטטיות לחלוטין (לא נפוץ), אתם צריכים לארח שירות webhook כדי לטפל בביצוע הזמנות שמופעלות באמצעות webhook.

כשמשתמשים בשילוב, המערכת צריכה לטפל רק בדברים הבאים:

  • ליצור סוכן.
  • אפשר להטמיע שירות webhook.

בתרשים הבא מוצגים השלבים שמתרחשים במהלך תור אחד של שיחה בביקור.

תרשים זרימה של API.

  1. משתמש הקצה מקליד או אומר משהו, שנקרא קלט ממשתמש הקצה.
  2. ממשק המשתמש או מערכת השילוב מקבלים את הקלט ומעבירים אותו אל Dialogflow API בבקשה לזיהוי כוונות.
  3. ‫Dialogflow API מקבל את הבקשה לזיהוי כוונות. הוא מתאים את הקלט לפרמטר של Intent או טופס, מגדיר פרמטרים לפי הצורך ומעדכן את מצב הסשן. אם צריך להתקשר ל-fulfillment עם webhook, הוא שולח בקשת webhook לשירות ה-webhook שלכם. אחרת, עוברים לשלב 6.
  4. שירות ה-webhook מקבל את בקשת ה-webhook. השירות מבצע את כל הפעולות הנדרשות, כמו קריאה לממשקי API חיצוניים, שליחת שאילתות למסד נתונים או עדכון שלו וכו'.
  5. שירות ה-webhook יוצר תגובה ושולח אותה בחזרה ל-Dialogflow CX.
  6. ‫Dialogflow CX יוצר תגובה לזיהוי כוונה. אם בוצע קריאה ל-webhook, המערכת משתמשת בתשובה שסופקה בתגובת ה-webhook. אם לא הופעל webhook, נעשה שימוש בתגובה הסטטית שהוגדרה בסוכן. ‫Dialogflow CX שולח תגובה של זיהוי כוונות לממשק המשתמש או למערכת השילוב.
  7. ממשק המשתמש או מערכת השילוב מקבלים את התגובה של זיהוי הכוונה ומעבירים את התגובה בטקסט או באודיו למשתמש הקצה.
  8. משתמש הקצה רואה או שומע את התשובה.

מטרת המדריך

במדריך הזה מוסבר איך להפעיל את ה-API לסיבוב שיחה אחד עם סוכן שלא משתמש בשילוב (שלב 2 בתרשים שלמעלה). במדריך הזה לא מוסבר איך להטמיע ממשק משתמש למשתמשי הקצה.

לפני שמתחילים

לפני שתקראו את המדריך הזה:

  1. מידע בסיסי על תהליכי עבודה
  2. לבצע את השלבים להגדרה.
  3. יוצרים סוכן חדש או ממשיכים להשתמש בסוכן שיצרתם במאמר יצירת סוכן באמצעות Flows או במאמר יצירת סוכן באמצעות Playbooks.

איסוף מזהים

בדוגמאות שלמטה צריך להזין כמה מזהים. כדי למצוא את מזהה הפרויקט, מזהה האזור ומזהה הסוכן:

מסוף Dialogflow CX

  1. פותחים את מסוף Dialogflow CX.
  2. בוחרים את Google Cloud הפרויקט כדי לפתוח את בורר הסוכנים.
  3. לוחצים על האפשרות בתפריט של סוכן ברשימה.
  4. לוחצים על הלחצן להעתקת השם .
  5. הפעולה הזו מעתיקה את השם המזהה המלא של הסוכן, שכולל את מזהה הפרויקט, מזהה האזור ומזהה הסוכן, בצורה הבאה:
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

מסוף Vertex AI Agent Builder

  1. עוברים אל מסוף Vertex AI Agent Builder:

    מסוף Vertex AI Agent Builder

  2. מזהה הפרויקט מוצג בחלק העליון של המסוף.

  3. בעמודה מיקום מוצגים מזהי אזורים.

  4. בוחרים אפליקציה.

  5. פלח נתיב כתובת ה-URL בדפדפן אחרי agents/ מכיל את מזהה האפליקציה של הסוכן.

צריך גם מזהה סשן. סשן מייצג שיחה בין סוכן של Dialogflow CX לבין משתמש קצה. אתם יוצרים מזהה סשן ייחודי בתחילת השיחה ומשתמשים בו בכל תור בשיחה. לצורך ניסיון ה-API, אפשר להשתמש בכל מזהה מחרוזת באורך של עד 36 בייט, כמו test-session-123.

זיהוי כוונת השיחה

בדוגמאות הבאות מבוצעת קריאה למתודה Sessions.detectIntent.

בוחרים פרוטוקול וגרסה להפניה של הסשן:

פרוטוקול V3 V3beta1
REST Session resource Session resource
RPC ממשק הסשן ממשק הסשן
C++‎ SessionsClient לא זמין
C#‎ SessionsClient לא זמין
המשך SessionsClient לא זמין
Java SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP לא זמין לא זמין
Python SessionsClient SessionsClient
Ruby לא זמין לא זמין

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב-Google Cloud
  • AGENT_ID: מזהה הסוכן
  • REGION_ID: מזהה האזור
  • SESSION_ID: מזהה הסשן
  • END_USER_INPUT: הקלט של משתמש הקצה

ה-method של ה-HTTP וכתובת ה-URL:

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 CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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 CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

העברה לסביבת ייצור

לפני שמפעילים את הנציג בסביבת הייצור, חשוב להטמיע את השיטות המומלצות להעברה לייצור.