Search in sources :

Example 1 with MessageInput

use of com.ibm.watson.assistant.v2.model.MessageInput in project java-sdk by watson-developer-cloud.

the class AssistantExample method main.

public static void main(String[] args) throws Exception {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    Assistant service = new Assistant("2019-02-28", authenticator);
    MessageInput input = new MessageInput();
    input.setText("Hi");
    MessageOptions options = new MessageOptions.Builder("<workspaceId>").input(input).build();
    // sync
    MessageResponse response = service.message(options).execute().getResult();
    System.out.println(response);
    // async
    service.message(options).enqueue(new ServiceCallback<MessageResponse>() {

        @Override
        public void onResponse(Response<MessageResponse> response) {
            System.out.println(response.getResult());
        }

        @Override
        public void onFailure(Exception e) {
        }
    });
    // RxJava
    Single<Response<MessageResponse>> observableRequest = service.message(options).reactiveRequest();
    observableRequest.subscribeOn(Schedulers.single()).subscribe(new Consumer<Response<MessageResponse>>() {

        @Override
        public void accept(Response<MessageResponse> response) throws Exception {
            System.out.println(response.getResult());
        }
    });
    Thread.sleep(5000);
}
Also used : IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) MessageInput(com.ibm.watson.assistant.v1.model.MessageInput) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) Response(com.ibm.cloud.sdk.core.http.Response) MessageOptions(com.ibm.watson.assistant.v1.model.MessageOptions) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator)

Example 2 with MessageInput

use of com.ibm.watson.assistant.v2.model.MessageInput in project java-sdk by watson-developer-cloud.

the class AssistantTest method testMessageWOptions.

