iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
0
Google Developers Machine Learning

Overview of Machine Learning Products系列 第 25

[Day 25] Google Dialogflow - 2

每個系列的第二篇,就是踏入API的世界。今天要入門的是Dialogflow的API,不囉嗦先丟上文件

忘了前置動作的可以參考第三天的文章。

昨天有了IntentResponse的相關認知,還知道了有兩個預設的Default fallback intentDefault welcome intent,今天的進度可以快一些。

我們直接先來看code:

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

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

  if projectID == "" || sessionID == "" {
    return "", errors.New(fmt.Sprintf("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()
  fmt.Printf("fulfillmentText: \"%v\"\n", fulfillmentText)
  return fulfillmentText, nil
}

可以注意到有一個參數sessionID,這是每個對話的id,一段對話會被dialogflow存20分鐘。且我們自己要產生Unique的session id,以免Dialogflow混淆或衝突。

A session represents a conversation between a Dialogflow agent and an end-user. You create a session at the beginning of a conversation and use it for each turn of the conversation. Once the conversation has ended, you discontinue using the session.

You should not use the same session for concurrent conversations with different end-users. Dialogflow maintains the currently active contexts for each active session. Session data is stored by Dialogflow for 20 minutes.

Each session is determined unique by a session ID generated by your system. You create a new session by providing a new session ID in a detect intent request. A session ID is a string of at most 36 bytes in size. Your system is responsible for generating unique session IDs. They can be random numbers, hashed end-user identifiers, or any other values that are convenient for you to generate.

而這邊因為需要ProjectID的關係,我們就仿照Day16的設計,用Env環境變數帶進去。在我們主程式呼叫dialogflow.DetectIntentText("123456789", "嗨", "zh-TW")後,我們多執行幾次看看吧。
output

每次的都會回來不一樣的welcome message,是不是真的很像Google助理呢?

OK,今天的文章就到這邊,謝謝各位的觀看。

今天的code可以看github:https://github.com/josephMG/ithelp-2019/tree/Day-25


上一篇
[Day 24] Google Dialogflow - 1
下一篇
[Day 26] Google AutoML Table - 1
系列文
Overview of Machine Learning Products30

尚未有邦友留言

立即登入留言