Skip to content

Commit 9c50376

Browse files
dzlier-gcpchingor13
authored andcommitted
samples: Fix DialogFlow tests and update to canonical sample format. (#1210)
1 parent 08e0cc0 commit 9c50376

27 files changed

+771
-1484
lines changed

dialogflow/snippets/src/main/java/com/example/dialogflow/ContextManagement.java

Lines changed: 25 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -17,41 +17,38 @@
1717
package com.example.dialogflow;
1818

1919
// Imports the Google Cloud client library
20+
2021
import com.google.cloud.dialogflow.v2.Context;
2122
import com.google.cloud.dialogflow.v2.ContextName;
2223
import com.google.cloud.dialogflow.v2.ContextsClient;
2324
import com.google.cloud.dialogflow.v2.SessionName;
25+
import com.google.common.collect.Lists;
2426
import com.google.protobuf.Value;
2527

28+
import java.util.List;
2629
import java.util.Map.Entry;
27-
import net.sourceforge.argparse4j.ArgumentParsers;
28-
import net.sourceforge.argparse4j.inf.ArgumentParser;
29-
import net.sourceforge.argparse4j.inf.ArgumentParserException;
30-
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
31-
import net.sourceforge.argparse4j.inf.Namespace;
32-
import net.sourceforge.argparse4j.inf.Subparser;
33-
import net.sourceforge.argparse4j.inf.Subparsers;
34-
3530

3631
/**
3732
* DialogFlow API Context sample.
3833
*/
3934
public class ContextManagement {
40-
4135
// [START dialogflow_list_contexts]
36+
4237
/**
4338
* Lists contexts
39+
*
4440
* @param sessionId Identifier of the DetectIntent session.
4541
* @param projectId Project/Agent Id.
42+
* @return List of Contexts found.
4643
*/
47-
public static void listContexts(String sessionId, String projectId) throws Exception {
44+
public static List<Context> listContexts(String sessionId, String projectId) throws Exception {
45+
List<Context> contexts = Lists.newArrayList();
4846
// Instantiates a client
4947
try (ContextsClient contextsClient = ContextsClient.create()) {
5048
// Set the session name using the sessionId (UUID) and projectId (my-project-id)
5149
SessionName session = SessionName.of(projectId, sessionId);
5250

5351
// Performs the list contexts request
54-
System.out.format("Contexts for session %s:\n", session.toString());
5552
for (Context context : contextsClient.listContexts(session).iterateAll()) {
5653
System.out.format("Context name: %s\n", context.getName());
5754
System.out.format("Lifespan Count: %d\n", context.getLifespanCount());
@@ -61,20 +58,29 @@ public static void listContexts(String sessionId, String projectId) throws Excep
6158
System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue());
6259
}
6360
}
61+
62+
contexts.add(context);
6463
}
6564
}
65+
return contexts;
6666
}
6767
// [END dialogflow_list_contexts]
6868

