Skip to content

Commit 7234e49

Browse files
jessiexjiang27Shabirmean
authored andcommitted
samples: add samples for Dialogflow CX (#15)
* Add sample codes. Add the sample codes for the following method: - CreateFlow - CreatePage - CreateIntent - DetectIntent - StreamingDetectIntent * Small fix to header Small fix to header to pass lint * Fix package name Fix package format. * Add tests for sample codes. Add tests for sample codes per change request. * Fix lint error. Change the location of variable declarations. * Exclude new dependencies from the region tag Exclude new dependencies from the region tag * Add integration tests for sample codes. Add integration tests for sample codes. * Change env vars and package based on comments Change the env variables and package names based on comments. Remove DIALOGFLOW_CX_AGENT_ID from Kokora configs. * Refactor code and move clean up logics * Change output stream Avoid setting output stream to null to enable tests to run in parallel. * Get audio transcript for test
1 parent eb83fbb commit 7234e49

File tree

11 files changed

+778
-0
lines changed

11 files changed

+778
-0
lines changed
30.3 KB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dialogflow.cx;
18+
19+
// [START dialogflow_cx_create_flow]
20+
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.dialogflow.cx.v3beta1.AgentName;
23+
import com.google.cloud.dialogflow.cx.v3beta1.EventHandler;
24+
import com.google.cloud.dialogflow.cx.v3beta1.Flow;
25+
import com.google.cloud.dialogflow.cx.v3beta1.FlowsClient;
26+
import com.google.cloud.dialogflow.cx.v3beta1.Fulfillment;
27+
import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage;
28+
import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text;
29+
import java.io.IOException;
30+
import java.util.ArrayList;
31+
import java.util.List;
32+
import java.util.Map;
33+
34+
public class CreateFlow {
35+
36+
// Create a flow in the specified agent.
37+
public static Flow createFlow(
38+
String displayName,
39+
String projectId,
40+
String locationId,
41+
String agentId,
42+
Map<String, String> eventsToFulfillmentMessages)
43+
throws IOException, ApiException {
44+
// Instantiates a client
45+
try (FlowsClient flowsClient = FlowsClient.create()) {
46+
// Set the project agent name using the projectID (my-project-id), locationID (global), and
47+
// agentID (UUID).
48+
AgentName parent = AgentName.of(projectId, locationId, agentId);
49+
50+
// Build the EventHandlers for the flow using the mapping from events to fulfillment messages.
51+
List<EventHandler> eventHandlers = new ArrayList<>();
52+
for (Map.Entry<String, String> item : eventsToFulfillmentMessages.entrySet()) {
53+
eventHandlers.add(
54+
EventHandler.newBuilder()
55+
.setEvent(item.getKey()) // Event (sys.no-match-default)
56+
.setTriggerFulfillment(
57+
Fulfillment.newBuilder()
58+
// Text ("Sorry, could you say that again?")
59+
.addMessages(
60+
ResponseMessage.newBuilder()
61+
.setText(Text.newBuilder().addText(item.getValue()).build())
62+
.build())
63+
.build())
64+
.build());
65+
}
66+
67+
// Build the flow.
68+
Flow flow =
69+
Flow.newBuilder().setDisplayName(displayName).addAllEventHandlers(eventHandlers).build();
70+
71+
// Performs the create flow request.
72+
Flow response = flowsClient.createFlow(parent, flow);
73+
System.out.format("Flow created: %s\n", response);
74+
75+
return response;
76+
}
77+
}
78+
}
79+
// [END dialogflow_cx_create_flow]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dialogflow.cx;
18+
19+
// [START dialogflow_cx_create_intent]
20+
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.dialogflow.cx.v3beta1.AgentName;
23+
import com.google.cloud.dialogflow.cx.v3beta1.Intent;
24+
import com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase;
25+
import com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase.Part;
26+
import com.google.cloud.dialogflow.cx.v3beta1.IntentsClient;
27+
import java.io.IOException;
28+
import java.util.ArrayList;
29+
import java.util.List;
30+
31+
public class CreateIntent {
32+
33+
// Create an intent of the given intent type.
34+
public static Intent createIntent(
35+
String displayName,
36+
String projectId,
37+
String locationId,
38+
String agentId,
39+
List<String> trainingPhrasesParts)
40+
throws IOException, ApiException {
41+
// Instantiates a client
42+
try (IntentsClient intentsClient = IntentsClient.create()) {
43+
// Set the project agent name using the projectID (my-project-id), locationID (global), and
44+
// agentID (UUID).
45+
AgentName parent = AgentName.of(projectId, locationId, agentId);
46+
47+
// Build the trainingPhrases from the trainingPhrasesParts.
48+
List<TrainingPhrase> trainingPhrases = new ArrayList<>();
49+
for (String trainingPhrase : trainingPhrasesParts) {
50+
trainingPhrases.add(
51+
TrainingPhrase.newBuilder()
52+
.addParts(Part.newBuilder().setText(trainingPhrase).build())
53+
.setRepeatCount(1)
54+
.build());
55+
}
56+
57+
// Build the intent.
58+
Intent intent =
59+
Intent.newBuilder()
60+
.setDisplayName(displayName)
61+
.addAllTrainingPhrases(trainingPhrases)
62+
.build();
63+
64+
// Performs the create intent request.
65+
Intent response = intentsClient.createIntent(parent, intent);
66+
System.out.format("Intent created: %s\n", response);
67+
68+
return response;
69+
}
70+
}
71+
}
72+
// [END dialogflow_cx_create_intent]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dialogflow.cx;
18+
19+
// [START dialogflow_cx_create_page]
20+
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.dialogflow.cx.v3beta1.FlowName;
23+
import com.google.cloud.dialogflow.cx.v3beta1.Form;
24+
import com.google.cloud.dialogflow.cx.v3beta1.Form.Parameter;
25+
import com.google.cloud.dialogflow.cx.v3beta1.Form.Parameter.FillBehavior;
26+
import com.google.cloud.dialogflow.cx.v3beta1.Fulfillment;
27+
import com.google.cloud.dialogflow.cx.v3beta1.Page;
28+
import com.google.cloud.dialogflow.cx.v3beta1.PagesClient;
29+
import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage;
30+
import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text;
31+
import java.io.IOException;
32+
import java.util.List;
33+
34+
public class CreatePage {
35+
36+
// Create a page in the specified agent.
37+
public static Page createPage(
38+
String displayName,
39+
String projectId,
40+
String locationId,
41+
String agentId,
42+
String flowId,
43+
List<String> entryTexts)
44+
throws IOException, ApiException {
45+
// Instantiates a client
46+
try (PagesClient pagesClient = PagesClient.create()) {
47+
// Set the flow name using the projectID (my-project-id), locationID (global), agentID (UUID)
48+
// and flowID (UUID).
49+
FlowName parent = FlowName.of(projectId, locationId, agentId, flowId);
50+
51+
// Build the entry fulfillment based on entry texts.
52+
Fulfillment.Builder entryFulfillmentBuilder = Fulfillment.newBuilder();
53+
for (String entryText : entryTexts) {
54+
entryFulfillmentBuilder.addMessages(
55+
ResponseMessage.newBuilder()
56+
// Text ("Hi")
57+
.setText(Text.newBuilder().addText(entryText).build())
58+
.build());
59+
}
60+
Fulfillment entryFulfillment = entryFulfillmentBuilder.build();
61+
62+
// Build the form for the new page.
63+
// Note: hard coding parameters for simplicity.
64+
FillBehavior fillBehavior =
65+
FillBehavior.newBuilder()
66+
.setInitialPromptFulfillment(
67+
Fulfillment.newBuilder()
68+
.addMessages(
69+
ResponseMessage.newBuilder()
70+
.setText(Text.newBuilder().addText("What would you like?").build())
71+
.build())
72+
.build())
73+
.build();
74+
Form form =
75+
Form.newBuilder()
76+
.addParameters(
77+
Parameter.newBuilder()
78+
.setDisplayName("param")
79+
.setRequired(true)
80+
.setEntityType("projects/-/locations/-/agents/-/entityTypes/sys.any")
81+
.setFillBehavior(fillBehavior)
82+
.build())
83+
.build();
84+
85+
// Build the page.
86+
Page page =
87+
Page.newBuilder()
88+
.setDisplayName(displayName)
89+
.setEntryFulfillment(entryFulfillment)
90+
.setForm(form)
91+
.build();
92+
93+
// Performs the create page request.
94+
Page response = pagesClient.createPage(parent, page);
95+
System.out.format("Page created: %s\n", response);
96+
97+
return response;
98+
}
99+
}
100+
}
101+
// [END dialogflow_cx_create_page]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dialogflow.cx;
18+
19+
// [START dialogflow_cx_detect_intent_text]
20+
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest;
23+
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse;
24+
import com.google.cloud.dialogflow.cx.v3beta1.QueryInput;
25+
import com.google.cloud.dialogflow.cx.v3beta1.QueryResult;
26+
import com.google.cloud.dialogflow.cx.v3beta1.SessionName;
27+
import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient;
28+
import com.google.cloud.dialogflow.cx.v3beta1.TextInput;
29+
import com.google.common.collect.Maps;
30+
import java.io.IOException;
31+
import java.util.List;
32+
import java.util.Map;
33+
34+
public class DetectIntent {
35+
36+
// DialogFlow API Detect Intent sample with text inputs.
37+
public static Map<String, QueryResult> detectIntent(
38+
String projectId,
39+
String locationId,
40+
String agentId,
41+
String sessionId,
42+
List<String> texts,
43+
String languageCode)
44+
throws IOException, ApiException {
45+
Map<String, QueryResult> queryResults = Maps.newHashMap();
46+
// Instantiates a client
47+
try (SessionsClient sessionsClient = SessionsClient.create()) {
48+
// Set the session name using the projectID (my-project-id), locationID (global), agentID
49+
// (UUID), and sessionId (UUID).
50+
SessionName session = SessionName.of(projectId, locationId, agentId, sessionId);
51+
System.out.println("Session Path: " + session.toString());
52+
53+
// Detect intents for each text input.
54+
for (String text : texts) {
55+
// Set the text (hello) for the query.
56+
TextInput.Builder textInput = TextInput.newBuilder().setText(text);
57+
58+
// Build the query with the TextInput and language code (en-US).
59+
QueryInput queryInput =
60+
QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build();
61+
62+
// Build the DetectIntentRequest with the SessionName and QueryInput.
63+
DetectIntentRequest request =
64+
DetectIntentRequest.newBuilder()
65+
.setSession(session.toString())
66+
.setQueryInput(queryInput)
67+
.build();
68+
69+
// Performs the detect intent request.
70+
DetectIntentResponse response = sessionsClient.detectIntent(request);
71+
72+
// Display the query result.
73+
QueryResult queryResult = response.getQueryResult();
74+
75+
System.out.println("====================");
76+
System.out.format("Query Text: '%s'\n", queryResult.getText());
77+
System.out.format(
78+
"Detected Intent: %s (confidence: %f)\n",
79+
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
80+
81+
queryResults.put(text, queryResult);
82+
}
83+
}
84+
return queryResults;
85+
}
86+
}
87+
// [END dialogflow_cx_detect_intent_text]

0 commit comments

Comments
 (0)