Search in sources :

Example 1 with Assistant

use of com.ibm.watson.assistant.v1.Assistant in project java-sdk by watson-developer-cloud.

the class AssistantExample method main.

public static void main(String[] args) throws Exception {
    Assistant service = new Assistant("2018-02-16");
    service.setUsernameAndPassword("<username>", "<password>");
    InputData input = new InputData.Builder("Hi").build();
    MessageOptions options = new MessageOptions.Builder("<workspaceId>").input(input).build();
    // sync
    MessageResponse response = service.message(options).execute();
    System.out.println(response);
    // async
    service.message(options).enqueue(new ServiceCallback<MessageResponse>() {

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

        @Override
        public void onFailure(Exception e) {
        }
    });
    // rx callback
    service.message(options).rx().thenApply(new CompletableFuture.Fun<MessageResponse, OutputData>() {

        @Override
        public OutputData apply(MessageResponse message) {
            return message.getOutput();
        }
    }).thenAccept(new CompletableFuture.Action<OutputData>() {

        @Override
        public void accept(OutputData output) {
            System.out.println(output);
        }
    });
    // rx async callback
    service.message(options).rx().thenApplyAsync(new CompletableFuture.Fun<MessageResponse, OutputData>() {

        @Override
        public OutputData apply(MessageResponse message) {
            return message.getOutput();
        }
    }).thenAccept(new CompletableFuture.Action<OutputData>() {

        @Override
        public void accept(OutputData output) {
            System.out.println(output);
        }
    });
    // rx sync
    try {
        MessageResponse rxMessageResponse = service.message(options).rx().get();
        System.out.println(rxMessageResponse);
    } catch (Exception ex) {
    // Handle exception
    }
}
Also used : MessageResponse(com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse) CompletableFuture(jersey.repackaged.jsr166e.CompletableFuture) MessageOptions(com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions) Assistant(com.ibm.watson.developer_cloud.assistant.v1.Assistant) OutputData(com.ibm.watson.developer_cloud.assistant.v1.model.OutputData)

Example 2 with Assistant

use of com.ibm.watson.assistant.v1.Assistant 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
    Assistant assistantService = new Assistant("2018-02-16");
    assistantService.setUsernameAndPassword("<username>", "<password>");
    // instantiate the tone analyzer service
    ToneAnalyzer toneService = new ToneAnalyzer("2017-09-21");
    toneService.setUsernameAndPassword("<username>", "<password>");
    // workspace id
    String workspaceId = "<workspace-id>";
    // maintain history in the context variable - will add a history variable to
    // each of the emotion, social
    // and language tones
    boolean maintainHistory = false;
    /**
     * Input for the Assistant service: input (String): an input string (the user's conversation turn) and context
     * (Map<String,Object>: 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.
     */
    String input = "I am happy";
    Map<String, Object> context = new HashMap<>();
    // 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.developer_cloud.assistant.v1.model)
    // async call to Tone Analyzer
    ToneOptions toneOptions = new ToneOptions.Builder().text(input).build();
    toneService.tone(toneOptions).enqueue(new ServiceCallback<ToneAnalysis>() {

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

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

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

        @Override
        public void onFailure(Exception e) {
        }
    });
}
Also used : ToneAnalysis(com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis) HashMap(java.util.HashMap) MessageResponse(com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse) ServiceCallback(com.ibm.watson.developer_cloud.http.ServiceCallback) ToneAnalyzer(com.ibm.watson.developer_cloud.tone_analyzer.v3.ToneAnalyzer) MessageOptions(com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions) Assistant(com.ibm.watson.developer_cloud.assistant.v1.Assistant)

Example 3 with Assistant

use of com.ibm.watson.assistant.v1.Assistant 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 4 with Assistant

use of com.ibm.watson.assistant.v1.Assistant in project java-sdk by watson-developer-cloud.

the class Assistant method listWorkspaces.

/**
 * List workspaces.
 *
 * <p>List the workspaces associated with a Watson Assistant service instance.
 *
 * @param listWorkspacesOptions the {@link ListWorkspacesOptions} containing the options for the
 *     call
 * @return a {@link ServiceCall} with a result of type {@link WorkspaceCollection}
 */
