Watson APIs Java SDK

repository·master·Indexed 20 days ago

https://github.com/watson-developer-cloud/java-sdk

A client library for interacting with IBM Watson services, including Assistant (v1 and v2), Discovery (v2), and Natural Language Understanding. The SDK supports multiple authentication methods such as IAM, Basic Auth, Bearer Token, and Cloud Pak for Data. It provides modular dependencies for Maven and Gradle to allow for full library installation or specific service modules.

Tokens
9.6K
Snippets
31
Records
32
Agent score
69%

What's inside Watson APIs Java SDK

  1. Make asynchronous API calls with enqueue() and reactiveRequest()

    master

    While execute() is used for synchronous calls, the SDK provides two methods for asynchronous execution:

    1. enqueue(): Uses a ServiceCallback<T> to handle the response or failure in a background thread.
    2. reactiveRequest(): Returns an RxJava Single<Response<T>>, allowing for reactive programming patterns.
    // Using enqueue() with a callback
    service.listEnvironments().enqueue(new ServiceCallback<ListEnvironmentsResponse>() {
      @Override
      public void onResponse(Response<ListEnvironmentsResponse> response) {
        System.out.println("We did it! " + response);
      }
    
      @Override
      public void onFailure(Exception e) {
        System.out.println("Whoops...");
      }
    });
    
    // Using reactiveRequest() with RxJava
    Single<Response<ListEnvironmentsResponse>> observableRequest
      = service.listEnvironments().reactiveRequest();
    
    observableRequest
      .subscribeOn(Schedulers.single())
      .subscribe(response -> System.out.println("We did it with s~t~r~e~a~m~s! " + response));
  2. Install the Text to Speech SDK

    master

    To use the Watson Text to Speech service in your Java project, add the following dependency to your build configuration file.

    ##### Maven
    ```xml
    <dependency>
      <groupId>com.ibm.watson</groupId>
      <artifactId>text-to-speech</artifactId>
      <version>16.2.0</version>
    </dependency>
    Gradle
    'com.ibm.watson:text-to-speech:16.2.0'
  3. Authenticate with Cloud Pak for Data

    master

    When authenticating with Cloud Pak for Data, you must:

    1. Use the CloudPakForDataAuthenticator.
    2. Explicitly set the service URL using service.setServiceUrl("<service CP4D URL>").
    3. Disable SSL verification using HttpConfigOptions if required.
    // Letting the SDK manage the token
    Authenticator authenticator = new CloudPakForDataAuthenticator.Builder()
                .url("<CP4D token exchange base URL>")
                .username("<username>")
                .password("<password>")
                .disableSSLVerification(true)
                .headers(null)
                .build();
    
    Discovery service = new Discovery("2023-03-31", authenticator);
    service.setServiceUrl("<service CP4D URL>");
  4. Install the Speech to Text SDK

    master

    Add the Speech to Text dependency to your project using Maven or Gradle. Ensure you use version 16.2.0 to match the current SDK release.

    ##### Maven
    ```xml
    <dependency>
      <groupId>com.ibm.watson</groupId>
      <artifactId>speech-to-text</artifactId>
      <version>16.2.0</version>
    </dependency>
    Gradle
    'com.ibm.watson:speech-to-text:16.2.0'
  5. Install the Assistant SDK

    master

    Add the Watson Assistant dependency to your project using Maven or Gradle to use the service for identifying intents, entities, and conducting conversations.

    ##### Maven
    
    ```xml
    <dependency>
      <groupId>com.ibm.watson</groupId>
      <artifactId>assistant</artifactId>
      <version>16.2.0</version>
    </dependency>
    Gradle
    'com.ibm.watson:assistant:16.2.0'
  6. Install the Natural Language Understanding SDK

    master

    To use the Watson Natural Language Understanding service in your Java project, add the following dependency to your build configuration file.

    ##### Maven
    ```xml
    <dependency>
      <groupId>com.ibm.watson</groupId>
      <artifactId>natural-language-understanding</artifactId>
      <version>16.2.0</version>
    </dependency>
    Gradle
    'com.ibm.watson:natural-language-understanding:16.2.0'
  7. Use the SDK in a Docker environment for testing

    master

    You can use the provided Dockerfile and pom.xml to create a containerized environment for testing SDK issues or running integration tests. This setup is pre-configured to pull the latest ibm-watson package.

    Setup Steps

    1. Install Docker: Ensure Docker is installed on your system (Mac or Windows).
    2. Prepare your code:
      • Simple tests: Edit the existing DockerTest.java file directly. The environment is configured to run this file by default.
      • Custom tests: Add your own .java files to the project. If you use your own files, you must update the execution command in the Dockerfile to point to your specific main class:
        RUN mvn -e exec:java -Dexec.mainClass="com.ibm.<MAIN_CLASS>"
      • Update POM: If your custom project uses a different Group ID, update the pom.xml accordingly.
    3. Build the image: Run the following command from the directory containing the Dockerfile:
      docker build --tag=<your-tag> .
    docker build --tag=<your-tag> .
  8. Install the Watson APIs Java SDK

    master

    You can install the SDK using Maven or Gradle. You can either install the full library containing all services or install specific service modules to reduce your dependency footprint.

    Maven

    To include all services:

    <dependency>
    	<groupId>com.ibm.watson</groupId>
    	<artifactId>ibm-watson</artifactId>
    	<version>16.2.0</version>
    </dependency>

    To include only Discovery:

    <dependency>
    	<groupId>com.ibm.watson</groupId>
    	<artifactId>discovery</artifactId>
    	<version>16.2.0</version>
    </dependency>

    Gradle

    To include all services:

    'com.ibm.watson:ibm-watson:16.2.0'

    To include only Assistant:

    'com.ibm.watson:assistant:16.2.0'
    <!-- Maven All Services -->
    <dependency>
    	<groupId>com.ibm.watson</groupId>
    	<artifactId>ibm-watson</artifactId>
    	<version>16.2.0</version>
    </dependency>
    
    <!-- Gradle All Services -->
    'com.ibm.watson:ibm-watson:16.2.0'
  9. Use Assistant v1

    master

    Assistant v1 uses a workspaceId to manage conversations. You must use the com.ibm.watson.assistant.v1.Assistant import. To maintain context across multiple messages, extract the Context object from the MessageResponse and pass it into the MessageOptions of the subsequent request.

    // make sure to use the Assistant v1 import!
    import com.ibm.watson.assistant.v1.Assistant;
    
    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();
    MessageResponse response = service.message(options).execute().getResult();
    System.out.println(response);
  10. Authenticate using a credential file

    master

    The easiest way to authenticate is by using an ibm-credentials.env file. You can download this file from the Manage tab of your service instance in the IBM Cloud Dashboard.

    The SDK automatically searches for this file in:

    1. Your system's home directory
    2. The top-level directory of your project

    If you have multiple services, you can combine their credentials into a single ibm-credentials.env file.

    To use a custom file path, set the IBM_CREDENTIALS_FILE environment variable.

    // If ibm-credentials.env is in the home directory or project root,
    // no authentication configuration is needed in code.
    Discovery service = new Discovery("2023-03-31");