diff --git a/dialogflow/cloud-client/README.md b/dialogflow/cloud-client/README.md new file mode 100644 index 00000000000..96002de929b --- /dev/null +++ b/dialogflow/cloud-client/README.md @@ -0,0 +1,249 @@ +# Dialogflow API Java examples + +These samples demonstrate the use of the [Dialogflow API][dialogflow]. + +These samples show how to detect intents with text, audio, and streaming audio. + +These samples show how to manage contexts, entities, entity types, and intents + +[dialogflow]: https://dialogflow.com/docs/getting-started/basics +[google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java + +## Java Version + +This sample requires you to have +[Java8](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html). + +### Download Maven + +To get started, [download][maven-download] and [install][maven-install] it. + +[maven]: https://maven.apache.org +[maven-download]: https://maven.apache.org/download.cgi +[maven-install]: https://maven.apache.org/install.html + +### Setup + +* Create a project with the [Google Cloud Console][cloud-console], and enable + the [Dialogflow API][dialogflow-api]. +* [Set up][auth] authentication. For + example, from the Cloud Console, create a service account, + download its json credentials file, then set the appropriate environment + variable: + + ```bash + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json + ``` +* To run tests, set GOOGLE_CLOUD_PROJECT to your PROJECT_ID: + ``` + export GOOGLE_CLOUD_PROJECT=PROJECT_ID + ``` + ``` + mvn clean verify + ``` +* Set PROJECT_ID in pom.xml to your Google Cloud Project Id. +* Set SESSION_ID in pom.xml to a session name of your choice. (Defaults to SESSION_ID) +* Set CONTEXT_ID in pom.xml to a context name of your choice. (Defaults to CONTEXT_ID) + +[cloud-console]: https://console.cloud.google.com +[dialogflow-api]: https://console.cloud.google.com/apis/library/dialogflow.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/getting-started + +## Run the sample + +To build the sample, we use Maven. + +```bash +mvn clean package +``` + +### Set up the Agent +Import the sample agent (RoomReservation.zip) from the resources directory to your +[Dialogflow Project][dialogflow-import] using the following guide: +[Versioning with Import/Export][import-export-versioning] + +[dialogflow-import]: https://console.dialogflow.com/api-client/#/editAgent/ +[import-export-versioning]: https://dialogflow.com/docs/best-practices/import-export-for-versions + +## Samples + +### Detect Intent Texts +DialogFlow API Detect Intent sample with text inputs. + +``` +mvn exec:java -DDetectIntentText +``` + +### Detect Intent Audio +DialogFlow API Detect Intent sample with audio files. Returns the result of detect intent with an +audio file as input. + +Note: Execute the following commands in order to yield reasonable outputs. +``` +mvn exec:java -DDetectIntentAudioBookARoom +``` +``` +mvn exec:java -DDetectIntentAudioMountainView +``` +``` +mvn exec:java -DDetectIntentAudioToday +``` +``` +mvn exec:java -DDetectIntentAudio230PM +``` +``` +mvn exec:java -DDetectIntentAudioHalfAnHour +``` +``` +mvn exec:java -DDetectIntentAudioTwoPeople +``` + +### Detect Intent Stream +DialogFlow API Detect Intent sample with audio files processes as an audio stream. + +``` +mvn exec:java -DDetectIntentStreamBookARoom +``` +``` +mvn exec:java -DDetectIntentStreamMountainView +``` + +### Detect Intent With Model Selection +DialogFlow API Detect Intent sample with model selection +``` +mvn exec:java -DDetectIntentWithModelSelection -Dexec.args='--projectId PROJECT_ID --audioFilePath resources/book_a_room.wav --sessionId SESSION_ID' +``` + +### Detect Intent With Sentiment Analysis +DialogFlow API Detect Intent sample with sentiment analysis +``` +mvn exec:java -DDetectIntentWithSentimentAnalysis -Dexec.args="--projectId PROJECT_ID -sessionId SESSION_ID 'hello'" +``` + +### Detect Intent With Text-to-Speech +DialogFlow API Detect Intent sample with Text-to-Speech +``` +mvn exec:java -DetectIntentTTSResponse +``` + +### Detect Intent Knowledge +DialogFlow API Detect Intent sample with querying knowledge connector. +``` +mvn exec:java -DDetectIntentKnowledge -Dexec.args="--projectId PROJECT_ID --knowledgeBaseId KNOWLEDGE_BASE_ID -sessionId SESSION_ID 'Where can I find pricing information?'" +``` + +### Context Management +DialogFlow API Context sample. + +Lists contexts +``` +mvn exec:java -DContextManagementList +``` +Create an entity type +``` +mvn exec:java -DContextManagementCreate +``` +Delete entity type +``` +mvn exec:java -DContextManagementDelete +``` + +### Entity Management +DialogFlow API Entity sample. + +List entities +``` +mvn exec:java -DEntityManagementList +``` +Create an entity +``` +mvn exec:java -DEntityManagementCreate +``` +Delete entity +``` +mvn exec:java -DEntityManagementDelete +``` + +### Entity Type Management +DialogFlow API EntityType sample. + +List entity types +``` +mvn exec:java -DEntityTypeManagementList +``` +Create an entity type +``` +mvn exec:java -DEntityTypeManagementCreate +``` +Delete entity type +``` +mvn exec:java -DEntityTypeManagementDelete +``` + +### Intent Management +DialogFlow API Intent sample. + +List intents +``` +mvn exec:java -DIntentManagementList +``` +Create an intent +``` +mvn exec:java -DIntentManagementCreate +``` +Delete intent +``` +mvn exec:java -DIntentManagementDelete +``` + +### Session Entity Type Management +DialogFlow API SessionEntityType sample. + +List session entity types +``` +mvn exec:java -DSessionEntityTypeManagementList +``` +Create session entity type +``` +mvn exec:java -DSessionEntityTypeManagementCreate +``` +Delete session entity type +``` +mvn exec:java -DSessionEntityTypeManagementDelete +``` + +### Knowledge Base Management +DialogFlow API KnowledgeBaseManagement sample + +List knowledge base +``` +mvn exec:java -DKnowledgeBaseManagement -Dexec.args='list --projectId PROJECT_ID' +``` +Create knowledge base +``` +mvn exec:java -DKnowledgeBaseManagement -Dexec.args='create DISPLAY_NAME --projectId PROJECT_ID' +``` +Delete knowledge base +``` +mvn exec:java -DKnowledgeBaseManagement -Dexec.args='delete KNOWLEDGE_BASE_ID --projectId PROJECT_ID' +``` + +### Document Management +DialogFlow API DocumentManagement sample + +List documents +``` +mvn exec:java -DDocumentManagement -Dexec.args='list --projectId PROJECT_ID --knowledgeBaseId KNOWLEDGE_BASE_ID' +``` +Create doucment +``` +mvn exec:java -DDocumentManagement -Dexec.args='create KNOWLEDGE_BASE_ID --projectId PROJECT_ID + --displayName DISPLAY_NAME + --mimeType text/html + --knowledgeType FAQ' + --contentUri https://cloud.google.com/storage/docs/faq' +``` +Delete doucment +``` +mvn exec:java -DDocumentManagement -Dexec.args='delete KNOWLEDGE_BASE_ID --projectId PROJECT_ID --documentId DOCUMENT_ID +``` \ No newline at end of file diff --git a/dialogflow/cloud-client/pom.xml b/dialogflow/cloud-client/pom.xml new file mode 100644 index 00000000000..ddcdf24d8ee --- /dev/null +++ b/dialogflow/cloud-client/pom.xml @@ -0,0 +1,1455 @@ + + + 4.0.0 + com.example.dialogflow + dialogflow-samples + jar + + + + com.google.cloud.samples + shared-configuration + 1.0.10 + + + + 1.8 + 1.8 + UTF-8 + + java-docs-samples-testing + SESSION_ID + CONTEXT_ID + + + + + com.google.cloud + google-cloud-dialogflow + 0.55.1-alpha + + + net.sourceforge.argparse4j + argparse4j + 0.8.1 + + + + + junit + junit + 4.12 + test + + + com.google.truth + truth + 0.42 + test + + + + + + + ContextManagement + + + ContextManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.ContextManagement + false + + + + + + + + + ContextManagementList + + + ContextManagementList + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.ContextManagement + + list + --sessionId + ${sessionId} + --projectId + ${projectId} + + false + + + + + + + + + ContextManagementCreate + + + ContextManagementCreate + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.ContextManagement + + create + --sessionId + ${sessionId} + --projectId + ${projectId} + --contextId + ${contextId} + + false + + + + + + + + + ContextManagementDelete + + + ContextManagementDelete + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.ContextManagement + + delete + --sessionId + ${sessionId} + --projectId + ${projectId} + --contextId + ${contextId} + + false + + + + + + + + + DetectIntentAudio + + + DetectIntentAudio + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + false + + + + + + + + + DetectIntentAudioBookARoom + + + DetectIntentAudioBookARoom + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/book_a_room.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentAudioMountainView + + + DetectIntentAudioMountainView + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/mountain_view.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentAudioToday + + + DetectIntentAudioToday + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/today.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentAudio230PM + + + DetectIntentAudio230PM + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/230pm.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentAudioHalfAnHour + + + DetectIntentAudioHalfAnHour + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/half_an_hour.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentAudioTwoPeople + + + DetectIntentAudioTwoPeople + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentAudio + + --projectId + ${projectId} + --audioFilePath + resources/two_people.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentStreamBookARoom + + + DetectIntentStreamBookARoom + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentStream + + --projectId + ${projectId} + --audioFilePath + resources/book_a_room.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentStream + + + DetectIntentStream + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentStream + false + + + + + + + + + DetectIntentStreamMountainView + + + DetectIntentStreamMountainView + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentStream + + --projectId + ${projectId} + --audioFilePath + resources/mountain_view.wav + --sessionId + ${sessionId} + + false + + + + + + + + + DetectIntentTexts + + + DetectIntentTexts + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentTexts + false + + + + + + + + + DetectIntentText + + + DetectIntentText + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentTexts + + --projectId + ${projectId} + --sessionId + ${sessionId} + "hello" + "book a meeting room" + "Mountain View" + "tomorrow" + "10 am" + "2 hours" + "10 people" + "A" + "yes" + + false + + + + + + + + + DetectIntentWithTTSResponses + + + DetectIntentWithTTSResponses + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentWithTextToSpeechResponse + false + + + + + + + + + DetectIntentTTSResponse + + + DetectIntentTTSResponse + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentWithTextToSpeechResponse + + --projectId + ${projectId} + --sessionId + ${sessionId} + "hello" + "book a meeting room" + "Mountain View" + "tomorrow" + "10 am" + "2 hours" + "10 people" + "A" + "yes" + + false + + + + + + + + + DetectIntentSentimentAnalysis + + + DetectIntentSentimentAnalysis + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentWithSentimentAnalysis + false + + + + + + + + + DetectIntentKnowledge + + + DetectIntentKnowledge + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentKnowledge + false + + + + + + + + + + EntityManagement + + + EntityManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityManagement + false + + + + + + + + + DetectIntentWithModelSelection + + + DetectIntentWithModelSelection + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DetectIntentWithModelSelection + false + + + + + + + + + EntityManagementList + + + EntityManagementList + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityManagement + + list + --projectId + ${projectId} + --entityTypeId + e57238e2-e692-44ea-9216-6be1b2332e2a + + false + + + + + + + + + EntityManagementCreate + + + EntityManagementCreate + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityManagement + + create + new_room + --projectId + ${projectId} + --entityTypeId + e57238e2-e692-44ea-9216-6be1b2332e2a + --synonyms + basement + cellar + + false + + + + + + + + + EntityManagementDelete + + + EntityManagementDelete + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityManagement + + delete + new_room + --projectId + ${projectId} + --entityTypeId + e57238e2-e692-44ea-9216-6be1b2332e2a + + false + + + + + + + + + EntityTypeManagement + + + EntityTypeManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityTypeManagement + false + + + + + + + + + EntityTypeManagementList + + + EntityTypeManagementList + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityTypeManagement + + list + --projectId + ${projectId} + + false + + + + + + + + + EntityTypeManagementCreate + + + EntityTypeManagementCreate + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityTypeManagement + + create + employee + --projectId + ${projectId} + + false + + + + + + + + + EntityTypeManagementDelete + + + EntityTypeManagementDelete + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.EntityTypeManagement + + delete + + + + + false + + + + + + + + + IntentManagement + + + IntentManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.IntentManagement + false + + + + + + + + + IntentManagementList + + + IntentManagementList + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.IntentManagement + + list + --projectId + ${projectId} + + false + + + + + + + + + IntentManagementCreate + + + IntentManagementCreate + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.IntentManagement + + create + "room.cancellation - yes" + --projectId + ${projectId} + --action + room.cancel + --trainingPhrasesParts + "cancel" + "cancellation" + --messageTexts + "Are you sure you want to cancel?" + "Cancelled." + + false + + + + + + + + + IntentManagementDelete + + + IntentManagementDelete + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.IntentManagement + + + + + + + false + + + + + + + + + KnowledgeBaseManagement + + + KnowledgeBaseManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.KnowledgeBaseManagement + false + + + + + + + + + DocumentManagement + + + DocumentManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.DocumentManagement + false + + + + + + + + + SessionEntityTypeManagement + + + SessionEntityTypeManagement + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.SessionEntityTypeManagement + false + + + + + + + + + SessionEntityTypeManagementList + + + SessionEntityTypeManagementList + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.SessionEntityTypeManagement + + list + --projectId + ${projectId} + --sessionId + ${sessionId} + + false + + + + + + + + + SessionEntityTypeManagementCreate + + + SessionEntityTypeManagementCreate + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.SessionEntityTypeManagement + + create + --projectId + ${projectId} + --sessionId + ${sessionId} + --entityTypeDisplayName + room + --entityValues + C + D + E + F + + false + + + + + + + + + SessionEntityTypeManagementDelete + + + SessionEntityTypeManagementDelete + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.example.dialogflow.SessionEntityTypeManagement + + delete + --projectId + ${projectId} + --sessionId + ${sessionId} + --entityTypeDisplayName + room + + false + + + + + + + diff --git a/dialogflow/cloud-client/resources/230pm.wav b/dialogflow/cloud-client/resources/230pm.wav new file mode 100644 index 00000000000..7509eca784d Binary files /dev/null and b/dialogflow/cloud-client/resources/230pm.wav differ diff --git a/dialogflow/cloud-client/resources/RoomReservation.zip b/dialogflow/cloud-client/resources/RoomReservation.zip new file mode 100644 index 00000000000..7873fb628c8 Binary files /dev/null and b/dialogflow/cloud-client/resources/RoomReservation.zip differ diff --git a/dialogflow/cloud-client/resources/book_a_room.wav b/dialogflow/cloud-client/resources/book_a_room.wav new file mode 100644 index 00000000000..9124e927946 Binary files /dev/null and b/dialogflow/cloud-client/resources/book_a_room.wav differ diff --git a/dialogflow/cloud-client/resources/half_an_hour.wav b/dialogflow/cloud-client/resources/half_an_hour.wav new file mode 100644 index 00000000000..71010a871bb Binary files /dev/null and b/dialogflow/cloud-client/resources/half_an_hour.wav differ diff --git a/dialogflow/cloud-client/resources/mountain_view.wav b/dialogflow/cloud-client/resources/mountain_view.wav new file mode 100644 index 00000000000..1c5437f7cb5 Binary files /dev/null and b/dialogflow/cloud-client/resources/mountain_view.wav differ diff --git a/dialogflow/cloud-client/resources/today.wav b/dialogflow/cloud-client/resources/today.wav new file mode 100644 index 00000000000..d47ed78b351 Binary files /dev/null and b/dialogflow/cloud-client/resources/today.wav differ diff --git a/dialogflow/cloud-client/resources/two_people.wav b/dialogflow/cloud-client/resources/two_people.wav new file mode 100644 index 00000000000..5114ebbd310 Binary files /dev/null and b/dialogflow/cloud-client/resources/two_people.wav differ diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/ContextManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/ContextManagement.java new file mode 100644 index 00000000000..0f72988fb1f --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/ContextManagement.java @@ -0,0 +1,177 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.Context; +import com.google.cloud.dialogflow.v2.ContextName; +import com.google.cloud.dialogflow.v2.ContextsClient; +import com.google.cloud.dialogflow.v2.SessionName; +import com.google.protobuf.Value; + +import java.util.Map.Entry; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + + +/** + * DialogFlow API Context sample. + */ +public class ContextManagement { + + // [START dialogflow_list_contexts] + /** + * Lists contexts + * @param sessionId Identifier of the DetectIntent session. + * @param projectId Project/Agent Id. + */ + public static void listContexts(String sessionId, String projectId) throws Exception { + // Instantiates a client + try (ContextsClient contextsClient = ContextsClient.create()) { + // Set the session name using the sessionId (UUID) and projectId (my-project-id) + SessionName session = SessionName.of(projectId, sessionId); + + // Performs the list contexts request + System.out.format("Contexts for session %s:\n", session.toString()); + for (Context context : contextsClient.listContexts(session).iterateAll()) { + System.out.format("Context name: %s\n", context.getName()); + System.out.format("Lifespan Count: %d\n", context.getLifespanCount()); + System.out.format("Fields:\n"); + for (Entry entry : context.getParameters().getFieldsMap().entrySet()) { + if (entry.getValue().hasStructValue()) { + System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue()); + } + } + } + } + } + // [END dialogflow_list_contexts] + + // [START dialogflow_create_context] + /** + * Create an entity type with the given display name + * @param contextId The Id of the context. + * @param sessionId Identifier of the DetectIntent session. + * @param lifespanCount The lifespan count of the context. + * @param projectId Project/Agent Id. + */ + public static void createContext(String contextId, String sessionId, String projectId, + int lifespanCount) throws Exception { + // Instantiates a client + try (ContextsClient contextsClient = ContextsClient.create()) { + // Set the session name using the sessionId (UUID) and projectID (my-project-id) + SessionName session = SessionName.of(projectId, sessionId); + + // Create the context name with the projectId, sessionId, and contextId + ContextName contextName = ContextName.newBuilder() + .setProject(projectId) + .setSession(sessionId) + .setContext(contextId) + .build(); + + // Create the context with the context name and lifespan count + Context context = Context.newBuilder() + .setName(contextName.toString()) // The unique identifier of the context + .setLifespanCount(lifespanCount) // Number of query requests before the context expires. + .build(); + + // Performs the create context request + Context response = contextsClient.createContext(session, context); + System.out.format("Context created: %s\n", response); + } + } + // [END dialogflow_create_context] + + // [START dialogflow_delete_context] + /** + * Delete entity type with the given entity type name + * @param contextId The Id of the context. + * @param sessionId Identifier of the DetectIntent session. + * @param projectId Project/Agent Id. + */ + public static void deleteContext(String contextId, String sessionId, String projectId) + throws Exception { + // Instantiates a client + try (ContextsClient contextsClient = ContextsClient.create()) { + // Create the context name with the projectId, sessionId, and contextId + ContextName contextName = ContextName.of(projectId, sessionId, contextId); + // Performs the delete context request + contextsClient.deleteContext(contextName); + } + } + // [END dialogflow_delete_context] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("ContextManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a context."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DContextManagement -Dexec.args='list --sessionId SESSION_ID " + + "--projectId PROJECT_ID'"); + listParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DContextManagement -Dexec.args='create --sessionId SESSION_ID " + + "--projectId PROJECT_ID --contextId CONTEXT_ID'"); + createParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--contextId") + .help("The Id of the context") + .required(true); + createParser.addArgument("--lifespanCount") + .help("The lifespan count of the context (Default: 1)").setDefault(1); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DContextManagement -Dexec.args='delete --sessionId SESSION_ID " + + "--projectId PROJECT_ID --contextId CONTEXT_ID'"); + deleteParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + deleteParser.addArgument("--contextId") + .help("The Id of the context") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listContexts(namespace.get("sessionId"), namespace.get("projectId")); + } else if (namespace.get("command").equals("create")) { + createContext(namespace.get("contextId"), namespace.get("sessionId"), + namespace.get("projectId"), namespace.get("lifespanCount")); + } else if (namespace.get("command").equals("delete")) { + deleteContext(namespace.get("contextId"), namespace.get("sessionId"), + namespace.get("projectId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java new file mode 100644 index 00000000000..c5d0c9a6fe8 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java @@ -0,0 +1,134 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.AudioEncoding; +import com.google.cloud.dialogflow.v2.DetectIntentRequest; +import com.google.cloud.dialogflow.v2.DetectIntentResponse; +import com.google.cloud.dialogflow.v2.InputAudioConfig; +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.protobuf.ByteString; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + + +/** + * DialogFlow API Detect Intent sample with audio files. + */ +public class DetectIntentAudio { + + // [START dialogflow_detect_intent_audio] + /** + * Returns the result of detect intent with an audio file as input. + * + * Using the same `session_id` between requests allows continuation of the conversation. + * @param projectId Project/Agent Id. + * @param audioFilePath Path to the audio file. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId, + String languageCode) + throws Exception { + // 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()); + + // Note: hard coding audioEncoding and sampleRateHertz for simplicity. + // Audio encoding of the audio content sent in the query request. + AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; + int sampleRateHertz = 16000; + + // Instructs the speech recognizer how to process the audio content. + InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() + .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 + .setLanguageCode(languageCode) // languageCode = "en-US" + .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 + .build(); + + // Build the query with the InputAudioConfig + QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); + + // Read the bytes from the audio file + byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath)); + + // Build the DetectIntentRequest + DetectIntentRequest request = DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setInputAudio(ByteString.copyFrom(inputAudio)) + .build(); + + // Performs the detect intent request + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // 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.getFulfillmentText()); + } + } + // [END dialogflow_detect_intent_audio] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentAudio") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with an audio file as input.\n" + + "mvn exec:java -DDetectIntentAudio -Dexec.args='--projectId PROJECT_ID " + + "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--audioFilePath") + .help("Path to the audio file") + .required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentAudio(namespace.get("projectId"), namespace.get("audioFilePath"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java new file mode 100644 index 00000000000..854803d964e --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java @@ -0,0 +1,151 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; +import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; +import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers; +import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer; +import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; +import com.google.cloud.dialogflow.v2beta1.QueryInput; +import com.google.cloud.dialogflow.v2beta1.QueryParameters; +import com.google.cloud.dialogflow.v2beta1.QueryResult; +import com.google.cloud.dialogflow.v2beta1.SessionName; +import com.google.cloud.dialogflow.v2beta1.SessionsClient; +import com.google.cloud.dialogflow.v2beta1.TextInput; +import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; + +import java.util.List; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + + +/** DialogFlow API Detect Intent sample with querying knowledge connector. */ +public class DetectIntentKnowledge { + + // [START dialogflow_detect_intent_knowledge] + /** + * Returns the result of detect intent with text as input. + * + *

