Skip to content

Commit

Permalink
samples: Fix DialogFlow tests and update to canonical sample format. (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
dzlier-gcp authored and Shabirmean committed Nov 15, 2022
1 parent 40893da commit c644c5c
Show file tree
Hide file tree
Showing 27 changed files with 771 additions and 1,484 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,41 +17,38 @@
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.common.collect.Lists;
import com.google.protobuf.Value;

import java.util.List;
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.
* @return List of Contexts found.
*/
public static void listContexts(String sessionId, String projectId) throws Exception {
public static List<Context> listContexts(String sessionId, String projectId) throws Exception {
List<Context> contexts = Lists.newArrayList();
// 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());
Expand All @@ -61,20 +58,29 @@ public static void listContexts(String sessionId, String projectId) throws Excep
System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue());
}
}

contexts.add(context);
}
}
return contexts;
}
// [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 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.
* @param projectId Project/Agent Id.
* @return The new Context.
*/
public static void createContext(String contextId, String sessionId, String projectId,
public static Context createContext(
String contextId,
String sessionId,
String projectId,
int lifespanCount) throws Exception {
// Instantiates a client
try (ContextsClient contextsClient = ContextsClient.create()) {
Expand All @@ -97,13 +103,17 @@ public static void createContext(String contextId, String sessionId, String proj
// Performs the create context request
Context response = contextsClient.createContext(session, context);
System.out.format("Context created: %s\n", response);

return 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.
Expand All @@ -119,59 +129,4 @@ public static void deleteContext(String contextId, String sessionId, String proj
}
}
// [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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
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;
Expand All @@ -29,29 +30,29 @@

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 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.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @return QueryResult for the request.
*/
public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId,
public static QueryResult detectIntentAudio(
String projectId,
String audioFilePath,
String sessionId,
String languageCode)
throws Exception {
// Instantiates a client
Expand Down Expand Up @@ -95,40 +96,9 @@ public static void detectIntentAudio(String projectId, String audioFilePath, Str
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);
return queryResult;
}
}
// [END dialogflow_detect_intent_audio]
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,52 +16,50 @@

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 com.google.common.collect.Maps;

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;

import java.util.Map;

/** DialogFlow API Detect Intent sample with querying knowledge connector. */
/**
* 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.
*
* <p>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.
* @param projectId Project/Agent Id.
* @param knowledgeBaseName Knowledge base Id.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @param texts The texts to be processed.
* @return The KnowledgeAnswers found for each text.
*/
public static void detectIntentKnowledge(
public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
String projectId,
String knowledgeBaseId,
String knowledgeBaseName,
String sessionId,
String languageCode,
List<String> texts)
throws Exception {
List<String> texts) throws Exception {
// Instantiates a client
Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
Expand All @@ -74,10 +72,9 @@ public static void detectIntentKnowledge(
// 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())
.addKnowledgeBaseNames(knowledgeBaseName)
.build();

DetectIntentRequest detectIntentRequest =
Expand All @@ -104,48 +101,12 @@ public static void detectIntentKnowledge(
System.out.format(" - Answer: '%s'\n", answer.getAnswer());
System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence());
}

KnowledgeAnswers answers = queryResult.getKnowledgeAnswers();
allKnowledgeAnswers.put(text, answers);
}
}
return allKnowledgeAnswers;
}
// [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);
}
}
}
Loading

0 comments on commit c644c5c

Please sign in to comment.