יצירת שירות webhook

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

יצירת הפונקציה

אפשר ליצור פונקציות Cloud Run באמצעות מסוף Google Cloud (למשאבי העזרה, לפתיחת המסוף). כדי ליצור פונקציה למדריך הזה:

  1. חשוב שהנציג ב-Dialogflow והפונקציה יהיו באותו פרויקט. זו הדרך הקלה ביותר לתת ל-Dialogflow גישה מאובטחת לפונקציה. לפני שיוצרים את הפונקציה, בוחרים את הפרויקט במסוף Google Cloud .

    כניסה לדף לבחירת הפרויקט

  2. פותחים את דף הסקירה הכללית של פונקציות Cloud Run.

    לסקירה הכללית של פונקציות Cloud Run

  3. לוחצים על Create Function ומגדירים את השדות הבאים:

    • סביבה: דור ראשון
    • שם הפונקציה: tutorial-banking-webhook
    • ‫Region: אם ציינתם אזור לסוכן, השתמשו באותו אזור.
    • HTTP Trigger type: ‏ HTTP
    • כתובת URL: לוחצים על כפתור ההעתקה כאן ושומרים את הערך. תצטרכו את כתובת ה-URL הזו כשתגדירו את ה-webhook.
    • אימות: דרישת אימות
    • דרישת HTTPS: מסומן
  4. לוחצים על Save.

  5. לוחצים על Next (אין צורך בהגדרות מיוחדות של זמן ריצה, build, חיבורים או אבטחה).

  6. מגדירים את השדות הבאים:

    • ‫Runtime: בוחרים את סביבת זמן הריצה העדכנית של Go.
    • קוד מקור: עורך בתוך השורה
    • נקודת כניסה: HandleWebhookRequest
  7. מחליפים את הקוד בקוד הבא:

    package estwh
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    	"strings"
    
    	"cloud.google.com/go/spanner"
      "google.golang.org/grpc/codes"
    )
    
    // client is a Spanner client, created only once to avoid creation
    // for every request.
    // See: https://cloud.google.com/functions/docs/concepts/go-runtime#one-time_initialization
    var client *spanner.Client
    
    func init() {
    	// If using a database, these environment variables will be set.
    	pid := os.Getenv("PROJECT_ID")
    	iid := os.Getenv("SPANNER_INSTANCE_ID")
    	did := os.Getenv("SPANNER_DATABASE_ID")
    	if pid != "" && iid != "" && did != "" {
    		db := fmt.Sprintf("projects/%s/instances/%s/databases/%s",
    			pid, iid, did)
    		log.Printf("Creating Spanner client for %s", db)
    		var err error
    		// Use the background context when creating the client,
    		// but use the request context for calls to the client.
    		// See: https://cloud.google.com/functions/docs/concepts/go-runtime#contextcontext
    		client, err = spanner.NewClient(context.Background(), db)
    		if err != nil {
    			log.Fatalf("spanner.NewClient: %v", err)
    		}
    	}
    }
    
    type queryResult struct {
    	Action     string         `json:"action"`
    	Parameters map[string]any `json:"parameters"`
    }
    
    type text struct {
    	Text []string `json:"text"`
    }
    
    type message struct {
    	Text text `json:"text"`
    }
    
    // webhookRequest is used to unmarshal a WebhookRequest JSON object. Note that
    // not all members need to be defined--just those that you need to process.
    // As an alternative, you could use the types provided by
    // the Dialogflow protocol buffers:
    // https://godoc.org/google.golang.org/genproto/googleapis/cloud/dialogflow/v2#WebhookRequest
    type webhookRequest struct {
    	Session     string      `json:"session"`
    	ResponseID  string      `json:"responseId"`
    	QueryResult queryResult `json:"queryResult"`
    }
    
    // webhookResponse is used to marshal a WebhookResponse JSON object. Note that
    // not all members need to be defined--just those that you need to process.
    // As an alternative, you could use the types provided by
    // the Dialogflow protocol buffers:
    // https://godoc.org/google.golang.org/genproto/googleapis/cloud/dialogflow/v2#WebhookResponse
    type webhookResponse struct {
    	FulfillmentMessages []message `json:"fulfillmentMessages"`
    }
    
    // accountBalanceCheck handles the similar named action
    func accountBalanceCheck(ctx context.Context, request webhookRequest) (
    	webhookResponse, error) {
    	account := request.QueryResult.Parameters["account"].(string)
    	account = strings.ToLower(account)
    	var table string
    	if account == "savings account" {
    		table = "Savings"
    	} else {
    		table = "Checking"
    	}
    	s := "Your balance is $0"
    	if client != nil {
    		// A Spanner client exists, so access the database.
    		// See: https://pkg.go.dev/cloud.google.com/go/spanner#ReadOnlyTransaction.ReadRow
    		row, err := client.Single().ReadRow(ctx,
    			table,
    			spanner.Key{1}, // The account ID
    			[]string{"Balance"})
    		if err != nil {
    			if spanner.ErrCode(err) == codes.NotFound {
    				log.Printf("Account %d not found", 1)
    			} else {
    				return webhookResponse{}, err
    			}
    		} else {
    			// A row was returned, so check the value
    			var balance int64
    			err := row.Column(0, &balance)
    			if err != nil {
    				return webhookResponse{}, err
    			}
    			s = fmt.Sprintf("Your balance is $%.2f", float64(balance)/100.0)
    		}
    	}
    	response := webhookResponse{
    		FulfillmentMessages: []message{
    			{
    				Text: text{
    					Text: []string{s},
    				},
    			},
    		},
    	}
    	return response, nil
    }
    
    // Define a type for handler functions.
    type handlerFn func(ctx context.Context, request webhookRequest) (
    	webhookResponse, error)
    
    // Create a map from action to handler function.
    var handlers map[string]handlerFn = map[string]handlerFn{
    	"account.balance.check": accountBalanceCheck,
    }
    
    // handleError handles internal errors.
    func handleError(w http.ResponseWriter, err error) {
    	log.Printf("ERROR: %v", err)
    	http.Error(w,
    		fmt.Sprintf("ERROR: %v", err),
    		http.StatusInternalServerError)
    }
    
    // HandleWebhookRequest handles WebhookRequest and sends the WebhookResponse.
    func HandleWebhookRequest(w http.ResponseWriter, r *http.Request) {
    	var request webhookRequest
    	var response webhookResponse
    	var err error
    
    	// Read input JSON
    	if err = json.NewDecoder(r.Body).Decode(&request); err != nil {
    		handleError(w, err)
    		return
    	}
    	log.Printf("Request: %+v", request)
    
    	// Get the action from the request, and call the corresponding
    	// function that handles that action.
    	action := request.QueryResult.Action
    	if fn, ok := handlers[action]; ok {
    		response, err = fn(r.Context(), request)
    	} else {
    		err = fmt.Errorf("Unknown action: %s", action)
    	}
    	if err != nil {
    		handleError(w, err)
    		return
    	}
    	log.Printf("Response: %+v", response)
    
    	// Send response
    	if err = json.NewEncoder(w).Encode(&response); err != nil {
    		handleError(w, err)
    		return
    	}
    }

  8. לוחצים על Deploy.

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

