クイックスタート: API の操作

統合を使用しない場合は、エンドユーザーとやり取りするコードを記述する必要があります。会話ターンごとに、コードで Dialogflow API を呼び出してエージェントへのクエリを実行します。このガイドでは、コマンドラインで REST API を使用し、クライアント ライブラリを使用してエージェントを操作する方法について説明します。

始める前に

API を使用する予定がない場合は、このクイックスタートをスキップできます。

このガイドを読む前に、次の手順を行ってください。

  1. Dialogflow の基本について理解します。
  2. 手順に沿って設定してください。
  3. エージェントを作成するクイックスタート ガイドの手順を実行します。下記の手順では、そのガイドで開始したエージェントを使って作業を続けます。現在、そのエージェントがない場合は、build-agent-quickstart.zip をダウンロードし、ファイルをインポートします。

セッション

セッションは、Dialogflow エージェントとエンドユーザー間の会話を表します。会話の始めにセッションを作成し、会話のターンごとにセッションを使用します。会話が終了すると、セッションの使用も終了します。

同じセッションを別のエンドユーザーとの同時会話には使用しないでください。Dialogflow は、アクティブなセッションごとに、現在アクティブなコンテキストを保持します。セッション データは Dialogflow によって 20 分間保存されます。

各セッションは、システムによって生成されたセッション ID によって一意に判別されます。新しいセッションを作成するには、インテント検出リクエストで新しいセッション ID を指定します。セッション ID は最大 36 バイトの文字列です。システムによって固有のセッション ID が生成されます。この ID には、乱数、ハッシュ化されたエンドユーザー ID など、生成しやすい任意の値を使用できます。

インテントの検出

API を使用してインタラクションを行う場合、サービスがエンドユーザーと直接対話します。会話ターンごとに、サービスによって Sessions 型の detectIntent メソッドまたは streamingDetectIntent メソッドが呼び出され、Dialogflow にエンドユーザーの表現が送信されます。Dialogflow は、一致インテント、アクション、パラメータ、インテントに定義されたレスポンスに関する情報で応答します。サービスは必要に応じてアクション(データベース クエリや外部 API の呼び出し)を実行し、エンドユーザーにメッセージを送信します。このプロセスは、会話が終了するまで続きます。

以下のサンプルは、インテントを検出する方法を示しています。サンプルごとに、次の入力のサブセットを受け取ります。

  • Project ID: 設定手順で作成したプロジェクトにはこのプロジェクト ID を使用してください。
  • Session ID: エージェントをテストする場合は、任意の値を使用できます。たとえば、サンプルでは「123456789」が頻繁に使用されます。
  • Text or texts: 単一のエンドユーザー表現またはエンドユーザー表現のリストです。複数の表現を指定した場合、各表現の検出インテントが呼び出されます。「I know french」で試してみてください。
  • Language code: エンドユーザー表現の言語コードです。この例のエージェントには「en-US」を使用します。

REST

インテントを検出するには、Sessions リソースの detectIntent メソッドを呼び出します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID
  • SESSION_ID: セッション ID

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 フィールドには、一致したインテントが含まれます。
  • queryResult.fulfillmentMessages フィールドの値には、インテント レスポンスが含まれます。これは、システムがエンドユーザーに転送するレスポンスです。
  • queryResult.parameters フィールドの値には、エンドユーザー表現から抽出されたパラメータが含まれます。
  • queryResult.outputContext フィールドにはアクティブなコンテキストが含まれます。

Go

Dialogflow への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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 "", 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()
	return fulfillmentText, nil
}

Java

Dialogflow への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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 への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


/**
 * 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 への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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# の設定手順を行ってから、.NET 用の Dialogflow リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Dialogflow リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Dialogflow リファレンス ドキュメントをご覧ください。

プロダクション

エージェントを本番環境で実行する場合は、必ずプロダクションのベスト プラクティスを実施してください。