Using the same `session_id` between requests allows continuation of the conversation. + * + * @param projectId Project/Agent Id. + * @param knowledgeBaseId Knowledge base Id. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + * @param texts The texts to be processed. + */ + public static void detectIntentKnowledge( + String projectId, + String knowledgeBaseId, + String sessionId, + String languageCode, + List texts) + throws Exception { + // 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 and language code (en-US) for the query + Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); + // Build the query with the TextInput + QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); + + KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); + QueryParameters queryParameters = + QueryParameters.newBuilder() + .addKnowledgeBaseNames(knowledgeBaseName.toString()) + .build(); + + DetectIntentRequest detectIntentRequest = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + // Performs the detect intent request + DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest); + + // Display the query result + QueryResult queryResult = response.getQueryResult(); + + System.out.format("Knowledge results:\n"); + System.out.format("====================\n"); + 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.getFulfillmentText()); + KnowledgeAnswers knowledgeAnswers = queryResult.getKnowledgeAnswers(); + for (Answer answer : knowledgeAnswers.getAnswersList()) { + System.out.format(" - Answer: '%s'\n", answer.getAnswer()); + System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence()); + } + } + } + } + // [END dialogflow_detect_intent_knowledge] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentKnowledge") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with text as input for a Knowledge " + + "Base.\n" + + "mvn exec:java -DDetectIntentKnowledge -Dexec.args=\"--projectId PROJECT_ID " + + "--knowledgeBaseId KNOWLEDGE_BASE_ID -sessionId SESSION_ID " + + "'Where can I find pricing information?'\"\n"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--knowledgeBaseId") + .help("The ID of the Knowledge Base") + .required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + parser.addArgument("texts") + .nargs("+") + .help("Text: 'Where can I find pricing information?'") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentKnowledge(namespace.get("projectId"), namespace.get("knowledgeBaseId"), + namespace.get("sessionId"), namespace.get("languageCode"), namespace.get("texts")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java new file mode 100644 index 00000000000..2594b1bfb34 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java @@ -0,0 +1,198 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + + +// Imports the Google Cloud client library + +import com.google.api.gax.rpc.ApiStreamObserver; +import com.google.cloud.dialogflow.v2.AudioEncoding; +import com.google.cloud.dialogflow.v2.InputAudioConfig; +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.StreamingDetectIntentRequest; +import com.google.cloud.dialogflow.v2.StreamingDetectIntentResponse; +import com.google.protobuf.ByteString; + +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + + +/** + * DialogFlow API Detect Intent sample with audio files processes as an audio stream. + */ +public class DetectIntentStream { + + // [START dialogflow_detect_intent_streaming] + /** + * Returns the result of detect intent with streaming audio as input. + * + * Using the same `session_id` between requests allows continuation of the conversation. + * @param projectId Project/Agent Id. + * @param audioFilePath The audio file to be processed. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentStream(String projectId, String audioFilePath, String sessionId, + String languageCode) throws Throwable { + // Start bi-directional StreamingDetectIntent stream. + final CountDownLatch notification = new CountDownLatch(1); + final List responseThrowables = new ArrayList<>(); + final List responses = new ArrayList<>(); + + // 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()); + + // Note: hard coding audioEncoding and sampleRateHertz for simplicity. + // Audio encoding of the audio content sent in the query request. + AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; + int sampleRateHertz = 16000; + + // Instructs the speech recognizer how to process the audio content. + InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() + .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 + .setLanguageCode(languageCode) // languageCode = "en-US" + .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 + .build(); + + ApiStreamObserver responseObserver = + new ApiStreamObserver() { + @Override + public void onNext(StreamingDetectIntentResponse response) { + // Do something when receive a response + responses.add(response); + } + + @Override + public void onError(Throwable t) { + // Add error-handling + responseThrowables.add(t); + } + + @Override + public void onCompleted() { + // Do something when complete. + notification.countDown(); + } + }; + + // Performs the streaming detect intent callable request + ApiStreamObserver requestObserver = + sessionsClient.streamingDetectIntentCallable().bidiStreamingCall(responseObserver); + + // Build the query with the InputAudioConfig + QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); + + try (FileInputStream audioStream = new FileInputStream(audioFilePath)) { + // The first request contains the configuration + StreamingDetectIntentRequest request = StreamingDetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Make the first request + requestObserver.onNext(request); + + // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality + // you would split the user input by time. + byte[] buffer = new byte[4096]; + int bytes; + while ((bytes = audioStream.read(buffer)) != -1) { + requestObserver.onNext( + StreamingDetectIntentRequest.newBuilder() + .setInputAudio(ByteString.copyFrom(buffer, 0, bytes)) + .build()); + } + } catch (RuntimeException e) { + // Cancel stream. + requestObserver.onError(e); + } + // Half-close the stream. + requestObserver.onCompleted(); + // Wait for the final response (without explicit timeout). + notification.await(); + // Process errors/responses. + if (!responseThrowables.isEmpty()) { + throw responseThrowables.get(0); + } + if (responses.isEmpty()) { + throw new RuntimeException("No response from Dialogflow."); + } + + for (StreamingDetectIntentResponse response : responses) { + if (response.hasRecognitionResult()) { + System.out.format( + "Intermediate transcript: '%s'\n", response.getRecognitionResult().getTranscript()); + } + } + + // Display the last query result + QueryResult queryResult = responses.get(responses.size() - 1).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.getFulfillmentText()); + } + } + // [END dialogflow_detect_intent_streaming] + + public static void main(String[] args) throws Throwable { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentStream") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with streaming audio as input.\n" + + "mvn exec:java -DDetectIntentStream -Dexec.args='--projectId PROJECT_ID " + + "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--audioFilePath") + .help("Path to the audio file") + .required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentStream(namespace.get("projectId"), namespace.get("audioFilePath"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java new file mode 100644 index 00000000000..388147fa231 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java @@ -0,0 +1,118 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +// Imports the Google Cloud client library +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.cloud.dialogflow.v2.TextInput.Builder; + +import java.util.List; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + + +/** + * DialogFlow API Detect Intent sample with text inputs. + */ +public class DetectIntentTexts { + + // [START dialogflow_detect_intent_text] + /** + * Returns the result of detect intent with texts as inputs. + * + * Using the same `session_id` between requests allows continuation of the conversation. + * @param projectId Project/Agent Id. + * @param texts The text intents to be detected based on what a user says. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentTexts(String projectId, List texts, String sessionId, + String languageCode) throws Exception { + // 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 + 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.getFulfillmentText()); + } + } + } + // [END dialogflow_detect_intent_text] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentTexts") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with text as input for a Knowledge " + + "Base.\n" + + "mvn exec:java -DDetectIntentTexts -Dexec.args=\"--projectId PROJECT_ID " + + "--sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' 'tomorrow' " + + "'10 am' '2 hours' '10 people' 'A' 'yes'\"\n"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + parser.addArgument("texts") + .nargs("+") + .help("Text: 'Where can I find pricing information?'") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentTexts(namespace.get("projectId"), namespace.get("texts"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java new file mode 100644 index 00000000000..e4b842a45d6 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java @@ -0,0 +1,136 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import com.google.cloud.dialogflow.v2beta1.AudioEncoding; +import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; +import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; +import com.google.cloud.dialogflow.v2beta1.InputAudioConfig; +import com.google.cloud.dialogflow.v2beta1.QueryInput; +import com.google.cloud.dialogflow.v2beta1.QueryResult; +import com.google.cloud.dialogflow.v2beta1.SessionName; +import com.google.cloud.dialogflow.v2beta1.SessionsClient; +import com.google.protobuf.ByteString; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + +public class DetectIntentWithModelSelection { + + // [START dialogflow_detect_intent_with_model_selection] + /** + * Returns the result of detect intent with an audio file as input. + * + *

Using the same `session_id` between requests allows continuation of the conversation. + * + * @param projectId Project/Agent Id. + * @param audioFilePath Path to the audio file. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentWithModelSelection( + String projectId, String sessionId, String audioFilePath, String languageCode) + throws Exception { + // 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()); + + // Note: hard coding audioEncoding and sampleRateHertz for simplicity. + // Audio encoding of the audio content sent in the query request. + AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; + int sampleRateHertz = 16000; + + // Instructs the speech recognizer how to process the audio content. + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding( + audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 + .setLanguageCode(languageCode) // languageCode = "en-US" + .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 + .setModel("phone_call") // model = phone call + .build(); + + // Build the query with the InputAudioConfig + QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); + + // Read the bytes from the audio file + byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath)); + + // Build the DetectIntentRequest + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setInputAudio(ByteString.copyFrom(inputAudio)) + .build(); + // Performs the detect intent request + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // 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.getFulfillmentText()); + } + } + // [END dialogflow_detect_intent_with_model_selection] + + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentWithModelSelection") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with an audio file as input.\n" + + "mvn exec:java -DDetectIntentWithModelSelection -Dexec.args='--projectId " + + "PROJECT_ID --audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--audioFilePath") + .help("Path to the audio file") + .required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentWithModelSelection(namespace.get("projectId"), namespace.get("audioFilePath"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } + +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java new file mode 100644 index 00000000000..4194074e716 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java @@ -0,0 +1,140 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; +import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; +import com.google.cloud.dialogflow.v2beta1.QueryInput; +import com.google.cloud.dialogflow.v2beta1.QueryParameters; +import com.google.cloud.dialogflow.v2beta1.QueryResult; +import com.google.cloud.dialogflow.v2beta1.SentimentAnalysisRequestConfig; +import com.google.cloud.dialogflow.v2beta1.SessionName; +import com.google.cloud.dialogflow.v2beta1.SessionsClient; +import com.google.cloud.dialogflow.v2beta1.TextInput; +import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; + +import java.util.List; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + +public class DetectIntentWithSentimentAnalysis { + + // [START dialogflow_detect_intent_with_sentiment_analysis] + /** + * Returns the result of detect intent with texts as inputs. + * + *

Using the same `session_id` between requests allows continuation of the conversation. + * + * @param projectId Project/Agent Id. + * @param texts The text intents to be detected based on what a user says. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentSentimentAnalysis( + String projectId, List texts, String sessionId, String languageCode) + throws Exception { + // 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 + Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); + + // Build the query with the TextInput + QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); + + // + SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig = + SentimentAnalysisRequestConfig.newBuilder().setAnalyzeQueryTextSentiment(true).build(); + + QueryParameters queryParameters = + QueryParameters.newBuilder() + .setSentimentAnalysisRequestConfig(sentimentAnalysisRequestConfig) + .build(); + DetectIntentRequest detectIntentRequest = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + + // Performs the detect intent request + DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest); + + // 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.getFulfillmentText()); + System.out.format( + "Sentiment Score: '%s'\n", + queryResult.getSentimentAnalysisResult().getQueryTextSentiment().getScore()); + } + } + } + // [END dialogflow_detect_intent_with_sentiment_analysis] + + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentWithSentimentAnalysis") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with text as input" + + "Base.\n" + + "mvn exec:java -DDetectIntentWithSentimentAnalysis -Dexec.args=\"--projectId " + + "PROJECT_ID --sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' " + + "'tomorrow' '10 am' '2 hours' '10 people' 'A' 'yes'\"\n"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + parser.addArgument("texts") + .nargs("+") + .help("Text: 'Where can I find pricing information?'") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentSentimentAnalysis(namespace.get("projectId"), namespace.get("texts"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } + + +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java new file mode 100644 index 00000000000..c6acfd84922 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java @@ -0,0 +1,141 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; +import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; +import com.google.cloud.dialogflow.v2beta1.OutputAudioConfig; +import com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding; +import com.google.cloud.dialogflow.v2beta1.QueryInput; +import com.google.cloud.dialogflow.v2beta1.QueryResult; +import com.google.cloud.dialogflow.v2beta1.SessionName; +import com.google.cloud.dialogflow.v2beta1.SessionsClient; +import com.google.cloud.dialogflow.v2beta1.TextInput; +import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; + +import java.util.List; +import java.util.UUID; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + +public class DetectIntentWithTextToSpeechResponse { + + // [START dialogflow_detect_intent_with_texttospeech_response] + /** + * Returns the result of detect intent with texts as inputs. + * + *

Using the same `session_id` between requests allows continuation of the conversation. + * + * @param projectId Project/Agent Id. + * @param texts The text intents to be detected based on what a user says. + * @param sessionId Identifier of the DetectIntent session. + * @param languageCode Language code of the query. + */ + public static void detectIntentWithTexttoSpeech( + String projectId, List texts, String sessionId, String languageCode) + throws Exception { + // 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 + Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); + + // Build the query with the TextInput + QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); + + // + OutputAudioEncoding audioEncoding = OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16; + int sampleRateHertz = 16000; + OutputAudioConfig outputAudioConfig = + OutputAudioConfig.newBuilder() + .setAudioEncoding(audioEncoding) + .setSampleRateHertz(sampleRateHertz) + .build(); + + DetectIntentRequest dr = + DetectIntentRequest.newBuilder() + .setQueryInput(queryInput) + .setOutputAudioConfig(outputAudioConfig) + .setSession(session.toString()) + .build(); + + // Performs the detect intent request + // DetectIntentResponse response = sessionsClient.detectIntent(session, + // queryInput,outputAudioConfig); + DetectIntentResponse response = sessionsClient.detectIntent(dr); + + // 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.getFulfillmentText()); + } + } + } + + // [END dialogflow_detect_intent_with_texttospeech_response] + + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DetectIntentWithTextToSpeechResponse") + .build() + .defaultHelp(true) + .description("Returns the result of detect intent with text as input" + + "Base.\n" + + "mvn exec:java -DDetectIntentWithTTSResponses -Dexec.args=\"--projectId " + + "PROJECT_ID --sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' " + + "'tomorrow' '10 am' '2 hours' '10 people' 'A' 'yes'\"\n"); + + parser.addArgument("--projectId").help("Project/Agent Id").required(true); + + parser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session (Default: UUID.)") + .setDefault(UUID.randomUUID().toString()); + + parser.addArgument("--languageCode") + .help("Language Code of the query (Default: en-US") + .setDefault("en-US"); + + parser.addArgument("texts") + .nargs("+") + .help("Text: 'Where can I find pricing information?'") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + detectIntentWithTexttoSpeech(namespace.get("projectId"), namespace.get("texts"), + namespace.get("sessionId"), namespace.get("languageCode")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } + + +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java new file mode 100644 index 00000000000..49ba5d8a650 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java @@ -0,0 +1,220 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.dialogflow.v2beta1.CreateDocumentRequest; +import com.google.cloud.dialogflow.v2beta1.Document; +import com.google.cloud.dialogflow.v2beta1.Document.KnowledgeType; +import com.google.cloud.dialogflow.v2beta1.DocumentName; +import com.google.cloud.dialogflow.v2beta1.DocumentsClient; +import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; +import com.google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +public class DocumentManagement { + + // [START dialogflow_list_document] + /** + * @param projectId Project/Agent id. + * @param knowledgeBaseId Knowledge Base id. + */ + public static void listDocuments(String projectId, String knowledgeBaseId) throws Exception { + // Instantiates a client + try (DocumentsClient documentsClient = DocumentsClient.create()) { + KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); + for (Document document : documentsClient.listDocuments(knowledgeBaseName).iterateAll()) { + System.out.format(" - Display Name: %s\n", document.getDisplayName()); + System.out.format(" - Knowledge ID: %s\n", document.getName()); + System.out.format(" - MIME Type: %s\n", document.getMimeType()); + System.out.format(" - Knowledge Types:\n"); + for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) { + System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); + } + System.out.format(" - Source: %s \n", document.getContentUri()); + } + } + } + // [END dialogflow_list_document] + + // [START dialogflow_create_document] + /** + * @param projectId Project/Agent id. + * @param knowledgeBaseId Knowledge Base id. + * @param displayName display name of the Document. + * @param mimeType MIME type of the Document. e.g. text/csv, text/html + * @param knowledgeType Knowledge Type of the Document. e.g. FAQ, EXTRACTIVE_QA + * @param contentUri Uri of the Document. e.g. gs://path/mydoc.csv, http://mypage.com/faq.html + */ + public static void createDocument( + String projectId, + String knowledgeBaseId, + String displayName, + String mimeType, + String knowledgeType, + String contentUri) + throws Exception { + // Instantiates a client + try (DocumentsClient documentsClient = DocumentsClient.create()) { + Document document = + Document.newBuilder() + .setDisplayName(displayName) + .setContentUri(contentUri) + .setMimeType(mimeType) + .addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType)) + .build(); + KnowledgeBaseName parent = KnowledgeBaseName.of(projectId, knowledgeBaseId); + CreateDocumentRequest createDocumentRequest = + CreateDocumentRequest.newBuilder() + .setDocument(document) + .setParent(parent.toString()) + .build(); + OperationFuture response = + documentsClient.createDocumentAsync(createDocumentRequest); + System.out.format("Created Document:\n"); + System.out.format(" - Display Name: %s\n", response.get().getDisplayName()); + System.out.format(" - Knowledge ID: %s\n", response.get().getName()); + System.out.format(" - MIME Type: %s\n", response.get().getMimeType()); + System.out.format(" - Knowledge Types:\n"); + for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) { + System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); + } + System.out.format(" - Source: %s \n", document.getContentUri()); + } + } + // [END dialogflow_create_document] + + // [START dialogflow_get_document] + /** + * @param projectId Project/Agent id. + * @param knowledgeBaseId Knowledge Base id. + * @param documentId Document Id. + */ + public static void getDocument(String projectId, String knowledgeBaseId, String documentId) + throws Exception { + // Instantiates a client + try (DocumentsClient documentsClient = DocumentsClient.create()) { + DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId); + Document response = documentsClient.getDocument(documentName); + System.out.format("Got Document: \n"); + System.out.format(" - Display Name: %s\n", response.getDisplayName()); + System.out.format(" - Knowledge ID: %s\n", response.getName()); + System.out.format(" - MIME Type: %s\n", response.getMimeType()); + System.out.format(" - Knowledge Types:\n"); + for (KnowledgeType knowledgeTypeId : response.getKnowledgeTypesList()) { + System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); + } + System.out.format(" - Source: %s \n", response.getContentUri()); + } + } + // [END dialogflow_get_document] + + // [START dialogflow_delete_document] + /** + * @param projectId Project/Agent id. + * @param knowledgeBaseId Knowledge Base id. + * @param documentId Document Id. + */ + public static void deleteDocument(String projectId, String knowledgeBaseId, String documentId) + throws Exception { + // Instantiates a client + try (DocumentsClient documentsClient = DocumentsClient.create()) { + DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId); + documentsClient.deleteDocumentAsync(documentName).getInitialFuture().get(); + System.out.format("The document has been deleted."); + } + } + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("DocumentManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a Document."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DDocumentManagement -Dexec.args='list --projectId PROJECT_ID " + + "--knowledgeBaseId KNOWLEDGE_BASE_ID'"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + listParser.addArgument("--knowledgeBaseId") + .help("The id of the Knowledge Base to list the Documents").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DDocumentManagement -Dexec.args='create --projectId PROJECT_ID " + + "--knowledgeBaseId KNOWLEDGE_BASE_ID --displayName DISPLAY_NAME " + + "--mimeType text/html --knowledgeType FAQ " + + "--contentUri https://cloud.google.com/storage/docs/faq'"); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--knowledgeBaseId") + .help("The ID of the Knowledge Base to list the Documents").required(true); + createParser.addArgument("--displayName") + .help("The display name of the Document").required(true); + createParser.addArgument("--mimeType") + .help("The mime-type of the Document, e.g. text/csv, text/html, text/plain, text/pdf etc.") + .required(true); + createParser.addArgument("--knowledgeType") + .help("The knowledge-type of the Document, e.g. FAQ, EXTRACTIVE_QA.").required(true); + createParser.addArgument("--contentUri") + .help("The uri of the Document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html") + .required(true); + + Subparser getParser = subparsers.addParser("get") + .help("mvn exec:java -DDocumentManagement -Dexec.args='get --projectId PROJECT_ID " + + "--knowledgeBaseId KNOWLEDGE_BASE_ID --documentId DOCUMENT_ID'"); + getParser.addArgument("--projectId").help("Project/Agent Id").required(true); + getParser.addArgument("--knowledgeBaseId") + .help("The ID of the Knowledge Base to list the Documents").required(true); + getParser.addArgument("--documentId") + .help("The ID of the Document you want to delete").required(true); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DDocumentManagement -Dexec.args='delete --projectId PROJECT_ID " + + "--knowledgeBaseId KNOWLEDGE_BASE_ID --documentId DOCUMENT_ID'"); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + deleteParser.addArgument("--knowledgeBaseId") + .help("The ID of the Knowledge Base to list the Documents").required(true); + deleteParser.addArgument("--documentId") + .help("The ID of the Document you want to delete").required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listDocuments(namespace.get("projectId"), namespace.get("knowledgeBaseId")); + } else if (namespace.get("command").equals("create")) { + createDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"), + namespace.get("displayName"), namespace.get("mimeType"), namespace.get("knowledgeType"), + namespace.get("contentUri")); + } else if (namespace.get("command").equals("get")) { + getDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"), + namespace.get("documentId")); + } else if (namespace.get("command").equals("delete")) { + deleteDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"), + namespace.get("documentId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java new file mode 100644 index 00000000000..63a48914e73 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java @@ -0,0 +1,179 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.EntityType; +import com.google.cloud.dialogflow.v2.EntityType.Entity; +import com.google.cloud.dialogflow.v2.EntityTypeName; +import com.google.cloud.dialogflow.v2.EntityTypesClient; +import com.google.protobuf.Empty; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + + +/** + * DialogFlow API Entity sample. + */ +public class EntityManagement { + + // [START dialogflow_list_entities] + /** + * List entities + * @param projectId Project/agent id. + * @param entityTypeId The id of the entity_type. + */ + public static void listEntities(String projectId, String entityTypeId) throws Exception { + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) + EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); + + // Performs the get entity type request + EntityType entityType = entityTypesClient.getEntityType(name); + for (Entity entity : entityType.getEntitiesList()) { + System.out.format("Entity value: %s\n", entity.getValue()); + System.out.format("Entity synonyms: %s\n", entity.getSynonymsList().toString()); + } + } + } + // [END dialogflow_list_entities] + + // [START dialogflow_create_entity] + /** + * Create an entity of the given entity type + * @param projectId Project/agent id. + * @param entityTypeId The id of the entity_type. + * @param entityValue The entity value to be added. + * @param synonyms The synonyms that will map to the provided entity value. + */ + public static void createEntity(String projectId, String entityTypeId, String entityValue, + List synonyms) throws Exception { + // Note: synonyms must be exactly [entityValue] if the + // entityTypeId's kind is KIND_LIST + if (synonyms.size() == 0) { + synonyms.add(entityValue); + } + + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the entity type name using the projectID (my-project-id) and entityTypeId (KINDS_LIST) + EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); + + // Build the entity + Entity entity = Entity.newBuilder() + .setValue(entityValue) + .addAllSynonyms(synonyms) + .build(); + + // Performs the create entity type request + Empty response = entityTypesClient.batchCreateEntitiesAsync(name, + Arrays.asList(entity)).get(); + System.out.println("Entity created: " + response); + } + + + } + // [END dialogflow_create_entity] + + // [START dialogflow_delete_entity] + /** + * Delete entity with the given entity type and entity value + * @param projectId Project/agent id. + * @param entityTypeId The id of the entity_type. + * @param entityValue The value of the entity to delete. + */ + public static void deleteEntity(String projectId, String entityTypeId, String entityValue) + throws Exception { + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the entity type name using the projectID (my-project-id) and entityTypeId (KINDS_LIST) + EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); + + // Performs the delete entity type request + entityTypesClient.batchDeleteEntitiesAsync(name, Arrays.asList(entityValue)) + .getInitialFuture().get(); + } + } + // [END dialogflow_delete_entity] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("EntityManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a Entity."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DEntityManagement -Dexec.args='list --projectId PROJECT_ID " + + "--entityTypeId ENTITY_TYPE_ID'"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + listParser.addArgument("--entityTypeId") + .help("The id of the entityType to which to add an entity.").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DEntityManagement -Dexec.args='create ENTITY_VALUE " + + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID " + + "--synonyms basement cellar'"); + createParser.addArgument("entityValue") + .help("The entity value to be added.").required(true); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--entityTypeId") + .help("The id of the entityType to which to add an entity.").required(true); + createParser.addArgument("--synonyms").nargs("+") + .help("The synonyms that will map to the provided entity value"); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DEntityManagement -Dexec.args='delete ENTITY_VALUE " + + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID'"); + deleteParser.addArgument("entityValue") + .help("The entity value to be added.").required(true); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + deleteParser.addArgument("--entityTypeId") + .help("The id of the entityType to delete.").required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listEntities(namespace.get("projectId"), namespace.get("entityTypeId")); + } else if (namespace.get("command").equals("create")) { + ArrayList synonyms = new ArrayList<>(); + if (namespace.get("synonyms") == null) { + synonyms = namespace.get("synonyms"); + } + createEntity(namespace.get("projectId"), namespace.get("entityTypeId"), + namespace.get("entityValue"), synonyms); + } else if (namespace.get("command").equals("delete")) { + deleteEntity(namespace.get("projectId"), namespace.get("entityTypeId"), + namespace.get("entityValue")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java new file mode 100644 index 00000000000..3eb4466e534 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java @@ -0,0 +1,175 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.EntityType; +import com.google.cloud.dialogflow.v2.EntityType.Kind; +import com.google.cloud.dialogflow.v2.EntityTypeName; +import com.google.cloud.dialogflow.v2.EntityTypesClient; +import com.google.cloud.dialogflow.v2.ProjectAgentName; + +import java.util.ArrayList; +import java.util.List; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + + +/** + * DialogFlow API EntityType sample. + */ +public class EntityTypeManagement { + + // [START dialogflow_list_entity_types] + /** + * List entity types + * @param projectId Project/agent id. + */ + public static void listEntityTypes(String projectId) throws Exception { + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the project agent name using the projectID (my-project-id) + ProjectAgentName parent = ProjectAgentName.of(projectId); + + // Performs the list entity types request + for (EntityType entityType : entityTypesClient.listEntityTypes(parent).iterateAll()) { + System.out.format("Entity type name %s\n", entityType.getName()); + System.out.format("Entity type display name: %s\n", entityType.getDisplayName()); + System.out.format("Number of entities: %d\n", entityType.getEntitiesCount()); + } + } + } + // [END dialogflow_list_entity_types] + + // [START dialogflow_create_entity_type] + /** + * Create an entity type with the given display name + * @param displayName The display name of the entity. + * @param projectId Project/agent id. + * @param kind The kind of entity. KIND_MAP (default) or KIND_LIST. + */ + public static void createEntityType(String displayName, String projectId, String kind) + throws Exception { + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the project agent name using the projectID (my-project-id) + ProjectAgentName parent = ProjectAgentName.of(projectId); + + // Entity types serve as a tool for extracting parameter values from natural language queries. + EntityType entityType = EntityType.newBuilder() + .setDisplayName(displayName) + .setKind(Kind.valueOf(kind)) + .build(); + + // Performs the create entity type request + EntityType response = entityTypesClient.createEntityType(parent, entityType); + System.out.println("Entity type created: " + response); + } + } + // [END dialogflow_create_entity_type] + + // [START dialogflow_delete_entity_type] + /** + * Delete entity type with the given entity type name + * @param entityTypeId The id of the entity_type. + * @param projectId Project/agent id. + */ + public static void deleteEntityType(String entityTypeId, String projectId) throws Exception { + // Instantiates a client + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) + EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); + + // Performs the delete entity type request + entityTypesClient.deleteEntityType(name); + } + } + // [END dialogflow_delete_entity_type] + + /** + * Helper method for testing to get entityTypeId from displayName. + */ + public static List getEntityTypeIds(String displayName, String projectId) + throws Exception { + List entityTypesIds = new ArrayList<>(); + + try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { + ProjectAgentName parent = ProjectAgentName.of(projectId); + // Performs the list entity types request + for (EntityType entityType : entityTypesClient.listEntityTypes(parent).iterateAll()) { + if (entityType.getDisplayName().equals(displayName)) { + String[] splitName = entityType.getName().split("/"); + entityTypesIds.add(splitName[splitName.length - 1]); + } + } + } + return entityTypesIds; + } + + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("EntityTypeManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a Entity Type."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DEntityTypeManagement -Dexec.args='list --projectId PROJECT_ID'"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DEntityTypeManagement -Dexec.args='create DISPLAY_NAME " + + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID " + + "--synonyms basement cellar'"); + createParser.addArgument("displayName") + .help("The display name of the entity.").required(true); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--kind") + .help("The kind of entity. KIND_MAP (default) or KIND_LIST.").setDefault("KIND_MAP"); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DEntityTypeManagement -Dexec.args='delete ENTITY_TYPE_ID " + + "--projectId PROJECT_ID'"); + deleteParser.addArgument("entityTypeId") + .help("The id of the entityType to delete.").required(true); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listEntityTypes(namespace.get("projectId")); + } else if (namespace.get("command").equals("create")) { + createEntityType(namespace.get("displayName"), namespace.get("projectId"), + namespace.get("kind")); + } else if (namespace.get("command").equals("delete")) { + deleteEntityType(namespace.get("entityTypeId"), namespace.get("projectId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java new file mode 100644 index 00000000000..c2147cbaf52 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java @@ -0,0 +1,220 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.Context; +import com.google.cloud.dialogflow.v2.Intent; +import com.google.cloud.dialogflow.v2.Intent.Message; +import com.google.cloud.dialogflow.v2.Intent.Message.Text; +import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase; +import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part; +import com.google.cloud.dialogflow.v2.IntentName; +import com.google.cloud.dialogflow.v2.IntentsClient; +import com.google.cloud.dialogflow.v2.ProjectAgentName; + +import java.util.ArrayList; +import java.util.List; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + + +/** + * DialogFlow API Intent sample. + */ +public class IntentManagement { + + // [START dialogflow_list_intents] + /** + * List intents + * @param projectId Project/Agent Id. + */ + public static void listIntents(String projectId) throws Exception { + // Instantiates a client + try (IntentsClient intentsClient = IntentsClient.create()) { + // Set the project agent name using the projectID (my-project-id) + ProjectAgentName parent = ProjectAgentName.of(projectId); + + // Performs the list intents request + for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { + System.out.println("===================="); + System.out.format("Intent name: '%s'\n", intent.getName()); + System.out.format("Intent display name: '%s'\n", intent.getDisplayName()); + System.out.format("Action: '%s'\n", intent.getAction()); + System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName()); + System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName()); + + System.out.format("Input contexts:\n"); + for (String inputContextName : intent.getInputContextNamesList()) { + System.out.format("\tName: %s\n", inputContextName); + } + + System.out.format("Output contexts:\n"); + for (Context outputContext : intent.getOutputContextsList()) { + System.out.format("\tName: %s\n", outputContext.getName()); + } + } + } + } + // [END dialogflow_list_intents] + + // [START dialogflow_create_intent] + /** + * Create an intent of the given intent type + * @param displayName The display name of the intent. + * @param projectId Project/Agent Id. + * @param trainingPhrasesParts Training phrases. + * @param messageTexts Message texts for the agent's response when the intent is detected. + */ + public static void createIntent(String displayName, String projectId, + List trainingPhrasesParts, List messageTexts) + throws Exception { + // Instantiates a client + try (IntentsClient intentsClient = IntentsClient.create()) { + // Set the project agent name using the projectID (my-project-id) + ProjectAgentName parent = ProjectAgentName.of(projectId); + + // Build the trainingPhrases from the trainingPhrasesParts + List trainingPhrases = new ArrayList<>(); + for (String trainingPhrase : trainingPhrasesParts) { + trainingPhrases.add( + TrainingPhrase.newBuilder().addParts( + Part.newBuilder().setText(trainingPhrase).build()) + .build()); + } + + // Build the message texts for the agent's response + Message message = Message.newBuilder() + .setText( + Text.newBuilder() + .addAllText(messageTexts).build() + ).build(); + + // Build the intent + Intent intent = Intent.newBuilder() + .setDisplayName(displayName) + .addMessages(message) + .addAllTrainingPhrases(trainingPhrases) + .build(); + + // Performs the create intent request + Intent response = intentsClient.createIntent(parent, intent); + System.out.format("Intent created: %s\n", response); + } + } + // [END dialogflow_create_intent] + + // [START dialogflow_delete_intent] + /** + * Delete intent with the given intent type and intent value + * @param intentId The id of the intent. + * @param projectId Project/Agent Id. + */ + public static void deleteIntent(String intentId, String projectId) throws Exception { + // Instantiates a client + try (IntentsClient intentsClient = IntentsClient.create()) { + IntentName name = IntentName.of(projectId, intentId); + // Performs the delete intent request + intentsClient.deleteIntent(name); + } + } + // [END dialogflow_delete_intent] + + /** + * Helper method for testing to get intentIds from displayName. + */ + public static List getIntentIds(String displayName, String projectId) throws Exception { + List intentIds = new ArrayList<>(); + + // Instantiates a client + try (IntentsClient intentsClient = IntentsClient.create()) { + ProjectAgentName parent = ProjectAgentName.of(projectId); + for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { + if (intent.getDisplayName().equals(displayName)) { + String[] splitName = intent.getName().split("/"); + intentIds.add(splitName[splitName.length - 1]); + } + } + } + + return intentIds; + } + + public static void main(String[] args) throws Exception { + + + ArgumentParser parser = + ArgumentParsers.newFor("IntentManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a Intent."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DIntentManagement -Dexec.args='list --projectId PROJECT_ID'"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DIntentManagement -Dexec.args='create DISPLAY_NAME " + + "--projectId PROJECT_ID --trainingPhrasesParts \"cancel\" \"cancellation\" " + + "--messageTexts \"Are you sure you want to cancel?\" \"Cancelled.\"'"); + createParser.addArgument("displayName") + .help("The display name of the intent.").required(true); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--trainingPhrasesParts") + .help("Training phrases.").nargs("+"); + createParser.addArgument("--messageTexts").nargs("+") + .help("Message texts for the agent's response when the intent is detected."); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DIntentManagement -Dexec.args='delete INTENT_ID " + + "--projectId PROJECT_ID'"); + deleteParser.addArgument("intentId") + .help("The ID of the intent.").required(true); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listIntents(namespace.get("projectId")); + } else if (namespace.get("command").equals("create")) { + ArrayList trainingPhrasesParts = new ArrayList<>(); + ArrayList messageTexts = new ArrayList<>(); + if (namespace.get("trainingPhrasesParts") != null) { + trainingPhrasesParts = namespace.get("trainingPhrasesParts"); + } + if (namespace.get("messageTexts") != null) { + messageTexts = namespace.get("messageTexts"); + } + + createIntent(namespace.get("displayName"), namespace.get("projectId"), trainingPhrasesParts, + messageTexts); + } else if (namespace.get("command").equals("delete")) { + deleteIntent(namespace.get("intentId"), namespace.get("projectId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java new file mode 100644 index 00000000000..d160e50c789 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import com.google.cloud.dialogflow.v2beta1.KnowledgeBase; +import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; +import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesClient; +import com.google.cloud.dialogflow.v2beta1.ProjectName; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +public class KnowledgeBaseManagement { + + // [START dialogflow_list_knowledge_base] + /** + * List Knowledge bases + * + * @param projectId Project/agent id. + */ + public static void listKnowledgeBases(String projectId) throws Exception { + // Instantiates a client + try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { + // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) + ProjectName projectName = ProjectName.of(projectId); + for (KnowledgeBase knowledgeBase : + knowledgeBasesClient.listKnowledgeBases(projectName).iterateAll()) { + System.out.format(" - Display Name: %s\n", knowledgeBase.getDisplayName()); + System.out.format(" - Knowledge ID: %s\n", knowledgeBase.getName()); + } + } + } + // [END dialogflow_list_knowledge_base] + + // [START dialogflow_create_knowledge_base] + /** + * Create a Knowledge base + * + * @param projectId Project/agent id. + * @param displayName Name of the knowledge base. + */ + public static void createKnowledgeBase(String projectId, String displayName) throws Exception { + // Instantiates a client + try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { + + KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().setDisplayName(displayName).build(); + ProjectName projectName = ProjectName.of(projectId); + KnowledgeBase response = knowledgeBasesClient.createKnowledgeBase(projectName, knowledgeBase); + System.out.format("Knowledgebase created:\n"); + System.out.format("Display Name: %s \n", response.getDisplayName()); + System.out.format("Knowledge ID: %s \n", response.getName()); + } + } + // [END dialogflow_create_knowledge_base] + + // [START dialogflow_get_knowledge_base] + + /** + * @param knowledgeBaseId Knowledge base id. + * @param projectId Project/agent id. + */ + public static void getKnowledgeBase(String projectId, String knowledgeBaseId) throws Exception { + + // Instantiates a client + try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { + KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); + KnowledgeBase response = knowledgeBasesClient.getKnowledgeBase(knowledgeBaseName); + System.out.format("Got Knowledge Base:\n"); + System.out.format(" - Display Name: %s\n", response.getDisplayName()); + System.out.format(" - Knowledge ID: %s\n", response.getName()); + } + } + // [END dialogflow_get_knowledge_base] + // [START dialogflow_delete_knowledge_base] + + /** + * @param knowledgeBaseId Knowledge base id. + * @param projectId Project/agent id. + */ + public static void deleteKnowledgeBase(String projectId, String knowledgeBaseId) + throws Exception { + // Instantiates a client + try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { + KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); + knowledgeBasesClient.deleteKnowledgeBase(knowledgeBaseName); + System.out.format("KnowledgeBase has been deleted.\n"); + } + } + // [END dialogflow_delete_knowledge_base] + + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("KnowledgeBaseManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a Knowledge Base."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DKnowledgeManagement -Dexec.args='list --projectId PROJECT_ID'"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DKnowledgeManagement -Dexec.args='create DISPLAY_NAME " + + "--projectId PROJECT_ID'"); + createParser.addArgument("displayName") + .help("The display name of the Document").required(true); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser getParser = subparsers.addParser("get") + .help("mvn exec:java -DKnowledgeManagement -Dexec.args='get KNOWLEDGE_BASE_ID " + + "--projectId PROJECT_ID'"); + getParser.addArgument("knowledgeBaseId") + .help("The ID of the Knowledge Base to list the Documents").required(true); + getParser.addArgument("--projectId").help("Project/Agent Id").required(true); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DKnowledgeManagement -Dexec.args='delete KNOWLEDGE_BASE_ID " + + "--projectId PROJECT_ID'"); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + deleteParser.addArgument("--knowledgeBaseId") + .help("The ID of the Knowledge Base to list the Documents").required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listKnowledgeBases(namespace.get("projectId")); + } else if (namespace.get("command").equals("create")) { + createKnowledgeBase(namespace.get("projectId"), namespace.get("displayName")); + } else if (namespace.get("command").equals("get")) { + getKnowledgeBase(namespace.get("projectId"), namespace.get("knowledgeBaseId")); + } else if (namespace.get("command").equals("delete")) { + deleteKnowledgeBase(namespace.get("projectId"), namespace.get("knowledgeBaseId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java new file mode 100644 index 00000000000..da52376e326 --- /dev/null +++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java @@ -0,0 +1,194 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +// Imports the Google Cloud client library +import com.google.cloud.dialogflow.v2.EntityType.Entity; +import com.google.cloud.dialogflow.v2.SessionEntityType; +import com.google.cloud.dialogflow.v2.SessionEntityType.EntityOverrideMode; +import com.google.cloud.dialogflow.v2.SessionEntityTypeName; +import com.google.cloud.dialogflow.v2.SessionEntityTypesClient; +import com.google.cloud.dialogflow.v2.SessionName; + +import java.util.ArrayList; +import java.util.List; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * DialogFlow API SessionEntityType sample. + */ +public class SessionEntityTypeManagement { + + // [START dialogflow_list_session_entity_types] + /** + * List session entity types + * @param projectId Project/Agent Id. + * @param sessionId Identifier of the DetectIntent session. + */ + public static void listSessionEntityTypes(String projectId, String sessionId) throws Exception { + // Instantiates a client + try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { + // Set the session name using the sessionId (UUID) and projectID (my-project-id) + SessionName session = SessionName.of(projectId, sessionId); + + System.out.format("SessionEntityTypes for session %s:\n", session.toString()); + // Performs the list session entity types request + for (SessionEntityType sessionEntityType : + sessionEntityTypesClient.listSessionEntityTypes(session).iterateAll()) { + System.out.format("\tSessionEntityType name: %s\n", sessionEntityType.getName()); + System.out.format("\tNumber of entities: %d\n", sessionEntityType.getEntitiesCount()); + } + } + } + // [END dialogflow_list_session_entity_types] + + // [START dialogflow_create_session_entity_type] + /** + * Create an entity type with the given display name + * @param projectId Project/Agent Id. + * @param sessionId Identifier of the DetectIntent session. + * @param entityValues The entity values of the session entity type. + * @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session. + * @param entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE (default) or + * ENTITY_OVERRIDE_MODE_SUPPLEMENT + */ + public static void createSessionEntityType(String projectId, String sessionId, + List entityValues, String entityTypeDisplayName,int entityOverrideMode) + throws Exception { + // Instantiates a client + try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { + // Set the session name using the sessionId (UUID) and projectID (my-project-id) + SessionName session = SessionName.of(projectId, sessionId); + SessionEntityTypeName name = SessionEntityTypeName.of(projectId, sessionId, + entityTypeDisplayName); + + List entities = new ArrayList<>(); + for (String entityValue : entityValues) { + entities.add(Entity.newBuilder() + .setValue(entityValue) + .addSynonyms(entityValue) + .build()); + } + + // Extends or replaces a developer entity type at the user session level (we refer to the + // entity types defined at the agent level as "developer entity types"). + SessionEntityType sessionEntityType = SessionEntityType.newBuilder() + .setName(name.toString()) + .addAllEntities(entities) + .setEntityOverrideMode(EntityOverrideMode.forNumber(entityOverrideMode)) + .build(); + + // Performs the create session entity type request + SessionEntityType response = sessionEntityTypesClient.createSessionEntityType(session, + sessionEntityType); + + System.out.format("SessionEntityType created: %s\n", response); + } + } + // [END dialogflow_create_session_entity_type] + + // [START dialogflow_delete_session_entity_type] + /** + * Delete entity type with the given entity type name + * @param projectId Project/Agent Id. + * @param sessionId Identifier of the DetectIntent session. + * @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session. + */ + public static void deleteSessionEntityType(String projectId, String sessionId, + String entityTypeDisplayName) throws Exception { + // Instantiates a client + try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { + SessionEntityTypeName name = SessionEntityTypeName.of(projectId, sessionId, + entityTypeDisplayName); + + // Performs the delete session entity type request + sessionEntityTypesClient.deleteSessionEntityType(name); + } + } + // [END dialogflow_delete_session_entity_type] + + public static void main(String[] args) throws Exception { + ArgumentParser parser = + ArgumentParsers.newFor("SessionEntityTypeManagement") + .build() + .defaultHelp(true) + .description("Create / List / Delete a SessionEntityType."); + + Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands"); + + Subparser listParser = subparsers.addParser("list") + .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='list " + + "--projectId PROJECT_ID --sessionId SESSION_ID '"); + listParser.addArgument("--projectId").help("Project/Agent Id").required(true); + listParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + + Subparser createParser = subparsers.addParser("create") + .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='create " + + "--projectId PROJECT_ID --sessionId SESSION_ID " + + "--entityTypeDisplayName ENTITY_TYPE_DISPLAY_NAME " + + "--entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE " + + "--entityValues C D E F'"); + createParser.addArgument("--projectId").help("Project/Agent Id").required(true); + createParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + createParser.addArgument("--entityTypeDisplayName") + .help("The DISPLAY NAME of the entity type to be overridden in the session.t") + .required(true); + createParser.addArgument("--entityOverrideMode") + .help("ENTITY_OVERRIDE_MODE_OVERRIDE (default) or ENTITY_OVERRIDE_MODE_SUPPLEMENT") + .setDefault(1); + createParser.addArgument("--entityValues").nargs("+") + .help("The entity values of the session entity type."); + + Subparser deleteParser = subparsers.addParser("delete") + .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='delete " + + "--sessionId SESSION_ID --projectId PROJECT_ID --contextId CONTEXT_ID'"); + deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true); + deleteParser.addArgument("--sessionId") + .help("Identifier of the DetectIntent session").required(true); + deleteParser.addArgument("--entityTypeDisplayName") + .help("The DISPLAY NAME of the entity type to be overridden in the session.t") + .required(true); + + try { + Namespace namespace = parser.parseArgs(args); + + if (namespace.get("command").equals("list")) { + listSessionEntityTypes(namespace.get("projectId"), namespace.get("sessionId")); + } else if (namespace.get("command").equals("create")) { + ArrayList entityValues = new ArrayList<>(); + if (namespace.get("entityValues") != null) { + entityValues = namespace.get("entityValues"); + } + createSessionEntityType(namespace.get("projectId"), namespace.get("sessionId"), + entityValues, namespace.get("entityTypeDisplayName"), + namespace.get("entityOverrideMode")); + } else if (namespace.get("command").equals("delete")) { + deleteSessionEntityType(namespace.get("projectId"), namespace.get("sessionId"), + namespace.get("entityTypeDisplayName")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java new file mode 100644 index 00000000000..fcd16806692 --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link ContextManagement}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ContextManagementIT { + + private ByteArrayOutputStream bout; + private PrintStream out; + + private DetectIntentTexts detectIntentTexts; + private ContextManagement contextManagement; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String CONTEXT_ID = "fake_context_for_testing"; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentTexts = new DetectIntentTexts(); + contextManagement = new ContextManagement(); + PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testCreateDeleteContext() throws Exception { + // Calling detect intent to create a session + detectIntentTexts.detectIntentTexts(PROJECT_ID, Arrays.asList("hi"), SESSION_ID, "en-US"); + + // Create the context + contextManagement.createContext(CONTEXT_ID, SESSION_ID, PROJECT_ID, 1); + contextManagement.listContexts(SESSION_ID, PROJECT_ID); + + String got = bout.toString(); + assertThat(got).contains(CONTEXT_ID); + + // Delete the context + bout.reset(); + contextManagement.deleteContext(CONTEXT_ID, SESSION_ID, PROJECT_ID); + contextManagement.listContexts(SESSION_ID, PROJECT_ID); + + got = bout.toString(); + assertThat(got).doesNotContain(CONTEXT_ID); + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java new file mode 100644 index 00000000000..23ab85991d4 --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java @@ -0,0 +1,133 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.junit.runners.MethodSorters; + + +/** + * Integration (system) tests for {@link EntityManagement} and {@link EntityTypeManagement}. + */ +@RunWith(JUnit4.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreateDeleteEntityIT { + private static String ENTITY_TYPE_DISPLAY_NAME = "fake_entity_type_for_testing"; + private static String ENTITY_VALUE_1 = "fake_entity_for_testing_1"; + private static String ENTITY_VALUE_2 = "fake_entity_for_testing_2"; + private static List SYNONYMS = Arrays.asList("fake_synonym_for_testing_1", + "fake_synonym_for_testing_2"); + + private ByteArrayOutputStream bout; + private PrintStream out; + + private EntityManagement entityManagement; + private EntityTypeManagement entityTypeManagement; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + entityManagement = new EntityManagement(); + entityTypeManagement = new EntityTypeManagement(); + } + + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testCreateEntityType() throws Exception { + List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + assertThat(entityTypeIds.size()).isEqualTo(0); + + entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP"); + + String got = bout.toString(); + assertThat(got).contains(String.format("display_name: \"%s\"", ENTITY_TYPE_DISPLAY_NAME)); + + entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + assertThat(entityTypeIds.size()).isEqualTo(1); + } + + @Test + public void testCreateEntityWithCreatedEntityType() throws Exception { + List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1, + Arrays.asList("")); + entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2, SYNONYMS); + + entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0)); + + String got = bout.toString(); + assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_1)); + assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_2)); + + for (String synonym : SYNONYMS) { + assertThat(got).contains(synonym); + } + } + + @Test + public void testDeleteEntity() throws Exception { + List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1); + entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2); + + entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0)); + + String got = bout.toString(); + assertThat(got).isEqualTo(""); + } + + @Test + public void testDeleteEntityType() throws Exception { + List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + for (String entityTypeId : entityTypeIds) { + entityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID); + } + + entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID); + assertThat(entityTypeIds.size()).isEqualTo(0); + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java new file mode 100644 index 00000000000..bc458d6e9ae --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java @@ -0,0 +1,72 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link DetectIntentAudio}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentAudioIT { + + private ByteArrayOutputStream bout; + private PrintStream out; + private DetectIntentAudio detectIntentAudio; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static List AUDIOS = Arrays.asList( + "resources/book_a_room.wav", + "resources/mountain_view.wav", + "resources/today.wav"); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentAudio = new DetectIntentAudio(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDetectIntent() throws Exception { + for (String audioFilePath : AUDIOS) { + detectIntentAudio.detectIntentAudio(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE); + } + + String got = bout.toString(); + assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'"); + } + +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java new file mode 100644 index 00000000000..88f3c7d613d --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java @@ -0,0 +1,67 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link DetectIntentStream}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentStreamIT { + + private ByteArrayOutputStream bout; + private PrintStream out; + private static String audioFilePath = "resources/book_a_room.wav"; + private DetectIntentStream detectIntentStream; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentStream = new DetectIntentStream(); + } + + + @After + public void tearDown() { + System.setOut(null); + } + + + @Test + public void testStreamingDetectIntentCallable() throws Throwable { + detectIntentStream.detectIntentStream(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE); + + String got = bout.toString(); + assertThat(got).contains("Intermediate transcript: 'book'"); + assertThat(got).contains("Detected Intent: room.reservation"); + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java new file mode 100644 index 00000000000..88213ae275b --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java @@ -0,0 +1,68 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link DetectIntentTexts}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentTextsIT { + + private ByteArrayOutputStream bout; + private DetectIntentTexts detectIntentTexts; + private PrintStream out; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "book a meeting room", "Mountain View", + "tomorrow", "10 am", "2 hours", "10 people", "A", "yes"); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentTexts = new DetectIntentTexts(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDetectIntent() throws Exception { + detectIntentTexts.detectIntentTexts(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE); + + String got = bout.toString(); + assertThat(got).contains("Fulfillment Text: 'All set!'"); + } + +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java new file mode 100644 index 00000000000..399f4342a9c --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java @@ -0,0 +1,69 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentWithModelSelection}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentWithModelSelectionIT { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static List AUDIOS = + Arrays.asList( + "resources/book_a_room.wav", "resources/mountain_view.wav", "resources/today.wav"); + private ByteArrayOutputStream bout; + private PrintStream out; + private DetectIntentWithModelSelection detectIntentWithModelSelection; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentWithModelSelection = new DetectIntentWithModelSelection(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDetectIntent() throws Exception { + for (String audioFilePath : AUDIOS) { + detectIntentWithModelSelection.detectIntentWithModelSelection( + PROJECT_ID, SESSION_ID, audioFilePath, LANGUAGE_CODE); + } + + String got = bout.toString(); + assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'"); + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java new file mode 100644 index 00000000000..c442fcf74bb --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java @@ -0,0 +1,69 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link DetectIntentWithSentimentAnalysis}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentWithSentimentAnalysisIT { + + private ByteArrayOutputStream bout; + private DetectIntentWithSentimentAnalysis detectIntentWithSentimentAnalysis; + private PrintStream out; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "book a meeting room", "Mountain View", + "tomorrow", "10 am", "2 hours", "10 people", "A", "yes"); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentWithSentimentAnalysis = new DetectIntentWithSentimentAnalysis(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDetectIntent() throws Exception { + detectIntentWithSentimentAnalysis.detectIntentSentimentAnalysis(PROJECT_ID, TEXTS, SESSION_ID, + LANGUAGE_CODE); + + String got = bout.toString(); + assertThat(got).contains("Sentiment Score:"); + } + +} \ No newline at end of file diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java new file mode 100644 index 00000000000..d28e2f21a64 --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java @@ -0,0 +1,75 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentWithTextToSpeechResponse}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentWithTextToSpeechResponseIT { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = + Arrays.asList( + "hello", + "book a meeting room", + "Mountain View", + "tomorrow", + "10 am", + "2 hours", + "10 people", + "A", + "yes"); + private ByteArrayOutputStream bout; + private DetectIntentWithTextToSpeechResponse detectIntentWithTextToSpeechResponse; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentWithTextToSpeechResponse = new DetectIntentWithTextToSpeechResponse(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDetectIntent() throws Exception { + detectIntentWithTextToSpeechResponse.detectIntentWithTexttoSpeech( + PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE); + + String got = bout.toString(); + assertThat(got).contains("Fulfillment Text: 'All set!'"); + } +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java new file mode 100644 index 00000000000..251984a00c8 --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java @@ -0,0 +1,99 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link IntentManagement}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class IntentManagementIT { + private static String INTENT_DISPLAY_NAME = "fake_display_name_for_testing"; + private static List MESSAGE_TEXTS = Arrays.asList( + "fake_message_text_for_testing_1", + "fake_message_text_for_testing_2"); + private static List TRAINING_PHRASE_PARTS = Arrays.asList( + "fake_training_phrase_part_1", + "fake_training_phrase_part_2"); + private ByteArrayOutputStream bout; + private PrintStream out; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private IntentManagement intentManagement; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + intentManagement = new IntentManagement(); + } + + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testCreateIntent() throws Exception { + // Create the intent + intentManagement.createIntent(INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, + MESSAGE_TEXTS); + + List intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); + + assertThat(intentIds.size()).isEqualTo(1); + + intentManagement.listIntents(PROJECT_ID); + + String got = bout.toString(); + assertThat(got).contains(INTENT_DISPLAY_NAME); + for (String messageText : MESSAGE_TEXTS) { + assertThat(got).contains(messageText); + } + + // Delete the intent + bout.reset(); + intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); + + for (String intentId : intentIds) { + intentManagement.deleteIntent(intentId, PROJECT_ID); + } + + intentManagement.listIntents(PROJECT_ID); + + got = bout.toString(); + assertThat(got).doesNotContain(INTENT_DISPLAY_NAME); + + intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); + + assertThat(intentIds.size()).isEqualTo(0); + } + +} diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java new file mode 100644 index 00000000000..18609814666 --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java @@ -0,0 +1,134 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {DetectIntentKnowledge, KnowledgeManagement, DocumentManagement}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class KnowledgeBaseManagementIT { + + private ByteArrayOutputStream bout; + private DetectIntentKnowledge detectIntentKnowledge; + private KnowledgeBaseManagement knowledgeBaseManagement; + private DocumentManagement documentManagement; + private PrintStream out; + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String SESSION_ID = "fake_session_for_testing"; + private static String LANGUAGE_CODE = "en-US"; + private static String KNOWLEDGE_BASE_NAME = "fake_knowledge_base_name"; + private static String DOCUMENT_BASE_NAME = "fake_document_name"; + private String knowledgeBaseId = ""; + private String documentId = ""; + + private static List TEXTS = Arrays.asList("Where is my data stored?"); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + detectIntentKnowledge = new DetectIntentKnowledge(); + knowledgeBaseManagement = new KnowledgeBaseManagement(); + documentManagement = new DocumentManagement(); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testKnowledgeBase() throws Exception { + // Check the knowledge base does not yet exist + knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID); + String got = bout.toString(); + assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME); + + // Create a Knowledge Base + knowledgeBaseManagement.createKnowledgeBase(PROJECT_ID,KNOWLEDGE_BASE_NAME); + got = bout.toString(); + assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); + + // List Knowledge Bases + knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID); + got = bout.toString(); + assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); + knowledgeBaseId = got.split("/knowledgeBases/")[2].trim(); + + // Get knowledge base + knowledgeBaseManagement.getKnowledgeBase(PROJECT_ID,knowledgeBaseId); + got = bout.toString(); + assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); + + // Create a Document + documentManagement.createDocument(PROJECT_ID,knowledgeBaseId,DOCUMENT_BASE_NAME,"text/html","FAQ","https://cloud.google.com/storage/docs/faq"); + got = bout.toString(); + assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); + + // List the Document + documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId); + got = bout.toString(); + assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); + documentId = got.split("documents/")[1].split("- MIME Type")[0].trim(); + + // Get the Document + documentManagement.getDocument(PROJECT_ID,knowledgeBaseId,documentId); + got = bout.toString(); + assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); + + // Detect Intent with Knowledge Base + detectIntentKnowledge.detectIntentKnowledge(PROJECT_ID, knowledgeBaseId,SESSION_ID, + LANGUAGE_CODE, TEXTS); + got = bout.toString(); + assertThat(got).contains("Knowledge results"); + + // Delete the Document + bout.reset(); + documentManagement.deleteDocument(PROJECT_ID,knowledgeBaseId,documentId); + got = bout.toString(); + assertThat(got).contains("The document has been deleted."); + + // List the Document + documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId); + got = bout.toString(); + assertThat(got).doesNotContain("Display Name: " + DOCUMENT_BASE_NAME); + + // Delete the Knowledge Base + knowledgeBaseManagement.deleteKnowledgeBase(PROJECT_ID,knowledgeBaseId); + + // List Knowledge Bases + knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID); + got = bout.toString(); + assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME); + + } + +} \ No newline at end of file diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java new file mode 100644 index 00000000000..a4f9edf480f --- /dev/null +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java @@ -0,0 +1,101 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.dialogflow; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Integration (system) tests for {@link SessionEntityTypeManagement}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class SessionEntityTypeManagementIT { + private static String SESSION_ID = "fake_session_for_testing"; + private static String ENTITY_TYPE_DISPLAY_NAME = "fake_display_name_for_testing"; + private static List ENTITY_VALUES = Arrays.asList("fake_entity_value_1", + "fake_entity_value_2"); + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private ByteArrayOutputStream bout; + private PrintStream out; + + private SessionEntityTypeManagement sessionEntityTypeManagement; + private EntityTypeManagement entityTypeManagement; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + sessionEntityTypeManagement = new SessionEntityTypeManagement(); + entityTypeManagement = new EntityTypeManagement(); + } + + + @After + public void tearDown() { + System.setOut(null); + } + + + @Test + public void testCreateDeleteSessionEntityType() throws Exception { + // Create session entity type + entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP"); + + sessionEntityTypeManagement.createSessionEntityType(PROJECT_ID, SESSION_ID, ENTITY_VALUES, + ENTITY_TYPE_DISPLAY_NAME, 1); + + sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID); + + String got = bout.toString(); + assertThat(got).contains(SESSION_ID); + assertThat(got).contains(ENTITY_TYPE_DISPLAY_NAME); + for (String entityValue : ENTITY_VALUES) { + assertThat(got).contains(entityValue); + } + + // Delete session entity type + bout.reset(); + sessionEntityTypeManagement.deleteSessionEntityType(PROJECT_ID, SESSION_ID, + ENTITY_TYPE_DISPLAY_NAME); + + sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID); + + got = bout.toString(); + assertThat(got).doesNotContain(ENTITY_TYPE_DISPLAY_NAME); + for (String entityValue : ENTITY_VALUES) { + assertThat(got).doesNotContain(entityValue); + } + + List entityTypesIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, + PROJECT_ID); + + for (String entityTypeId : entityTypesIds) { + entityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID); + } + } +} diff --git a/pom.xml b/pom.xml index ae0d733a09c..0fd68da195e 100644 --- a/pom.xml +++ b/pom.xml @@ -57,6 +57,8 @@ datastore datastore/cloud-client + dialogflow/cloud-client + dlp errorreporting