Skip to content

Add Conversation AI to Java SDK #1235

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 27 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5421ac1
Conversation first commit
siri-varma Mar 6, 2025
61aa209
Add unit tests
siri-varma Mar 7, 2025
93c13d4
change ai to conv
siri-varma Mar 14, 2025
cd87ca5
Move to single module
siri-varma Mar 18, 2025
00a0280
Remove module
siri-varma Mar 18, 2025
90a68ea
Add Integration tests
siri-varma Mar 18, 2025
fcb3177
Update sdk-tests/src/test/java/io/dapr/it/testcontainers/DaprConversa…
siri-varma Apr 12, 2025
9bb922e
Fix things
siri-varma Apr 22, 2025
1d6f7c7
Address comments
siri-varma Apr 22, 2025
f646a26
Import tag
siri-varma Apr 22, 2025
6498cd1
Address comments
siri-varma Apr 22, 2025
e29c06b
Make common config
siri-varma Apr 22, 2025
38e3f82
Address comments
siri-varma Apr 22, 2025
9e23ce1
fix constant
siri-varma Apr 22, 2025
3b6b0a5
fix constant
siri-varma Apr 22, 2025
b795391
Merge branch 'master' into users/svegiraju/conversation-api-2
siri-varma Apr 22, 2025
c0c3f63
fix constant
siri-varma Apr 23, 2025
6f54ac2
Merge branch 'users/svegiraju/conversation-api-2' of https://github.c…
siri-varma Apr 23, 2025
6e303fa
fix s
siri-varma Apr 23, 2025
655ef70
Fix things
siri-varma Apr 23, 2025
bff8932
Fix things
siri-varma Apr 24, 2025
6a1e09a
Fix things
siri-varma Apr 24, 2025
e618070
Make common config
siri-varma Apr 24, 2025
eb77e88
Merge branch 'master' into users/svegiraju/conversation-api-2
siri-varma Apr 29, 2025
f994c8a
Update README.md
siri-varma Apr 29, 2025
ce7067a
Update README.md
siri-varma Apr 30, 2025
af02465
Merge branch 'master' into users/svegiraju/conversation-api-2
cicoyle Apr 30, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ jobs:
mm.py ./src/main/java/io/dapr/examples/jobs/README.md
env:
DOCKER_HOST: ${{steps.setup_docker.outputs.sock}}
- name: Validate conversation ai example
working-directory: ./examples
run: |
mm.py ./src/main/java/io/dapr/examples/conversation/README.md
env:
DOCKER_HOST: ${{steps.setup_docker.outputs.sock}}
- name: Validate invoke http example
working-directory: ./examples
run: |
Expand Down
7 changes: 7 additions & 0 deletions examples/components/conversation/conversation.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: echo
spec:
type: conversation.echo
version: v1
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2021 The Dapr Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
limitations under the License.
*/

package io.dapr.examples.conversation;

import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprPreviewClient;
import io.dapr.client.domain.ConversationInput;
import io.dapr.client.domain.ConversationRequest;
import io.dapr.client.domain.ConversationResponse;
import reactor.core.publisher.Mono;

import java.util.List;