public ServiceCall<WorkspaceCollection> listWorkspaces(ListWorkspacesOptions listWorkspacesOptions) {
    if (listWorkspacesOptions == null) {
        listWorkspacesOptions = new ListWorkspacesOptions.Builder().build();
    }
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v1/workspaces"));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "listWorkspaces");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    builder.query("version", String.valueOf(this.version));
    if (listWorkspacesOptions.pageLimit() != null) {
        builder.query("page_limit", String.valueOf(listWorkspacesOptions.pageLimit()));
    }
    if (listWorkspacesOptions.includeCount() != null) {
        builder.query("include_count", String.valueOf(listWorkspacesOptions.includeCount()));
    }
    if (listWorkspacesOptions.sort() != null) {
        builder.query("sort", String.valueOf(listWorkspacesOptions.sort()));
    }
    if (listWorkspacesOptions.cursor() != null) {
        builder.query("cursor", String.valueOf(listWorkspacesOptions.cursor()));
    }
    if (listWorkspacesOptions.includeAudit() != null) {
        builder.query("include_audit", String.valueOf(listWorkspacesOptions.includeAudit()));
    }
    ResponseConverter<WorkspaceCollection> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<WorkspaceCollection>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) WorkspaceCollection(com.ibm.watson.assistant.v1.model.WorkspaceCollection)

Example 5 with Assistant

use of com.ibm.watson.assistant.v1.Assistant in project java-sdk by watson-developer-cloud.

the class Assistant method message.

/**
 * Get response to user input.
 *
 * <p>Send user input to a workspace and receive a response.
 *
 * <p>**Important:** This method has been superseded by the new v2 runtime API. The v2 API offers
 * significant advantages, including ease of deployment, automatic state management, versioning,
 * and search capabilities. For more information, see the
 * [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-api-overview).
 *
 * @param messageOptions the {@link MessageOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link MessageResponse}
 */
public ServiceCall<MessageResponse> message(MessageOptions messageOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(messageOptions, "messageOptions cannot be null");
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("workspace_id", messageOptions.workspaceId());
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v1/workspaces/{workspace_id}/message", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "message");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    builder.query("version", String.valueOf(this.version));
    if (messageOptions.nodesVisitedDetails() != null) {
        builder.query("nodes_visited_details", String.valueOf(messageOptions.nodesVisitedDetails()));
    }
    final JsonObject contentJson = new JsonObject();
    if (messageOptions.input() != null) {
        contentJson.add("input", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.input()));
    }
    if (messageOptions.intents() != null) {
        contentJson.add("intents", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.intents()));
    }
    if (messageOptions.entities() != null) {
        contentJson.add("entities", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.entities()));
    }
    if (messageOptions.alternateIntents() != null) {
        contentJson.addProperty("alternate_intents", messageOptions.alternateIntents());
    }
    if (messageOptions.context() != null) {
        contentJson.add("context", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.context()));
    }
    if (messageOptions.output() != null) {
        contentJson.add("output", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.output()));
    }
    if (messageOptions.userId() != null) {
        contentJson.addProperty("user_id", messageOptions.userId());
    }
    builder.bodyJson(contentJson);
    ResponseConverter<MessageResponse> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<MessageResponse>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) JsonObject(com.google.gson.JsonObject)

Aggregations

MessageResponse (com.ibm.watson.assistant.v1.model.MessageResponse)3 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)2 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 MessageInput (com.ibm.watson.assistant.v1.model.MessageInput)2 MessageOptions (com.ibm.watson.assistant.v1.model.MessageOptions)2 Assistant (com.ibm.watson.developer_cloud.assistant.v1.Assistant)2 MessageOptions (com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions)2 MessageResponse (com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse)2 HashMap (java.util.HashMap)2 JsonObject (com.google.gson.JsonObject)1 ServiceCallback (com.ibm.cloud.sdk.core.http.ServiceCallback)1 Assistant (com.ibm.watson.assistant.v1.Assistant)1 Context (com.ibm.watson.assistant.v1.model.Context)1 WorkspaceCollection (com.ibm.watson.assistant.v1.model.WorkspaceCollection)1 OutputData (com.ibm.watson.developer_cloud.assistant.v1.model.OutputData)1 ServiceCallback (com.ibm.watson.developer_cloud.http.ServiceCallback)1 ToneAnalyzer (com.ibm.watson.developer_cloud.tone_analyzer.v3.ToneAnalyzer)1 ToneAnalysis (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis)1