הגדרת ה-webhook של הסוכן

עכשיו, כשה-webhook קיים כשירות, צריך לשייך אותו לנציג. כדי לעשות את זה, צריך להשתמש ב-fulfillment. כדי להפעיל ולנהל את מילוי הבקשות של הנציג:

  1. נכנסים למסוף Dialogflow ES.
  2. בוחרים את הנציג שנוצר מראש שיצרתם.
  3. בתפריט סרגל הצד הימני, לוחצים על Fulfillment.
  4. מעבירים את המתג בשדה Webhook למצב מופעל.
  5. מזינים את כתובת ה-URL שהעתקתם למעלה. משאירים את כל שאר השדות ריקים.
  6. בתחתית הדף, לוחצים על שמירה.

צילום מסך של הפעלת מילוי הבקשה.

אחרי שהפעלתם את מילוי הבקשה בסוכן, אתם צריכים להפעיל את מילוי הבקשה ב-intent:

  1. בתפריט שבסרגל הצד הימני, לוחצים על Intents (כוונות).
  2. בוחרים את ה-intent‏ account.balance.check.
  3. גוללים למטה לקטע Fulfillment (מילוי בקשות).
  4. מפעילים את האפשרות Enable webhook call for this intent.
  5. לוחצים על Save.

רוצה לנסות את הסוכן?

הסוכן מוכן לשימוש. לוחצים על הכפתור Test Agent כדי לפתוח את הסימולטור. נסו לנהל את השיחה הבאה עם הסוכן:

תור בשיחה את/ה סוכן
1 שלום שלום, תודה שבחרת בבנק ACME.
2 אני רוצה לדעת מה היתרה בחשבון שלי What account do you want the balance for: savings or checking?
3 עובר ושב היתרה העדכנית שלך: 0.00$

בשלב 3 בשיחה, ציינתם שסוג החשבון הוא "עו"ש". ל-Intent‏ account.balance.check יש פרמטר שנקרא account. הפרמטר הזה מוגדר כ-"checking" בשיחה הזו. ל-Intent יש גם ערך פעולה של "account.balance.check". שירות ה-webhook נקרא, ומועברים אליו ערכי הפרמטר והפעולה.

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

פתרון בעיות

הקוד של ה-webhook כולל פקודות רישום ביומן. אם נתקלתם בבעיות, נסו לעיין ביומנים של הפונקציה.

מידע נוסף

למידע נוסף על השלבים שלמעלה, אפשר לעיין במאמרים הבאים: