מדריך למתחילים: אינטראקציות עם ה-API

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

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

אם אתם לא מתכננים להשתמש ב-API, אתם יכולים לדלג על המדריך הזה.

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

  1. חשוב להבין את היסודות של Dialogflow.
  2. לבצע את השלבים להגדרה.
  3. פועלים לפי השלבים במדריך למתחילים בנושא יצירת סוכן. השלבים שבהמשך מתייחסים לסוכן שהתחלתם לעבוד איתו במדריך הזה. אם אין לכם יותר את הסוכן הזה, אתם יכולים להוריד את build-agent-quickstart.zip ואז לייבא את הקובץ.

התפקידים הנדרשים

כדי לקבל את ההרשאות שנדרשות לביצוע המשימות במדריך הזה, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד Dialogflow API Client (roles/dialogflow.client) בפרויקט. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

סשנים

סשן מייצג שיחה בין סוכן Dialogflow לבין משתמש קצה. יוצרים סשן בתחילת השיחה ומשתמשים בו בכל תור של השיחה. אחרי שהשיחה מסתיימת, מפסיקים להשתמש בסשן.

אסור להשתמש באותו סשן לשיחות בו-זמניות עם משתמשי קצה שונים. מערכת Dialogflow שומרת את ההקשרים הפעילים כרגע לכל סשן פעיל. נתוני הסשן מאוחסנים על ידי Dialogflow למשך 20 דקות.

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

זיהוי כוונות

כשמשתמשים בממשק ה-API לאינטראקציות, השירות יוצר אינטראקציה ישירה עם משתמש הקצה. בכל תור בשיחה, השירות שלכם שולח ביטויים של משתמשי הקצה ל-Dialogflow על ידי קריאה לשיטה detectIntent או streamingDetectIntent של הסוג Sessions. ‫Dialogflow מגיב עם מידע על ה-Intent התואם, הפעולה, הפרמטרים והתגובה שהוגדרו עבור ה-Intent. השירות שלכם מבצע פעולות לפי הצורך (לדוגמה, שאילתות במסד נתונים או קריאות ל-API חיצוני) ושולח הודעה למשתמש הקצה. התהליך הזה נמשך עד שהשיחה מסתיימת.

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

  • מזהה הפרויקט: משתמשים במזהה הפרויקט של הפרויקט שיצרתם בשלבי ההגדרה.
  • מזהה סשן: למטרת בדיקת סוכן, אפשר להשתמש בכל ערך. לדוגמה, המחרוזת '123456789' משמשת לעיתים קרובות בדוגמאות.
  • טקסט או טקסטים: זהו הביטוי היחיד של משתמש הקצה או רשימת הביטויים של משתמשי הקצה. אם מספקים כמה ביטויים, קריאות לקוד לדוגמה יזהו את הכוונה של כל ביטוי. אפשר לנסות להגיד "אני יודע צרפתית".
  • Language code: קוד השפה של הביטוי של משתמש הקצה. בדוגמה הזו, נשתמש בסוכן עם השפה en-US.

REST

כדי לזהות כוונות, מבצעים קריאה לשיטה detectIntent במשאב Sessions.

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

  • PROJECT_ID: מזהה הפרויקט ב-Google Cloud
  • SESSION_ID: מזהה סשן

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

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

תוכן בקשת JSON:

{
  "query_input": {
    "text": {
      "text": "I know french",
      "language_code": "en-US"
    }
  }
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "responseId": "856510ca-f617-4e25-b0bb-a26c0a59e030-19db3199",
  "queryResult": {
    "queryText": "I know french",
    "parameters": {
      "language": "French",
      "language-programming": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Wow! I didn't know you knew French. How long have you known French?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Wow! I didn't know you knew French. How long have you known French?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/123456789/contexts/set-language-followup",
        "lifespanCount": 2,
        "parameters": {
          "language": "French",
          "language.original": "french",
          "language-programming": "",
          "language-programming.original": ""
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/fe45022f-e58a-484f-96e8-1cbd6628f648",
      "displayName": "set-language"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  }
}

כמה נקודות חשובות לגבי התשובה:

  • השדה queryResult.intent מכיל את ה-Intent שתאם.
  • הערך של השדה queryResult.fulfillmentMessages מכיל את התגובה להבעת הכוונה. זו התשובה שהמערכת שלכם צריכה להעביר למשתמש הקצה.
  • הערך של השדה queryResult.parameters מכיל את הפרמטרים שחולצו מהביטוי של משתמש הקצה.
  • השדה queryResult.outputContext מכיל את ההקשר הפעיל.

Go

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
	ctx := context.Background()

	sessionClient, err := dialogflow.NewSessionsClient(ctx)
	if err != nil {
		return "", err
	}
	defer sessionClient.Close()

	if projectID == "" || sessionID == "" {
		return "", fmt.Errorf("detect.DetectIntentText received empty project (%s) or session (%s)", projectID, sessionID)
	}

	sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
	textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
	queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
	queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
	request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

	response, err := sessionClient.DetectIntent(ctx, &request)
	if err != nil {
		return "", err
	}

	queryResult := response.GetQueryResult()
	fulfillmentText := queryResult.GetFulfillmentText()
	return fulfillmentText, nil
}

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class DetectIntentTexts {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntentTexts(
      String projectId, List<String> texts, String sessionId, 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 sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of(projectId, sessionId);
      System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input
      for (String text : texts) {
        // Set the text (hello) and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

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

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

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format(
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format(
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");

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

Node.js

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


/**
 * TODO(developer): UPDATE these variables before running the sample.
 */
// projectId: ID of the GCP project where Dialogflow agent is deployed
// const projectId = 'PROJECT_ID';
// sessionId: String representing a random number or hashed user identifier
// const sessionId = '123456';
// queries: A set of sequential queries to be send to Dialogflow agent for Intent Detection
// const queries = [
//   'Reserve a meeting room in Toronto office, there will be 5 of us',
//   'Next monday at 3pm for 1 hour, please', // Tell the bot when the meeting is taking place
//   'B'  // Rooms are defined on the Dialogflow agent, default options are A, B, or C
// ]
// languageCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates a session client
const sessionClient = new dialogflow.SessionsClient();

async function detectIntent(
  projectId,
  sessionId,
  query,
  contexts,
  languageCode
) {
  // The path to identify the agent that owns the created intent.
  const sessionPath = sessionClient.projectAgentSessionPath(
    projectId,
    sessionId
  );

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (contexts && contexts.length > 0) {
    request.queryParams = {
      contexts: contexts,
    };
  }

  const responses = await sessionClient.detectIntent(request);
  return responses[0];
}

async function executeQueries(projectId, sessionId, queries, languageCode) {
  // Keeping the context across queries let's us simulate an ongoing conversation with the bot
  let context;
  let intentResponse;
  for (const query of queries) {
    try {
      console.log(`Sending Query: ${query}`);
      intentResponse = await detectIntent(
        projectId,
        sessionId,
        query,
        context,
        languageCode
      );
      console.log('Detected intent');
      console.log(
        `Fulfillment Text: ${intentResponse.queryResult.fulfillmentText}`
      );
      // Use the context from this response for next queries
      context = intentResponse.queryResult.outputContexts;
    } catch (error) {
      console.log(error);
    }
  }
}
executeQueries(projectId, sessionId, queries, languageCode);

Python

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def detect_intent_texts(project_id, 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."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    for text in texts:
        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"session": session, "query_input": query_input}
        )

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))

שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Dialogflow CX בנושא ‎ .NET.

PHP: צריך לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Dialogflow CX ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Dialogflow CX בנושא Ruby.

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

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