public class DemoConversationAI {
/**
* The main method to start the client.
*
* @param args Input arguments (unused).
*/
public static void main(String[] args) {
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
System.out.println("Sending the following input to LLM: Hello How are you? This is the my number 672-123-4567");

ConversationInput daprConversationInput = new ConversationInput("Hello How are you? "
+ "This is the my number 672-123-4567");

// Component name is the name provided in the metadata block of the conversation.yaml file.
Mono<ConversationResponse> responseMono = client.converse(new ConversationRequest("echo",
List.of(daprConversationInput))
.setContextId("contextId")
.setScrubPii(true).setTemperature(1.1d));
ConversationResponse response = responseMono.block();
System.out.printf("Conversation output: %s", response.getConversationOutputs().get(0).getResult());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
114 changes: 114 additions & 0 deletions examples/src/main/java/io/dapr/examples/conversation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
## Manage Dapr via the Conversation API

This example provides the different capabilities provided by Dapr Java SDK for Conversation. For further information about Conversation APIs please refer to [this link](https://docs.dapr.io/developing-applications/building-blocks/conversation/conversation-overview/)

### Using the Conversation API

The Java SDK exposes several methods for this -
* `client.converse(...)` for conversing with an LLM through Dapr.

## Pre-requisites

* [Dapr CLI](https://docs.dapr.io/getting-started/install-dapr-cli/).
* Java JDK 11 (or greater):
* [Microsoft JDK 11](https://docs.microsoft.com/en-us/java/openjdk/download#openjdk-11)
* [Oracle JDK 11](https://www.oracle.com/technetwork/java/javase/downloads/index.html#JDK11)
* [OpenJDK 11](https://jdk.java.net/11/)
* [Apache Maven](https://maven.apache.org/install.html) version 3.x.

### Checking out the code

Clone this repository:

```sh
git clone https://github.com/dapr/java-sdk.git
cd java-sdk
```

Then build the Maven project:

```sh
# make sure you are in the `java-sdk` directory
mvn install
```

Then get into the examples directory:

```sh
cd examples
```

### Initialize Dapr

Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.

### Running the example

This example uses the Java SDK Dapr client in order to **Converse** with an LLM.
`DemoConversationAI.java` is the example class demonstrating these features.
Kindly check [DaprPreviewClient.java](https://github.com/dapr/java-sdk/blob/master/sdk/src/main/java/io/dapr/client/DaprPreviewClient.java) for a detailed description of the supported APIs.

```java
public class DemoConversationAI {
/**
* The main method to start the client.
*
* @param args Input arguments (unused).
*/
public static void main(String[] args) {
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
System.out.println("Sending the following input to LLM: Hello How are you? This is the my number 672-123-4567");

ConversationInput daprConversationInput = new ConversationInput("Hello How are you? "
+ "This is the my number 672-123-4567");

// Component name is the name provided in the metadata block of the conversation.yaml file.
Mono<ConversationResponse> responseMono = client.converse(new ConversationRequest("echo",
List.of(daprConversationInput))
.setContextId("contextId")
.setScrubPii(true).setTemperature(1.1d));
ConversationResponse response = responseMono.block();
System.out.printf("Conversation output: %s", response.getConversationOutpus().get(0).getResult());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
```

Use the following command to run this example-

<!-- STEP
name: Run Demo Conversation Client example
expected_stdout_lines:
- "== APP == Conversation output: Hello How are you? This is the my number <ISBN>"
background: true
output_match_mode: substring
sleep: 10
-->

```bash
dapr run --resources-path ./components/conversation --app-id myapp --app-port 8080 --dapr-http-port 3500 --dapr-grpc-port 51439 --log-level debug -- java -jar target/dapr-java-sdk-examples-exec.jar io.dapr.examples.conversation.DemoConversationAI
```

<!-- END_STEP -->

### Sample output
```
== APP == Conversation output: Hello How are you? This is the my number <ISBN>
```
### Cleanup

To stop the app, run (or press CTRL+C):

<!-- STEP

name: Cleanup
-->

```bash
dapr stop --app-id myapp
```

<!-- END_STEP -->

Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2021 The Dapr Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
limitations under the License.
*/

package io.dapr.it.testcontainers;

import io.dapr.client.DaprPreviewClient;
import io.dapr.client.domain.ConversationInput;
import io.dapr.client.domain.ConversationRequest;
import io.dapr.client.domain.ConversationResponse;
import io.dapr.testcontainers.Component;
import io.dapr.testcontainers.DaprContainer;
import io.dapr.testcontainers.DaprLogLevel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.Network;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import static io.dapr.it.testcontainers.ContainerConstants.DAPR_RUNTIME_IMAGE_TAG;

@SpringBootTest(
webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {
DaprPreviewClientConfiguration.class,
TestConversationApplication.class
}
)
@Testcontainers
@Tag("testcontainers")
public class DaprConversationIT {

private static final Network DAPR_NETWORK = Network.newNetwork();
private static final Random RANDOM = new Random();
private static final int PORT = RANDOM.nextInt(1000) + 8000;

@Container
private static final DaprContainer DAPR_CONTAINER = new DaprContainer(DAPR_RUNTIME_IMAGE_TAG)
.withAppName("conversation-dapr-app")
.withComponent(new Component("echo", "conversation.echo", "v1", new HashMap<>()))
.withNetwork(DAPR_NETWORK)
.withDaprLogLevel(DaprLogLevel.DEBUG)
.withLogConsumer(outputFrame -> System.out.println(outputFrame.getUtf8String()))
.withAppChannelAddress("host.testcontainers.internal")
.withAppPort(PORT);

/**
* Expose the Dapr port to the host.
*
* @param registry the dynamic property registry
*/
@DynamicPropertySource
static void daprProperties(DynamicPropertyRegistry registry) {
registry.add("dapr.http.endpoint", DAPR_CONTAINER::getHttpEndpoint);
registry.add("dapr.grpc.endpoint", DAPR_CONTAINER::getGrpcEndpoint);
registry.add("server.port", () -> PORT);
}

@Autowired
private DaprPreviewClient daprPreviewClient;

@BeforeEach
public void setUp(){
org.testcontainers.Testcontainers.exposeHostPorts(PORT);
}

@Test
public void testConversationSDKShouldHaveSameOutputAndInput() {
ConversationInput conversationInput = new ConversationInput("input this");
List<ConversationInput> conversationInputList = new ArrayList<>();
conversationInputList.add(conversationInput);

ConversationResponse response =
this.daprPreviewClient.converse(new ConversationRequest("echo", conversationInputList)).block();

Assertions.assertEquals("", response.getContextId());
Assertions.assertEquals("input this", response.getConversationOutputs().get(0).getResult());
}

@Test
public void testConversationSDKShouldScrubPIIWhenScrubPIIIsSetInRequestBody() {
List<ConversationInput> conversationInputList = new ArrayList<>();
conversationInputList.add(new ConversationInput("input this [email protected]"));
conversationInputList.add(new ConversationInput("input this +12341567890"));

ConversationResponse response =
this.daprPreviewClient.converse(new ConversationRequest("echo", conversationInputList)
.setScrubPii(true)).block();

Assertions.assertEquals("", response.getContextId());
Assertions.assertEquals("input this <EMAIL_ADDRESS>",
response.getConversationOutputs().get(0).getResult());
Assertions.assertEquals("input this <PHONE_NUMBER>",
response.getConversationOutputs().get(1).getResult());
}

@Test
public void testConversationSDKShouldScrubPIIOnlyForTheInputWhereScrubPIIIsSet() {
List<ConversationInput> conversationInputList = new ArrayList<>();
conversationInputList.add(new ConversationInput("input this [email protected]"));
conversationInputList.add(new ConversationInput("input this +12341567890").setScrubPii(true));

ConversationResponse response =
this.daprPreviewClient.converse(new ConversationRequest("echo", conversationInputList)).block();

Assertions.assertEquals("", response.getContextId());
Assertions.assertEquals("input this [email protected]",
response.getConversationOutputs().get(0).getResult());
Assertions.assertEquals("input this <PHONE_NUMBER>",
response.getConversationOutputs().get(1).getResult());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
@SpringBootTest(
webEnvironment = WebEnvironment.RANDOM_PORT,
classes = {
TestDaprJobsConfiguration.class,
DaprPreviewClientConfiguration.class,
TestJobsApplication.class
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,17 @@
package io.dapr.it.testcontainers;

import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprClientImpl;
import io.dapr.client.DaprPreviewClient;
import io.dapr.config.Properties;
import io.dapr.config.Property;
import io.dapr.serializer.DefaultObjectSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class TestDaprJobsConfiguration {
public class DaprPreviewClientConfiguration {
@Bean
public DaprPreviewClient daprPreviewClient(
@Value("${dapr.http.endpoint}") String daprHttpEndpoint,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2024 The Dapr Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
limitations under the License.
*/

package io.dapr.it.testcontainers;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestConversationApplication {

public static void main(String[] args) {
SpringApplication.run(TestConversationApplication.class, args);
}
}
Loading
Loading