6969
// [START dialogflow_create_context]
70+
7071
/**
7172
* Create an entity type with the given display name
72-
* @param contextId The Id of the context.
73-
* @param sessionId Identifier of the DetectIntent session.
73+
*
74+
* @param contextId The Id of the context.
75+
* @param sessionId Identifier of the DetectIntent session.
7476
* @param lifespanCount The lifespan count of the context.
75-
* @param projectId Project/Agent Id.
77+
* @param projectId Project/Agent Id.
78+
* @return The new Context.
7679
*/
77-
public static void createContext(String contextId, String sessionId, String projectId,
80+
public static Context createContext(
81+
String contextId,
82+
String sessionId,
83+
String projectId,
7884
int lifespanCount) throws Exception {
7985
// Instantiates a client
8086
try (ContextsClient contextsClient = ContextsClient.create()) {
@@ -97,13 +103,17 @@ public static void createContext(String contextId, String sessionId, String proj
97103
// Performs the create context request
98104
Context response = contextsClient.createContext(session, context);
99105
System.out.format("Context created: %s\n", response);
106+
107+
return response;
100108
}
101109
}
102110
// [END dialogflow_create_context]
103111

104112
// [START dialogflow_delete_context]
113+
105114
/**
106115
* Delete entity type with the given entity type name
116+
*
107117
* @param contextId The Id of the context.
108118
* @param sessionId Identifier of the DetectIntent session.
109119
* @param projectId Project/Agent Id.
@@ -119,59 +129,4 @@ public static void deleteContext(String contextId, String sessionId, String proj
119129
}
120130
}
121131
// [END dialogflow_delete_context]
122-
123-
public static void main(String[] args) throws Exception {
124-
ArgumentParser parser =
125-
ArgumentParsers.newFor("ContextManagement")
126-
.build()
127-
.defaultHelp(true)
128-
.description("Create / List / Delete a context.");
129-
130-
Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
131-
132-
Subparser listParser = subparsers.addParser("list")
133-
.help("mvn exec:java -DContextManagement -Dexec.args='list --sessionId SESSION_ID "
134-
+ "--projectId PROJECT_ID'");
135-
listParser.addArgument("--sessionId")
136-
.help("Identifier of the DetectIntent session").required(true);
137-
listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
138-
139-
Subparser createParser = subparsers.addParser("create")
140-
.help("mvn exec:java -DContextManagement -Dexec.args='create --sessionId SESSION_ID "
141-
+ "--projectId PROJECT_ID --contextId CONTEXT_ID'");
142-
createParser.addArgument("--sessionId")
143-
.help("Identifier of the DetectIntent session").required(true);
144-
createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
145-
createParser.addArgument("--contextId")
146-
.help("The Id of the context")
147-
.required(true);
148-
createParser.addArgument("--lifespanCount")
149-
.help("The lifespan count of the context (Default: 1)").setDefault(1);
150-
151-
Subparser deleteParser = subparsers.addParser("delete")
152-
.help("mvn exec:java -DContextManagement -Dexec.args='delete --sessionId SESSION_ID "
153-
+ "--projectId PROJECT_ID --contextId CONTEXT_ID'");
154-
deleteParser.addArgument("--sessionId")
155-
.help("Identifier of the DetectIntent session").required(true);
156-
deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
157-
deleteParser.addArgument("--contextId")
158-
.help("The Id of the context")
159-
.required(true);
160-
161-
try {
162-
Namespace namespace = parser.parseArgs(args);
163-
164-
if (namespace.get("command").equals("list")) {
165-
listContexts(namespace.get("sessionId"), namespace.get("projectId"));
166-
} else if (namespace.get("command").equals("create")) {
167-
createContext(namespace.get("contextId"), namespace.get("sessionId"),
168-
namespace.get("projectId"), namespace.get("lifespanCount"));
169-
} else if (namespace.get("command").equals("delete")) {
170-
deleteContext(namespace.get("contextId"), namespace.get("sessionId"),
171-
namespace.get("projectId"));
172-
}
173-
} catch (ArgumentParserException e) {
174-
parser.handleError(e);
175-
}
176-
}
177132
}

dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentAudio.java

Lines changed: 13 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.example.dialogflow;
1818

1919
// Imports the Google Cloud client library
20+
2021
import com.google.cloud.dialogflow.v2.AudioEncoding;
2122
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
2223
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
@@ -29,29 +30,29 @@
2930

3031
import java.nio.file.Files;
3132
import java.nio.file.Paths;
32-
import java.util.UUID;
33-
import net.sourceforge.argparse4j.ArgumentParsers;
34-
import net.sourceforge.argparse4j.inf.ArgumentParser;
35-
import net.sourceforge.argparse4j.inf.ArgumentParserException;
36-
import net.sourceforge.argparse4j.inf.Namespace;
3733

3834

3935
/**
4036
* DialogFlow API Detect Intent sample with audio files.
4137
*/
4238
public class DetectIntentAudio {
43-
4439
// [START dialogflow_detect_intent_audio]
40+
4541
/**
4642
* Returns the result of detect intent with an audio file as input.
4743
*
4844
* Using the same `session_id` between requests allows continuation of the conversation.
49-
* @param projectId Project/Agent Id.
45+
*
46+
* @param projectId Project/Agent Id.
5047
* @param audioFilePath Path to the audio file.
51-
* @param sessionId Identifier of the DetectIntent session.
52-
* @param languageCode Language code of the query.
48+
* @param sessionId Identifier of the DetectIntent session.
49+
* @param languageCode Language code of the query.
50+
* @return QueryResult for the request.
5351
*/
54-
public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId,
52+
public static QueryResult detectIntentAudio(
53+
String projectId,
54+
String audioFilePath,
55+
String sessionId,
5556
String languageCode)
5657
throws Exception {
5758
// Instantiates a client
@@ -95,40 +96,9 @@ public static void detectIntentAudio(String projectId, String audioFilePath, Str
9596
System.out.format("Detected Intent: %s (confidence: %f)\n",
9697
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
9798
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
98-
}
99-
}
100-
// [END dialogflow_detect_intent_audio]
10199

102-
public static void main(String[] args) throws Exception {
103-
ArgumentParser parser =
104-
ArgumentParsers.newFor("DetectIntentAudio")
105-
.build()
106-
.defaultHelp(true)
107-
.description("Returns the result of detect intent with an audio file as input.\n"
108-
+ "mvn exec:java -DDetectIntentAudio -Dexec.args='--projectId PROJECT_ID "
109-
+ "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'");
110-
111-
parser.addArgument("--projectId").help("Project/Agent Id").required(true);
112-
113-
parser.addArgument("--audioFilePath")
114-
.help("Path to the audio file")
115-
.required(true);
116-
117-
parser.addArgument("--sessionId")
118-
.help("Identifier of the DetectIntent session (Default: UUID.)")
119-
.setDefault(UUID.randomUUID().toString());
120-
121-
parser.addArgument("--languageCode")
122-
.help("Language Code of the query (Default: en-US")
123-
.setDefault("en-US");
124-
125-
try {
126-
Namespace namespace = parser.parseArgs(args);
127-
128-
detectIntentAudio(namespace.get("projectId"), namespace.get("audioFilePath"),
129-
namespace.get("sessionId"), namespace.get("languageCode"));
130-
} catch (ArgumentParserException e) {
131-
parser.handleError(e);
100+
return queryResult;
132101
}
133102
}
103+
// [END dialogflow_detect_intent_audio]
134104
}

dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java

Lines changed: 22 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -16,52 +16,50 @@
1616

1717
package com.example.dialogflow;
1818

19-
2019
// Imports the Google Cloud client library
20+
2121
import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest;
2222
import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
2323
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
2424
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
25-
import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName;
2625
import com.google.cloud.dialogflow.v2beta1.QueryInput;
2726
import com.google.cloud.dialogflow.v2beta1.QueryParameters;
2827
import com.google.cloud.dialogflow.v2beta1.QueryResult;
2928
import com.google.cloud.dialogflow.v2beta1.SessionName;
3029
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
3130
import com.google.cloud.dialogflow.v2beta1.TextInput;
3231
import com.google.cloud.dialogflow.v2beta1.TextInput.Builder;
32+
import com.google.common.collect.Maps;
3333

3434
import java.util.List;
35-
import java.util.UUID;
36-
import net.sourceforge.argparse4j.ArgumentParsers;
37-
import net.sourceforge.argparse4j.inf.ArgumentParser;
38-
import net.sourceforge.argparse4j.inf.ArgumentParserException;
39-
import net.sourceforge.argparse4j.inf.Namespace;
40-
35+
import java.util.Map;
4136

42-
/** DialogFlow API Detect Intent sample with querying knowledge connector. */
37+
/**
38+
* DialogFlow API Detect Intent sample with querying knowledge connector.
39+
*/
4340
public class DetectIntentKnowledge {
44-
4541
// [START dialogflow_detect_intent_knowledge]
42+
4643
/**
4744
* Returns the result of detect intent with text as input.
4845
*
4946
* <p>Using the same `session_id` between requests allows continuation of the conversation.
5047
*
51-
* @param projectId Project/Agent Id.
52-
* @param knowledgeBaseId Knowledge base Id.
53-
* @param sessionId Identifier of the DetectIntent session.
54-
* @param languageCode Language code of the query.
55-
* @param texts The texts to be processed.
48+
* @param projectId Project/Agent Id.
49+
* @param knowledgeBaseName Knowledge base Id.
50+
* @param sessionId Identifier of the DetectIntent session.
51+
* @param languageCode Language code of the query.
52+
* @param texts The texts to be processed.
53+
* @return The KnowledgeAnswers found for each text.
5654
*/
57-
public static void detectIntentKnowledge(
55+
public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
5856
String projectId,
59-
String knowledgeBaseId,
57+
String knowledgeBaseName,
6058
String sessionId,
6159
String languageCode,
62-
List<String> texts)
63-
throws Exception {
60+
List<String> texts) throws Exception {
6461
// Instantiates a client
62+
Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
6563
try (SessionsClient sessionsClient = SessionsClient.create()) {
6664
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
6765
SessionName session = SessionName.of(projectId, sessionId);
@@ -74,10 +72,9 @@ public static void detectIntentKnowledge(
7472
// Build the query with the TextInput
7573
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
7674

77-
KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId);
7875
QueryParameters queryParameters =
7976
QueryParameters.newBuilder()
80-
.addKnowledgeBaseNames(knowledgeBaseName.toString())
77+
.addKnowledgeBaseNames(knowledgeBaseName)
8178
.build();
8279

8380
DetectIntentRequest detectIntentRequest =
@@ -104,48 +101,12 @@ public static void detectIntentKnowledge(
104101
System.out.format(" - Answer: '%s'\n", answer.getAnswer());
105102
System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence());
106103
}
104+
105+
KnowledgeAnswers answers = queryResult.getKnowledgeAnswers();
106+
allKnowledgeAnswers.put(text, answers);
107107
}
108108
}
109+
return allKnowledgeAnswers;
109110
}
110111
// [END dialogflow_detect_intent_knowledge]
111-
112-
public static void main(String[] args) throws Exception {
113-
ArgumentParser parser =
114-
ArgumentParsers.newFor("DetectIntentKnowledge")
115-
.build()
116-
.defaultHelp(true)
117-
.description("Returns the result of detect intent with text as input for a Knowledge "
118-
+ "Base.\n"
119-
+ "mvn exec:java -DDetectIntentKnowledge -Dexec.args=\"--projectId PROJECT_ID "
120-
+ "--knowledgeBaseId KNOWLEDGE_BASE_ID -sessionId SESSION_ID "
121-
+ "'Where can I find pricing information?'\"\n");
122-
123-
parser.addArgument("--projectId").help("Project/Agent Id").required(true);
124-
125-
parser.addArgument("--knowledgeBaseId")
126-
.help("The ID of the Knowledge Base")
127-
.required(true);
128-
129-
parser.addArgument("--sessionId")
130-
.help("Identifier of the DetectIntent session (Default: UUID.)")
131-
.setDefault(UUID.randomUUID().toString());
132-
133-
parser.addArgument("--languageCode")
134-
.help("Language Code of the query (Default: en-US")
135-
.setDefault("en-US");
136-
137-
parser.addArgument("texts")
138-
.nargs("+")
139-
.help("Text: 'Where can I find pricing information?'")
140-
.required(true);
141-
142-
try {
143-
Namespace namespace = parser.parseArgs(args);
144-
145-
detectIntentKnowledge(namespace.get("projectId"), namespace.get("knowledgeBaseId"),
146-
namespace.get("sessionId"), namespace.get("languageCode"), namespace.get("texts"));
147-
} catch (ArgumentParserException e) {
148-
parser.handleError(e);
149-
}
150-
}
151112
}

0 commit comments

Comments
 (0)