Skip to content

Add Tool Calling to Java SDK #1481

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

Open
wants to merge 81 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
46035e9
Use Java Bean for connection details and add more tests (#1317)
artur-ciocanu Apr 22, 2025
8f72e81
Update CONTRIBUTING.md
siri-varma Apr 29, 2025
bb848ed
Bump codecov/codecov-action from 5.4.0 to 5.4.2 (#1318)
dependabot[bot] Apr 22, 2025
bc30545
Fix URL building logic (#1320)
artur-ciocanu Apr 29, 2025
19ae63d
Generate updated javadocs for 1.14.1
dapr-bot Apr 30, 2025
a31c09e
Add Conversation AI to Java SDK (#1235)
siri-varma May 1, 2025
164feef
Add docs for usage of Jobs SDK (#1323)
siri-varma May 6, 2025
f31c24f
Use dapr/durabletask-java (#1336)
cicoyle May 8, 2025
8112471
Update master version to 1.16.0-SNAPSHOT
dapr-bot May 8, 2025
0618c5d
Renaming and exposing connection details (#1341)
artur-ciocanu May 13, 2025
e085019
[Master] Fix Vulnerabilities (#1354)
cicoyle May 13, 2025
93fb9e9
Feat Add TLS & mTLS support for gRPC with root CA and insecure mode (…
cicoyle May 14, 2025
3cac8b5
Fix the issue with retries not happening correctly for Activities and…
siri-varma May 15, 2025
04148bc
1.5.4 (#1375)
cicoyle May 16, 2025
653f816
Bump codecov/codecov-action from 5.4.2 to 5.4.3 (#1379)
dependabot[bot] May 19, 2025
8aa0c68
Bump fossas/fossa-action from 1.6.0 to 1.7.0 (#1380)
dependabot[bot] May 19, 2025
7974ff3
Fix component spec parsing (#1370)
iddeepak May 19, 2025
26e59ae
chore: Add grpc keepalives (#1382)
javier-aliaga May 21, 2025
4a6404e
Fix : Typo in code comments (#1381)
iddeepak May 21, 2025
fa77030
Spring boot workflow patterns examples with mechanical markdown and t…
salaboy May 21, 2025
48291c5
System Properties + Env Var Docs (#1384)
cicoyle May 21, 2025
4bb15dc
Updating docs to have spring boot 3.x banner and not hardcoded deps (…
salaboy May 22, 2025
e4b7e4e
Cleaup Test Dependencies (#1332)
siri-varma May 23, 2025
ffaf13f
chore: New task execution task id test (#1352)
javier-aliaga May 28, 2025
74b39c6
Revert "chore: New task execution task id test (#1352)" (#1389)
javier-aliaga May 28, 2025
882462a
1.5.5 (#1390)
cicoyle May 28, 2025
c4929bb
Add Documentation for Conversation AI SDK (#1387)
siri-varma May 29, 2025
23c7e88
Cleanup Spring Dependencies (#1334)
siri-varma May 29, 2025
fed43ab
Bump org.springframework:spring-context in /dapr-spring (#1394)
dependabot[bot] May 29, 2025
0cd6add
Compensation example for Workflows (#1333)
cicoyle May 29, 2025
4d87b50
Adding remote endpoint request from inside activity with retry (#1388)
salaboy May 31, 2025
d874025
Bump org.springframework:spring-context in /dapr-spring (#1398)
dependabot[bot] Jun 3, 2025
322ec30
Grouping IT tests per API surface (#1401)
artur-ciocanu Jun 5, 2025
2dff670
Ensure OTEL version from examples aligns with SDK and ITs (#1403)
artur-ciocanu Jun 5, 2025
fc36e73
chore: Support configuration for max grpc inbound message (#1411)
javier-aliaga Jun 10, 2025
1fcc754
Adding Support for Suspend / Resume Workflows (#1405)
salaboy Jun 11, 2025
f291658
Add retry handler support (#1412)
TheForbiddenAi Jun 11, 2025
d7e7205
Pull out createTimer logic (#1419)
cicoyle Jun 11, 2025
0dd37f9
Make sure there no multiple empty lines and every file ends with a ne…
siri-varma Jun 12, 2025
89167f1
Automated Header Checks (#1416)
siri-varma Jun 12, 2025
a316dd7
Bump org.springframework:spring-web in /dapr-spring (#1424)
dependabot[bot] Jun 16, 2025
0b3ca70
Aligning Spring Boot and SpringFramework versions (#1427)
salaboy Jun 26, 2025
982b287
Update pom.xml to have testcontainers 1.21.3 (#1436)
salaboy Jun 30, 2025
85f82f2
Adding examples to Spring Boot (duration, zoneddatetime and suspend/r…
salaboy Jul 14, 2025
41894a5
Bump org.apache.commons:commons-lang3 from 3.9 to 3.18.0 (#1446)
dependabot[bot] Jul 14, 2025
4191fff
Update dapr docs for Hugo upgrade (#1443)
marcduiker Jul 14, 2025
e674141
Adds note about workflow start time (#1444)
JoshVanL Jul 14, 2025
ffebf97
Migrate PubSub removing flaky test (#1407)
mcruzdev Jul 14, 2025
3c9bee7
supporting spring boot property for API TOKEN on workflow interceptor…
salaboy Jul 15, 2025
8a6f839
Supporting placement and scheduler custom images (#1450)
salaboy Jul 15, 2025
3f04df7
chore: Replace ossrh url (#1454)
javier-aliaga Jul 16, 2025
e3fcacc
Upgrading to 1.15.7 (#1458)
salaboy Jul 18, 2025
2443058
updating sched api on DaprContainer (#1462)
salaboy Jul 22, 2025
0438f36
Adding app health check parameters (#1465)
salaboy Jul 23, 2025
90e6531
Add note about the dapr.client.* properties (#1467)
mcruzdev Jul 23, 2025
795e1cd
conversation ai
siri-varma Aug 3, 2025
c465471
Fix pom
siri-varma Aug 3, 2025
e7e8fde
Fix pom
siri-varma Aug 3, 2025
fbc4ce0
fix things
siri-varma Aug 6, 2025
118bd69
Fix things
siri-varma Aug 6, 2025
220e54b
docs: Add gRPC response settings to properties documentation (#1482)
MyMirelHub Aug 4, 2025
9b94509
Generate updated javadocs for 1.14.2
dapr-bot Aug 4, 2025
48ad25e
chore: Use 1.16.0 rc 2 (#1463)
javier-aliaga Aug 4, 2025
7c3afb3
Add Failure Policy for Jobs SDK (#1448)
siri-varma Aug 5, 2025
4063b1c
Merge branch 'master' into users/svegiraju/conversation-ai
siri-varma Aug 6, 2025
683beae
Fix things
siri-varma Aug 6, 2025
4c13261
Fix things
siri-varma Aug 6, 2025
5718bd4
Fix things
siri-varma Aug 6, 2025
3834a0d
Fix things
siri-varma Aug 6, 2025
3c79ce8
Fix things
siri-varma Aug 6, 2025
57fad34
fxi things
siri-varma Aug 7, 2025
7946fee
Add better tests
siri-varma Aug 7, 2025
ace90e4
Add examples
siri-varma Aug 7, 2025
392c286
Add examples
siri-varma Aug 7, 2025
e2bdffd
Update README.md
siri-varma Aug 7, 2025
d812b65
Update UserMessageDemo.java
siri-varma Aug 7, 2025
398802a
Update UserMessageDemo.java
siri-varma Aug 7, 2025
d4650ad
Merge branch 'master' into users/svegiraju/conversation-ai
siri-varma Aug 11, 2025
196270e
Merge branch 'master' into users/svegiraju/conversation-ai
siri-varma Aug 15, 2025
7886540
Merge branch 'master' into users/svegiraju/conversation-ai
siri-varma Aug 16, 2025
8ef726c
Merge branch 'master' into users/svegiraju/conversation-ai
siri-varma Aug 18, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* 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.AssistantMessage;
import io.dapr.client.domain.ConversationInputAlpha2;
import io.dapr.client.domain.ConversationMessage;
import io.dapr.client.domain.ConversationMessageContent;
import io.dapr.client.domain.ConversationRequestAlpha2;
import io.dapr.client.domain.ConversationResponseAlpha2;
import io.dapr.client.domain.ConversationResultAlpha2;
import io.dapr.client.domain.ConversationResultChoices;
import io.dapr.client.domain.ConversationToolCalls;
import io.dapr.client.domain.ConversationToolCallsOfFunction;
import io.dapr.client.domain.SystemMessage;
import io.dapr.client.domain.ToolMessage;
import io.dapr.client.domain.UserMessage;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

public class AssistantMessageDemo {
/**
* The main method to demonstrate conversation AI with assistant messages and conversation history.
*
* @param args Input arguments (unused).
*/
public static void main(String[] args) {
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
System.out.println("Demonstrating Conversation AI with Assistant Messages and Conversation History");

// Create a conversation history with multiple message types
List<ConversationMessage> conversationHistory = new ArrayList<>();

// 1. System message to set context
SystemMessage systemMessage = new SystemMessage(List.of(
new ConversationMessageContent("You are a helpful assistant that can help with weather queries.")
));
systemMessage.setName("WeatherBot");
conversationHistory.add(systemMessage);

// 2. Initial user greeting
UserMessage greeting = new UserMessage(List.of(
new ConversationMessageContent("Hello! I need help with weather information.")
));
greeting.setName("User123");
conversationHistory.add(greeting);

// 3. Assistant response with tool call
AssistantMessage assistantResponse = new AssistantMessage(
List.of(new ConversationMessageContent("I'll help you with weather information. Let me check the weather for you.")),
List.of(new ConversationToolCalls(
new ConversationToolCallsOfFunction("get_weather", "{\"location\": \"San Francisco\", \"unit\": \"fahrenheit\"}")
))
);
assistantResponse.setName("WeatherBot");
conversationHistory.add(assistantResponse);

// 4. Tool response (simulating weather API response)
ToolMessage toolResponse = new ToolMessage(List.of(
new ConversationMessageContent("{\"temperature\": \"72F\", \"condition\": \"sunny\", \"humidity\": \"65%\"}")
));
toolResponse.setName("weather_api");
conversationHistory.add(toolResponse);

// 5. Current user question
UserMessage currentQuestion = new UserMessage(List.of(
new ConversationMessageContent("Based on that weather data, should I wear a jacket today?")
));
currentQuestion.setName("User123");
conversationHistory.add(currentQuestion);

// Create conversation input with the full history
ConversationInputAlpha2 conversationInput = new ConversationInputAlpha2(conversationHistory);
conversationInput.setScrubPii(false);

// Create the conversation request
ConversationRequestAlpha2 request = new ConversationRequestAlpha2("echo", List.of(conversationInput))
.setContextId("assistant-demo-context")
.setTemperature(0.8d);

// Send the request
System.out.println("Sending conversation with assistant messages and history...");
System.out.println("Conversation includes:");
System.out.println("- System message (context setting)");
System.out.println("- User greeting");
System.out.println("- Assistant response with tool call");
System.out.println("- Tool response with weather data");
System.out.println("- User follow-up question");

Mono<ConversationResponseAlpha2> responseMono = client.converseAlpha2(request);
ConversationResponseAlpha2 response = responseMono.block();

// Process and display the response
if (response != null && response.getOutputs() != null && !response.getOutputs().isEmpty()) {
ConversationResultAlpha2 result = response.getOutputs().get(0);
if (result.getChoices() != null && !result.getChoices().isEmpty()) {
ConversationResultChoices choice = result.getChoices().get(0);

if (choice.getMessage() != null && choice.getMessage().getContent() != null) {
System.out.printf("Assistant Response: %s%n", choice.getMessage().getContent());
}

// Check for additional tool calls in the response
if (choice.getMessage() != null && choice.getMessage().getToolCalls() != null) {
System.out.println("Assistant requested additional tool calls:");
choice.getMessage().getToolCalls().forEach(toolCall -> {
System.out.printf("Tool: %s, Arguments: %s%n",
toolCall.getFunction().getName(),
toolCall.getFunction().getArguments());
});
}
}
}

System.out.println("Assistant message demonstration completed.");

} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

This file was deleted.

41 changes: 31 additions & 10 deletions examples/src/main/java/io/dapr/examples/conversation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,30 +45,51 @@ Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initi
### 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.
`UserMessageDemo.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 {
public class UserMessageDemo {
/**
* The main method to start the client.
*
* @param args Input arguments (unused).
*/
public static void main(String[] args) {
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
Map<Property<?>, String> overrides = Map.of(
Properties.HTTP_PORT, "3500",
Properties.GRPC_PORT, "50001"
);

try (DaprPreviewClient client = new DaprClientBuilder().withPropertyOverrides(overrides).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");
// Create user message with content
UserMessage userMessage = new UserMessage(List.of(new ConversationMessageContent("Hello How are you? "
+ "This is the my number 672-123-4567")));

// Create conversation input with the user message
ConversationInputAlpha2 daprConversationInput = new ConversationInputAlpha2(List.of(userMessage));

// Component name is the name provided in the metadata block of the conversation.yaml file.
Mono<ConversationResponse> responseMono = client.converse(new ConversationRequest("echo",
Mono<ConversationResponseAlpha2> responseMono = client.converseAlpha2(new ConversationRequestAlpha2("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());
.setScrubPii(true)
.setTemperature(1.1d));

ConversationResponseAlpha2 response = responseMono.block();

// Extract and print the conversation result
if (response != null && response.getOutputs() != null && !response.getOutputs().isEmpty()) {
ConversationResultAlpha2 result = response.getOutputs().get(0);
if (result.getChoices() != null && !result.getChoices().isEmpty()) {
ConversationResultChoices choice = result.getChoices().get(0);
if (choice.getMessage() != null && choice.getMessage().getContent() != null) {
System.out.printf("Conversation output: %s", choice.getMessage().getContent());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
Expand All @@ -88,7 +109,7 @@ 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
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.UserMessageDemo
```

<!-- END_STEP -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.ConversationInputAlpha2;
import io.dapr.client.domain.ConversationMessageContent;
import io.dapr.client.domain.ConversationRequestAlpha2;
import io.dapr.client.domain.ConversationResponseAlpha2;
import io.dapr.client.domain.ConversationResultAlpha2;
import io.dapr.client.domain.ConversationResultChoices;
import io.dapr.client.domain.ConversationTools;
import io.dapr.client.domain.ConversationToolsFunction;
import io.dapr.client.domain.SystemMessage;
import io.dapr.client.domain.UserMessage;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ToolsCallDemo {
/**
* The main method to demonstrate conversation AI with tools/function calling.
*
* @param args Input arguments (unused).
*/
public static void main(String[] args) {
try (DaprPreviewClient client = new DaprClientBuilder().buildPreviewClient()) {
System.out.println("Demonstrating Conversation AI with Tools/Function Calling");

// Create system message to set context
SystemMessage systemMessage = new SystemMessage(List.of(
new ConversationMessageContent("You are a helpful weather assistant. Use the provided tools to get weather information.")
));

// Create user message asking for weather
UserMessage userMessage = new UserMessage(List.of(
new ConversationMessageContent("What's the weather like in San Francisco?")
));

// Create conversation input with messages
ConversationInputAlpha2 conversationInput = new ConversationInputAlpha2(List.of(systemMessage, userMessage));

// Define function parameters for the weather tool
Map<String, Object> functionParams = new HashMap<>();
functionParams.put("location", "string");
functionParams.put("unit", "string");

// Create the weather function definition
ConversationToolsFunction weatherFunction = new ConversationToolsFunction("get_current_weather", functionParams);
weatherFunction.setDescription("Get the current weather for a specified location");

// Create the tool wrapper
ConversationTools weatherTool = new ConversationTools(weatherFunction);

// Create the conversation request with tools
ConversationRequestAlpha2 request = new ConversationRequestAlpha2("echo", List.of(conversationInput))
.setContextId("weather-demo-context")
.setTemperature(0.7d)
.setTools(List.of(weatherTool));

// Send the request
System.out.println("Sending request to AI with weather tool available...");
Mono<ConversationResponseAlpha2> responseMono = client.converseAlpha2(request);
ConversationResponseAlpha2 response = responseMono.block();

// Process and display the response
if (response != null && response.getOutputs() != null && !response.getOutputs().isEmpty()) {
ConversationResultAlpha2 result = response.getOutputs().get(0);
if (result.getChoices() != null && !result.getChoices().isEmpty()) {
ConversationResultChoices choice = result.getChoices().get(0);

// Check if the AI wants to call a tool
if (choice.getMessage() != null && choice.getMessage().getToolCalls() != null) {
System.out.println("AI requested to call tools:");
choice.getMessage().getToolCalls().forEach(toolCall -> {
System.out.printf("Tool: %s, Arguments: %s%n",
toolCall.getFunction().getName(),
toolCall.getFunction().getArguments());
});
}

// Display the message content if available
if (choice.getMessage() != null && choice.getMessage().getContent() != null) {
System.out.printf("AI Response: %s%n", choice.getMessage().getContent());
}
}
}

System.out.println("Tools call demonstration completed.");

} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Loading
Loading