// Test the message operation with a valid options model parameter
@Test
public void testMessageWOptions() throws Throwable {
    // Register a mock response
    String mockResponseBody = "{\"input\": {\"text\": \"text\", \"spelling_suggestions\": false, \"spelling_auto_correct\": false, \"suggested_text\": \"suggestedText\", \"original_text\": \"originalText\"}, \"intents\": [{\"intent\": \"intent\", \"confidence\": 10}], \"entities\": [{\"entity\": \"entity\", \"location\": [8], \"value\": \"value\", \"confidence\": 10, \"groups\": [{\"group\": \"group\", \"location\": [8]}], \"interpretation\": {\"calendar_type\": \"calendarType\", \"datetime_link\": \"datetimeLink\", \"festival\": \"festival\", \"granularity\": \"day\", \"range_link\": \"rangeLink\", \"range_modifier\": \"rangeModifier\", \"relative_day\": 11, \"relative_month\": 13, \"relative_week\": 12, \"relative_weekend\": 15, \"relative_year\": 12, \"specific_day\": 11, \"specific_day_of_week\": \"specificDayOfWeek\", \"specific_month\": 13, \"specific_quarter\": 15, \"specific_year\": 12, \"numeric_value\": 12, \"subtype\": \"subtype\", \"part_of_day\": \"partOfDay\", \"relative_hour\": 12, \"relative_minute\": 14, \"relative_second\": 14, \"specific_hour\": 12, \"specific_minute\": 14, \"specific_second\": 14, \"timezone\": \"timezone\"}, \"alternatives\": [{\"value\": \"value\", \"confidence\": 10}], \"role\": {\"type\": \"date_from\"}}], \"alternate_intents\": false, \"context\": {\"conversation_id\": \"conversationId\", \"system\": {\"mapKey\": \"anyValue\"}, \"metadata\": {\"deployment\": \"deployment\", \"user_id\": \"userId\"}}, \"output\": {\"nodes_visited\": [\"nodesVisited\"], \"nodes_visited_details\": [{\"dialog_node\": \"dialogNode\", \"title\": \"title\", \"conditions\": \"conditions\"}], \"log_messages\": [{\"level\": \"info\", \"msg\": \"msg\", \"code\": \"code\", \"source\": {\"type\": \"dialog_node\", \"dialog_node\": \"dialogNode\"}}], \"generic\": [{\"response_type\": \"option\", \"title\": \"title\", \"description\": \"description\", \"preference\": \"dropdown\", \"options\": [{\"label\": \"label\", \"value\": {\"input\": {\"text\": \"text\", \"spelling_suggestions\": false, \"spelling_auto_correct\": false, \"suggested_text\": \"suggestedText\", \"original_text\": \"originalText\"}, \"intents\": [{\"intent\": \"intent\", \"confidence\": 10}], \"entities\": [{\"entity\": \"entity\", \"location\": [8], \"value\": \"value\", \"confidence\": 10, \"groups\": [{\"group\": \"group\", \"location\": [8]}], \"interpretation\": {\"calendar_type\": \"calendarType\", \"datetime_link\": \"datetimeLink\", \"festival\": \"festival\", \"granularity\": \"day\", \"range_link\": \"rangeLink\", \"range_modifier\": \"rangeModifier\", \"relative_day\": 11, \"relative_month\": 13, \"relative_week\": 12, \"relative_weekend\": 15, \"relative_year\": 12, \"specific_day\": 11, \"specific_day_of_week\": \"specificDayOfWeek\", \"specific_month\": 13, \"specific_quarter\": 15, \"specific_year\": 12, \"numeric_value\": 12, \"subtype\": \"subtype\", \"part_of_day\": \"partOfDay\", \"relative_hour\": 12, \"relative_minute\": 14, \"relative_second\": 14, \"specific_hour\": 12, \"specific_minute\": 14, \"specific_second\": 14, \"timezone\": \"timezone\"}, \"alternatives\": [{\"value\": \"value\", \"confidence\": 10}], \"role\": {\"type\": \"date_from\"}}]}}], \"channels\": [{\"channel\": \"chat\"}]}]}, \"actions\": [{\"name\": \"name\", \"type\": \"client\", \"parameters\": {\"mapKey\": \"anyValue\"}, \"result_variable\": \"resultVariable\", \"credentials\": \"credentials\"}], \"user_id\": \"userId\"}";
    String messagePath = "/v1/workspaces/testString/message";
    server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(200).setBody(mockResponseBody));
    // Construct an instance of the MessageInput model
    MessageInput messageInputModel = new MessageInput.Builder().text("testString").spellingSuggestions(false).spellingAutoCorrect(false).add("foo", "testString").build();
    // Construct an instance of the RuntimeIntent model
    RuntimeIntent runtimeIntentModel = new RuntimeIntent.Builder().intent("testString").confidence(Double.valueOf("72.5")).build();
    // Construct an instance of the CaptureGroup model
    CaptureGroup captureGroupModel = new CaptureGroup.Builder().group("testString").location(new java.util.ArrayList<Long>(java.util.Arrays.asList(Long.valueOf("26")))).build();
    // Construct an instance of the RuntimeEntityInterpretation model
    RuntimeEntityInterpretation runtimeEntityInterpretationModel = new RuntimeEntityInterpretation.Builder().calendarType("testString").datetimeLink("testString").festival("testString").granularity("day").rangeLink("testString").rangeModifier("testString").relativeDay(Double.valueOf("72.5")).relativeMonth(Double.valueOf("72.5")).relativeWeek(Double.valueOf("72.5")).relativeWeekend(Double.valueOf("72.5")).relativeYear(Double.valueOf("72.5")).specificDay(Double.valueOf("72.5")).specificDayOfWeek("testString").specificMonth(Double.valueOf("72.5")).specificQuarter(Double.valueOf("72.5")).specificYear(Double.valueOf("72.5")).numericValue(Double.valueOf("72.5")).subtype("testString").partOfDay("testString").relativeHour(Double.valueOf("72.5")).relativeMinute(Double.valueOf("72.5")).relativeSecond(Double.valueOf("72.5")).specificHour(Double.valueOf("72.5")).specificMinute(Double.valueOf("72.5")).specificSecond(Double.valueOf("72.5")).timezone("testString").build();
    // Construct an instance of the RuntimeEntityAlternative model
    RuntimeEntityAlternative runtimeEntityAlternativeModel = new RuntimeEntityAlternative.Builder().value("testString").confidence(Double.valueOf("72.5")).build();
    // Construct an instance of the RuntimeEntityRole model
    RuntimeEntityRole runtimeEntityRoleModel = new RuntimeEntityRole.Builder().type("date_from").build();
    // Construct an instance of the RuntimeEntity model
    RuntimeEntity runtimeEntityModel = new RuntimeEntity.Builder().entity("testString").location(new java.util.ArrayList<Long>(java.util.Arrays.asList(Long.valueOf("26")))).value("testString").confidence(Double.valueOf("72.5")).groups(new java.util.ArrayList<CaptureGroup>(java.util.Arrays.asList(captureGroupModel))).interpretation(runtimeEntityInterpretationModel).alternatives(new java.util.ArrayList<RuntimeEntityAlternative>(java.util.Arrays.asList(runtimeEntityAlternativeModel))).role(runtimeEntityRoleModel).build();
    // Construct an instance of the MessageContextMetadata model
    MessageContextMetadata messageContextMetadataModel = new MessageContextMetadata.Builder().deployment("testString").userId("testString").build();
    // Construct an instance of the Context model
    Context contextModel = new Context.Builder().conversationId("testString").system(new java.util.HashMap<String, Object>() {

        {
            put("foo", "testString");
        }
    }).metadata(messageContextMetadataModel).add("foo", "testString").build();
    // Construct an instance of the DialogNodeVisitedDetails model
    DialogNodeVisitedDetails dialogNodeVisitedDetailsModel = new DialogNodeVisitedDetails.Builder().dialogNode("testString").title("testString").conditions("testString").build();
    // Construct an instance of the LogMessageSource model
    LogMessageSource logMessageSourceModel = new LogMessageSource.Builder().type("dialog_node").dialogNode("testString").build();
    // Construct an instance of the LogMessage model
    LogMessage logMessageModel = new LogMessage.Builder().level("info").msg("testString").code("testString").source(logMessageSourceModel).build();
    // Construct an instance of the DialogNodeOutputOptionsElementValue model
    DialogNodeOutputOptionsElementValue dialogNodeOutputOptionsElementValueModel = new DialogNodeOutputOptionsElementValue.Builder().input(messageInputModel).intents(new java.util.ArrayList<RuntimeIntent>(java.util.Arrays.asList(runtimeIntentModel))).entities(new java.util.ArrayList<RuntimeEntity>(java.util.Arrays.asList(runtimeEntityModel))).build();
    // Construct an instance of the DialogNodeOutputOptionsElement model
    DialogNodeOutputOptionsElement dialogNodeOutputOptionsElementModel = new DialogNodeOutputOptionsElement.Builder().label("testString").value(dialogNodeOutputOptionsElementValueModel).build();
    // Construct an instance of the ResponseGenericChannel model
    ResponseGenericChannel responseGenericChannelModel = new ResponseGenericChannel.Builder().channel("chat").build();
    // Construct an instance of the RuntimeResponseGenericRuntimeResponseTypeOption model
    RuntimeResponseGenericRuntimeResponseTypeOption runtimeResponseGenericModel = new RuntimeResponseGenericRuntimeResponseTypeOption.Builder().responseType("option").title("testString").description("testString").preference("dropdown").options(new java.util.ArrayList<DialogNodeOutputOptionsElement>(java.util.Arrays.asList(dialogNodeOutputOptionsElementModel))).channels(new java.util.ArrayList<ResponseGenericChannel>(java.util.Arrays.asList(responseGenericChannelModel))).build();
    // Construct an instance of the OutputData model
    OutputData outputDataModel = new OutputData.Builder().nodesVisited(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).nodesVisitedDetails(new java.util.ArrayList<DialogNodeVisitedDetails>(java.util.Arrays.asList(dialogNodeVisitedDetailsModel))).logMessages(new java.util.ArrayList<LogMessage>(java.util.Arrays.asList(logMessageModel))).generic(new java.util.ArrayList<RuntimeResponseGeneric>(java.util.Arrays.asList(runtimeResponseGenericModel))).add("foo", "testString").build();
    // Construct an instance of the MessageOptions model
    MessageOptions messageOptionsModel = new MessageOptions.Builder().workspaceId("testString").input(messageInputModel).intents(new java.util.ArrayList<RuntimeIntent>(java.util.Arrays.asList(runtimeIntentModel))).entities(new java.util.ArrayList<RuntimeEntity>(java.util.Arrays.asList(runtimeEntityModel))).alternateIntents(false).context(contextModel).output(outputDataModel).userId("testString").nodesVisitedDetails(false).build();
    // Invoke message() with a valid options model and verify the result
    Response<MessageResponse> response = assistantService.message(messageOptionsModel).execute();
    assertNotNull(response);
    MessageResponse responseObj = response.getResult();
    assertNotNull(responseObj);
    // Verify the contents of the request sent to the mock server
    RecordedRequest request = server.takeRequest();
    assertNotNull(request);
    assertEquals(request.getMethod(), "POST");
    // Verify request path
    String parsedPath = TestUtilities.parseReqPath(request);
    assertEquals(parsedPath, messagePath);
    // Verify query params
    Map<String, String> query = TestUtilities.parseQueryString(request);
    assertNotNull(query);
    assertEquals(query.get("version"), "testString");
    assertEquals(Boolean.valueOf(query.get("nodes_visited_details")), Boolean.valueOf(false));
}
Also used : RuntimeResponseGenericRuntimeResponseTypeOption(com.ibm.watson.assistant.v1.model.RuntimeResponseGenericRuntimeResponseTypeOption) HashMap(java.util.HashMap) DialogNodeOutputOptionsElementValue(com.ibm.watson.assistant.v1.model.DialogNodeOutputOptionsElementValue) LogMessageSource(com.ibm.watson.assistant.v1.model.LogMessageSource) MessageContextMetadata(com.ibm.watson.assistant.v1.model.MessageContextMetadata) DialogNodeVisitedDetails(com.ibm.watson.assistant.v1.model.DialogNodeVisitedDetails) MockResponse(okhttp3.mockwebserver.MockResponse) DialogNodeOutputOptionsElement(com.ibm.watson.assistant.v1.model.DialogNodeOutputOptionsElement) RuntimeIntent(com.ibm.watson.assistant.v1.model.RuntimeIntent) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) RuntimeEntityRole(com.ibm.watson.assistant.v1.model.RuntimeEntityRole) RuntimeResponseGeneric(com.ibm.watson.assistant.v1.model.RuntimeResponseGeneric) OutputData(com.ibm.watson.assistant.v1.model.OutputData) RuntimeEntityAlternative(com.ibm.watson.assistant.v1.model.RuntimeEntityAlternative) RuntimeEntity(com.ibm.watson.assistant.v1.model.RuntimeEntity) CaptureGroup(com.ibm.watson.assistant.v1.model.CaptureGroup) ResponseGenericChannel(com.ibm.watson.assistant.v1.model.ResponseGenericChannel) MessageInput(com.ibm.watson.assistant.v1.model.MessageInput) MessageOptions(com.ibm.watson.assistant.v1.model.MessageOptions) DialogNodeContext(com.ibm.watson.assistant.v1.model.DialogNodeContext) Context(com.ibm.watson.assistant.v1.model.Context) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) RuntimeEntityInterpretation(com.ibm.watson.assistant.v1.model.RuntimeEntityInterpretation) LogMessage(com.ibm.watson.assistant.v1.model.LogMessage) Test(org.testng.annotations.Test)

Example 3 with MessageInput

use of com.ibm.watson.assistant.v2.model.MessageInput in project java-sdk by watson-developer-cloud.

the class AssistantTest method testMessageWOptions.

// Test the message operation with a valid options model parameter
@Test
public void testMessageWOptions() throws Throwable {
    // Register a mock response
    String mockResponseBody = "{\"output\": {\"generic\": [{\"response_type\": \"option\", \"title\": \"title\", \"description\": \"description\", \"preference\": \"dropdown\", \"options\": [{\"label\": \"label\", \"value\": {\"input\": {\"message_type\": \"text\", \"text\": \"text\", \"intents\": [{\"intent\": \"intent\", \"confidence\": 10}], \"entities\": [{\"entity\": \"entity\", \"location\": [8], \"value\": \"value\", \"confidence\": 10, \"groups\": [{\"group\": \"group\", \"location\": [8]}], \"interpretation\": {\"calendar_type\": \"calendarType\", \"datetime_link\": \"datetimeLink\", \"festival\": \"festival\", \"granularity\": \"day\", \"range_link\": \"rangeLink\", \"range_modifier\": \"rangeModifier\", \"relative_day\": 11, \"relative_month\": 13, \"relative_week\": 12, \"relative_weekend\": 15, \"relative_year\": 12, \"specific_day\": 11, \"specific_day_of_week\": \"specificDayOfWeek\", \"specific_month\": 13, \"specific_quarter\": 15, \"specific_year\": 12, \"numeric_value\": 12, \"subtype\": \"subtype\", \"part_of_day\": \"partOfDay\", \"relative_hour\": 12, \"relative_minute\": 14, \"relative_second\": 14, \"specific_hour\": 12, \"specific_minute\": 14, \"specific_second\": 14, \"timezone\": \"timezone\"}, \"alternatives\": [{\"value\": \"value\", \"confidence\": 10}], \"role\": {\"type\": \"date_from\"}}], \"suggestion_id\": \"suggestionId\", \"attachments\": [{\"url\": \"url\", \"media_type\": \"mediaType\"}], \"options\": {\"restart\": false, \"alternate_intents\": false, \"spelling\": {\"suggestions\": false, \"auto_correct\": false}, \"debug\": false, \"return_context\": false, \"export\": false}}}}], \"channels\": [{\"channel\": \"channel\"}]}], \"intents\": [{\"intent\": \"intent\", \"confidence\": 10}], \"entities\": [{\"entity\": \"entity\", \"location\": [8], \"value\": \"value\", \"confidence\": 10, \"groups\": [{\"group\": \"group\", \"location\": [8]}], \"interpretation\": {\"calendar_type\": \"calendarType\", \"datetime_link\": \"datetimeLink\", \"festival\": \"festival\", \"granularity\": \"day\", \"range_link\": \"rangeLink\", \"range_modifier\": \"rangeModifier\", \"relative_day\": 11, \"relative_month\": 13, \"relative_week\": 12, \"relative_weekend\": 15, \"relative_year\": 12, \"specific_day\": 11, \"specific_day_of_week\": \"specificDayOfWeek\", \"specific_month\": 13, \"specific_quarter\": 15, \"specific_year\": 12, \"numeric_value\": 12, \"subtype\": \"subtype\", \"part_of_day\": \"partOfDay\", \"relative_hour\": 12, \"relative_minute\": 14, \"relative_second\": 14, \"specific_hour\": 12, \"specific_minute\": 14, \"specific_second\": 14, \"timezone\": \"timezone\"}, \"alternatives\": [{\"value\": \"value\", \"confidence\": 10}], \"role\": {\"type\": \"date_from\"}}], \"actions\": [{\"name\": \"name\", \"type\": \"client\", \"parameters\": {\"mapKey\": \"anyValue\"}, \"result_variable\": \"resultVariable\", \"credentials\": \"credentials\"}], \"debug\": {\"nodes_visited\": [{\"dialog_node\": \"dialogNode\", \"title\": \"title\", \"conditions\": \"conditions\"}], \"log_messages\": [{\"level\": \"info\", \"message\": \"message\", \"code\": \"code\", \"source\": {\"type\": \"dialog_node\", \"dialog_node\": \"dialogNode\"}}], \"branch_exited\": true, \"branch_exited_reason\": \"completed\"}, \"user_defined\": {\"mapKey\": \"anyValue\"}, \"spelling\": {\"text\": \"text\", \"original_text\": \"originalText\", \"suggested_text\": \"suggestedText\"}}, \"context\": {\"global\": {\"system\": {\"timezone\": \"timezone\", \"user_id\": \"userId\", \"turn_count\": 9, \"locale\": \"en-us\", \"reference_time\": \"referenceTime\", \"session_start_time\": \"sessionStartTime\", \"state\": \"state\", \"skip_user_input\": false}, \"session_id\": \"sessionId\"}, \"skills\": {\"mapKey\": {\"user_defined\": {\"mapKey\": {\"anyKey\": \"anyValue\"}}, \"system\": {\"state\": \"state\"}}}, \"integrations\": {\"mapKey\": \"anyValue\"}}, \"user_id\": \"userId\"}";
    String messagePath = "/v2/assistants/testString/sessions/testString/message";
    server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(200).setBody(mockResponseBody));
    // Construct an instance of the RuntimeIntent model
    RuntimeIntent runtimeIntentModel = new RuntimeIntent.Builder().intent("testString").confidence(Double.valueOf("72.5")).build();
    // Construct an instance of the CaptureGroup model
    CaptureGroup captureGroupModel = new CaptureGroup.Builder().group("testString").location(new java.util.ArrayList<Long>(java.util.Arrays.asList(Long.valueOf("26")))).build();
    // Construct an instance of the RuntimeEntityInterpretation model
    RuntimeEntityInterpretation runtimeEntityInterpretationModel = new RuntimeEntityInterpretation.Builder().calendarType("testString").datetimeLink("testString").festival("testString").granularity("day").rangeLink("testString").rangeModifier("testString").relativeDay(Double.valueOf("72.5")).relativeMonth(Double.valueOf("72.5")).relativeWeek(Double.valueOf("72.5")).relativeWeekend(Double.valueOf("72.5")).relativeYear(Double.valueOf("72.5")).specificDay(Double.valueOf("72.5")).specificDayOfWeek("testString").specificMonth(Double.valueOf("72.5")).specificQuarter(Double.valueOf("72.5")).specificYear(Double.valueOf("72.5")).numericValue(Double.valueOf("72.5")).subtype("testString").partOfDay("testString").relativeHour(Double.valueOf("72.5")).relativeMinute(Double.valueOf("72.5")).relativeSecond(Double.valueOf("72.5")).specificHour(Double.valueOf("72.5")).specificMinute(Double.valueOf("72.5")).specificSecond(Double.valueOf("72.5")).timezone("testString").build();
    // Construct an instance of the RuntimeEntityAlternative model
    RuntimeEntityAlternative runtimeEntityAlternativeModel = new RuntimeEntityAlternative.Builder().value("testString").confidence(Double.valueOf("72.5")).build();
    // Construct an instance of the RuntimeEntityRole model
    RuntimeEntityRole runtimeEntityRoleModel = new RuntimeEntityRole.Builder().type("date_from").build();
    // Construct an instance of the RuntimeEntity model
    RuntimeEntity runtimeEntityModel = new RuntimeEntity.Builder().entity("testString").location(new java.util.ArrayList<Long>(java.util.Arrays.asList(Long.valueOf("26")))).value("testString").confidence(Double.valueOf("72.5")).groups(new java.util.ArrayList<CaptureGroup>(java.util.Arrays.asList(captureGroupModel))).interpretation(runtimeEntityInterpretationModel).alternatives(new java.util.ArrayList<RuntimeEntityAlternative>(java.util.Arrays.asList(runtimeEntityAlternativeModel))).role(runtimeEntityRoleModel).build();
    // Construct an instance of the MessageInputAttachment model
    MessageInputAttachment messageInputAttachmentModel = new MessageInputAttachment.Builder().url("testString").mediaType("testString").build();
    // Construct an instance of the MessageInputOptionsSpelling model
    MessageInputOptionsSpelling messageInputOptionsSpellingModel = new MessageInputOptionsSpelling.Builder().suggestions(true).autoCorrect(true).build();
    // Construct an instance of the MessageInputOptions model
    MessageInputOptions messageInputOptionsModel = new MessageInputOptions.Builder().restart(false).alternateIntents(false).spelling(messageInputOptionsSpellingModel).debug(false).returnContext(false).export(false).build();
    // Construct an instance of the MessageInput model
    MessageInput messageInputModel = new MessageInput.Builder().messageType("text").text("testString").intents(new java.util.ArrayList<RuntimeIntent>(java.util.Arrays.asList(runtimeIntentModel))).entities(new java.util.ArrayList<RuntimeEntity>(java.util.Arrays.asList(runtimeEntityModel))).suggestionId("testString").attachments(new java.util.ArrayList<MessageInputAttachment>(java.util.Arrays.asList(messageInputAttachmentModel))).options(messageInputOptionsModel).build();
    // Construct an instance of the MessageContextGlobalSystem model
    MessageContextGlobalSystem messageContextGlobalSystemModel = new MessageContextGlobalSystem.Builder().timezone("testString").userId("testString").turnCount(Long.valueOf("26")).locale("en-us").referenceTime("testString").sessionStartTime("testString").state("testString").skipUserInput(true).build();
    // Construct an instance of the MessageContextGlobal model
    MessageContextGlobal messageContextGlobalModel = new MessageContextGlobal.Builder().system(messageContextGlobalSystemModel).build();
    // Construct an instance of the MessageContextSkillSystem model
    MessageContextSkillSystem messageContextSkillSystemModel = new MessageContextSkillSystem.Builder().state("testString").add("foo", "testString").build();
    // Construct an instance of the MessageContextSkill model
    MessageContextSkill messageContextSkillModel = new MessageContextSkill.Builder().userDefined(new java.util.HashMap<String, Object>() {

        {
            put("foo", TestUtilities.createMockMap());
        }
    }).system(messageContextSkillSystemModel).build();
    // Construct an instance of the MessageContext model
    MessageContext messageContextModel = new MessageContext.Builder().global(messageContextGlobalModel).skills(new java.util.HashMap<String, MessageContextSkill>() {

        {
            put("foo", messageContextSkillModel);
        }
    }).integrations(new java.util.HashMap<String, Object>() {

        {
            put("foo", "testString");
        }
    }).build();
    // Construct an instance of the MessageOptions model
    MessageOptions messageOptionsModel = new MessageOptions.Builder().assistantId("testString").sessionId("testString").input(messageInputModel).context(messageContextModel).userId("testString").build();
    // Invoke message() with a valid options model and verify the result
    Response<MessageResponse> response = assistantService.message(messageOptionsModel).execute();
    assertNotNull(response);
    MessageResponse responseObj = response.getResult();
    assertNotNull(responseObj);
    // Verify the contents of the request sent to the mock server
    RecordedRequest request = server.takeRequest();
    assertNotNull(request);
    assertEquals(request.getMethod(), "POST");
    // Verify request path
    String parsedPath = TestUtilities.parseReqPath(request);
    assertEquals(parsedPath, messagePath);
    // Verify query params
    Map<String, String> query = TestUtilities.parseQueryString(request);
    assertNotNull(query);
    assertEquals(query.get("version"), "testString");
}
Also used : RuntimeEntity(com.ibm.watson.assistant.v2.model.RuntimeEntity) HashMap(java.util.HashMap) CaptureGroup(com.ibm.watson.assistant.v2.model.CaptureGroup) MessageInput(com.ibm.watson.assistant.v2.model.MessageInput) MessageContextSkill(com.ibm.watson.assistant.v2.model.MessageContextSkill) MessageContextGlobalSystem(com.ibm.watson.assistant.v2.model.MessageContextGlobalSystem) MessageOptions(com.ibm.watson.assistant.v2.model.MessageOptions) MessageContextSkillSystem(com.ibm.watson.assistant.v2.model.MessageContextSkillSystem) MessageContext(com.ibm.watson.assistant.v2.model.MessageContext) MessageContextGlobal(com.ibm.watson.assistant.v2.model.MessageContextGlobal) MessageInputOptionsSpelling(com.ibm.watson.assistant.v2.model.MessageInputOptionsSpelling) MessageInputAttachment(com.ibm.watson.assistant.v2.model.MessageInputAttachment) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RuntimeIntent(com.ibm.watson.assistant.v2.model.RuntimeIntent) MessageResponse(com.ibm.watson.assistant.v2.model.MessageResponse) MessageInputOptions(com.ibm.watson.assistant.v2.model.MessageInputOptions) RuntimeEntityInterpretation(com.ibm.watson.assistant.v2.model.RuntimeEntityInterpretation) RuntimeEntityRole(com.ibm.watson.assistant.v2.model.RuntimeEntityRole) RuntimeEntityAlternative(com.ibm.watson.assistant.v2.model.RuntimeEntityAlternative) Test(org.testng.annotations.Test)

Example 4 with MessageInput

use of com.ibm.watson.assistant.v2.model.MessageInput in project java-sdk by watson-developer-cloud.

the class AssistantToneAnalyzerIntegrationExample method main.

public static void main(String[] args) throws Exception {
    // instantiate the assistant service
    Authenticator assistantAuthenticator = new IamAuthenticator("<iam_api_key>");
    final Assistant assistantService = new Assistant("2019-02-28", assistantAuthenticator);
    // instantiate the tone analyzer service
    Authenticator toneAuthenticator = new IamAuthenticator("<iam_api_key>");
    ToneAnalyzer toneService = new ToneAnalyzer("2017-09-21", toneAuthenticator);
    // workspace id
    final String workspaceId = "<workspace-id>";
    // maintain history in the context variable - will add a history variable to
    // each of the emotion, social
    // and language tones
    final boolean maintainHistory = false;
    /**
     * Input for the Assistant service: text (String): an input string (the user's conversation
     * turn) and context (Context): any context that needs to be maintained - either added by the
     * client app or passed in the response from the Assistant service on the previous conversation
     * turn.
     */
    final String text = "I am happy";
    final Context context = new Context();
    // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION
    // set local context variable to the context from the last response from the
    // Assistant Service
    // (see the getContext() method of the MessageResponse class in
    // com.ibm.watson.assistant.v1.model)
    // async call to Tone Analyzer
    ToneOptions toneOptions = new ToneOptions.Builder().text(text).build();
    toneService.tone(toneOptions).enqueue(new ServiceCallback<ToneAnalysis>() {

        @Override
        public void onResponse(Response<ToneAnalysis> toneResponsePayload) {
            // update context with the tone data returned by the Tone Analyzer
            context.setSystem(ToneDetection.updateUserTone(context, toneResponsePayload.getResult(), maintainHistory));
            // create input for message
            MessageInput input = new MessageInput();
            input.setText(text);
            // call Assistant Service with the input and tone-aware context
            MessageOptions messageOptions = new MessageOptions.Builder(workspaceId).input(input).context(context).build();
            assistantService.message(messageOptions).enqueue(new ServiceCallback<MessageResponse>() {

                @Override
                public void onResponse(Response<MessageResponse> response) {
                    System.out.println(response.getResult());
                }

                @Override
                public void onFailure(Exception e) {
                }
            });
        }

        @Override
        public void onFailure(Exception e) {
        }
    });
}
Also used : Context(com.ibm.watson.assistant.v1.model.Context) ToneAnalysis(com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) MessageInput(com.ibm.watson.assistant.v1.model.MessageInput) ToneOptions(com.ibm.watson.tone_analyzer.v3.model.ToneOptions) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) Response(com.ibm.cloud.sdk.core.http.Response) ServiceCallback(com.ibm.cloud.sdk.core.http.ServiceCallback) ToneAnalyzer(com.ibm.watson.tone_analyzer.v3.ToneAnalyzer) MessageOptions(com.ibm.watson.assistant.v1.model.MessageOptions) Assistant(com.ibm.watson.assistant.v1.Assistant) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator)

Aggregations

MessageInput (com.ibm.watson.assistant.v1.model.MessageInput)3 MessageOptions (com.ibm.watson.assistant.v1.model.MessageOptions)3 MessageResponse (com.ibm.watson.assistant.v1.model.MessageResponse)3 Response (com.ibm.cloud.sdk.core.http.Response)2 Authenticator (com.ibm.cloud.sdk.core.security.Authenticator)2 IamAuthenticator (com.ibm.cloud.sdk.core.security.IamAuthenticator)2 Context (com.ibm.watson.assistant.v1.model.Context)2 HashMap (java.util.HashMap)2 MockResponse (okhttp3.mockwebserver.MockResponse)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 Test (org.testng.annotations.Test)2 ServiceCallback (com.ibm.cloud.sdk.core.http.ServiceCallback)1 Assistant (com.ibm.watson.assistant.v1.Assistant)1 CaptureGroup (com.ibm.watson.assistant.v1.model.CaptureGroup)1 DialogNodeContext (com.ibm.watson.assistant.v1.model.DialogNodeContext)1 DialogNodeOutputOptionsElement (com.ibm.watson.assistant.v1.model.DialogNodeOutputOptionsElement)1 DialogNodeOutputOptionsElementValue (com.ibm.watson.assistant.v1.model.DialogNodeOutputOptionsElementValue)1 DialogNodeVisitedDetails (com.ibm.watson.assistant.v1.model.DialogNodeVisitedDetails)1 LogMessage (com.ibm.watson.assistant.v1.model.LogMessage)1 LogMessageSource (com.ibm.watson.assistant.v1.model.LogMessageSource)1