Skip to content

Commit ef9bdc4

Browse files
committed
Reuse tool
1 parent 9ef8e6f commit ef9bdc4

File tree

5 files changed

+50
-57
lines changed

5 files changed

+50
-57
lines changed

sample-code/spring-app/src/main/java/com/sap/ai/sdk/app/controllers/OpenAiController.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ Object chatCompletionTools(
135135
@Nonnull
136136
Object chatCompletionToolExecution(
137137
@Nullable @RequestParam(value = "format", required = false) final String format) {
138-
final var response = service.chatCompletionToolExecution(12);
138+
final var response = service.chatCompletionToolExecution("Dubai", "°C");
139139
if ("json".equals(format)) {
140140
return response;
141141
}

sample-code/spring-app/src/main/java/com/sap/ai/sdk/app/services/OpenAiService.java

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
@Service
2929
@Slf4j
3030
public class OpenAiService {
31+
private static final ObjectMapper JACKSON = new ObjectMapper();
3132

3233
/**
3334
* Chat request to OpenAI
@@ -115,54 +116,50 @@ public OpenAiChatCompletionOutput chatCompletionTools(final int months) {
115116
}
116117

117118
/**
118-
* Executes a chat completion request to OpenAI with a tool that calculates the Fibonacci number.
119+
* Executes a chat completion request to OpenAI with a tool that calculates the weather.
119120
*
120-
* @param months The number of months to be inferred in the tool.
121+
* @param location The location to get the weather for.
122+
* @param unit The unit of temperature to use.
121123
* @return The assistant message response.
122124
*/
123125
@Nonnull
124-
public OpenAiChatCompletionOutput chatCompletionToolExecution(final int months) {
125-
record Fibonacci(int N) {
126-
public long execute() {
127-
return fib(N);
128-
}
129-
130-
private static long fib(final int n) {
131-
if (n < 2) {
132-
return n;
133-
}
134-
return fib(n - 1) + fib(n - 2);
135-
}
136-
}
137-
126+
public OpenAiChatCompletionOutput chatCompletionToolExecution(
127+
@Nonnull final String location, @Nonnull final String unit) {
138128
final var function =
139129
new OpenAiChatCompletionFunction()
140-
.setName("fibonacci")
141-
.setDescription("Calculate the Fibonacci number for given sequence index.")
130+
.setName("weather")
131+
.setDescription("Get the weather for the given location")
142132
.setParameters(
143-
Map.of("type", "object", "properties", Map.of("N", Map.of("type", "integer"))));
133+
Map.of(
134+
"type",
135+
"object",
136+
"properties",
137+
Map.of(
138+
"location", Map.of("type", "string"),
139+
"unit", Map.of("type", "string", "enum", List.of("C", "F")))));
144140
final var tool = new OpenAiChatCompletionTool().setType(FUNCTION).setFunction(function);
145141

146142
final var messages = new ArrayList<OpenAiChatMessage>();
147143
messages.add(
148144
new OpenAiChatMessage.OpenAiChatUserMessage()
149-
.addText("How many rabbits will there be after %s months?".formatted(months)));
145+
.addText("What's the weather in %s in %s?".formatted(location, unit)));
150146

151147
final var request =
152148
new OpenAiChatCompletionParameters()
153149
.addMessages(messages.toArray(OpenAiChatMessage[]::new))
154150
.setTools(List.of(tool))
155-
.setToolChoiceFunction("fibonacci");
151+
.setToolChoiceFunction("weather");
156152

157153
final var client = OpenAiClient.forModel(GPT_4O_MINI);
158154
final var initialResponse = client.chatCompletion(request);
159155

160156
final var toolCall = initialResponse.getChoices().get(0).getMessage().getToolCalls().get(0);
161-
String toolResponse;
157+
String toolResponseJson;
162158
try {
163-
final var fibonacci =
164-
new ObjectMapper().readValue(toolCall.getFunction().getArguments(), Fibonacci.class);
165-
toolResponse = String.valueOf(fibonacci.execute());
159+
final var weatherRequest =
160+
JACKSON.readValue(toolCall.getFunction().getArguments(), WeatherMethod.Request.class);
161+
final var toolResponse = new WeatherMethod().getCurrentWeather(weatherRequest);
162+
toolResponseJson = JACKSON.writeValueAsString(toolResponse);
166163
} catch (Exception e) {
167164
throw new IllegalArgumentException("Error parsing tool call arguments", e);
168165
}
@@ -173,7 +170,7 @@ private static long fib(final int n) {
173170
final var toolMessage =
174171
new OpenAiChatMessage.OpenAiChatToolMessage()
175172
.setToolCallId(toolCall.getId())
176-
.setContent(toolResponse);
173+
.setContent(toolResponseJson);
177174
messages.add(toolMessage);
178175

179176
final var finalRequest =

sample-code/spring-app/src/test/java/com/sap/ai/sdk/app/controllers/OpenAiTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,11 @@ void chatCompletionWithResource() {
104104

105105
@Test
106106
void chatCompletionToolExecution() {
107-
final var completion = service.chatCompletionToolExecution(12);
107+
final var completion = service.chatCompletionToolExecution("Dubai", "°C");
108108

109109
String content = completion.getContent();
110110

111111
assertThat(content).isNotEmpty();
112-
assertThat(content).contains("144");
112+
assertThat(content).contains("°C");
113113
}
114114
}

sample-code/spring-app/src/test/java/com/sap/ai/sdk/app/controllers/OpenAiV2Test.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,11 @@ void chatCompletionWithResource() {
105105

106106
@Test
107107
void chatCompletionToolExecution() {
108-
final var completion = service.chatCompletionToolExecution(12);
108+
final var completion = service.chatCompletionToolExecution("Dubai", "°C");
109109

110110
String content = completion.getChoices().get(0).getMessage().getContent();
111111

112112
assertThat(content).isNotEmpty();
113-
assertThat(content).contains("144");
113+
assertThat(content).contains("°C");
114114
}
115115
}

sample-code/spring-app/src/test/java/com/sap/ai/sdk/app/services/OpenAiServiceV2.java

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
@Service
3939
@Slf4j
4040
public class OpenAiServiceV2 {
41+
private static final ObjectMapper JACKSON = new ObjectMapper();
4142

4243
/**
4344
* Chat request to OpenAI
@@ -121,33 +122,28 @@ public OpenAiChatCompletionResponse chatCompletionTools(final int months) {
121122
}
122123

123124
/**
124-
* Executes a chat completion request to OpenAI with a tool that calculates the Fibonacci number.
125+
* Executes a chat completion request to OpenAI with a tool that calculates the weather.
125126
*
126-
* @param months The number of months to be inferred in the tool.
127+
* @param location The location to get the weather for.
128+
* @param unit The unit of temperature to use.
127129
* @return The assistant message response.
128130
*/
129131
@Nonnull
130-
public CreateChatCompletionResponse chatCompletionToolExecution(final int months) {
131-
132-
record Fibonacci(int n) {
133-
public long execute() {
134-
return fib(n);
135-
}
136-
137-
private static long fib(int n) {
138-
if (n < 2) {
139-
return n;
140-
}
141-
return fib(n - 1) + fib(n - 2);
142-
}
143-
}
132+
public CreateChatCompletionResponse chatCompletionToolExecution(
133+
@Nonnull final String location, @Nonnull final String unit) {
144134

145135
final var function =
146136
new FunctionObject()
147-
.name("fibonacci")
148-
.description("Calculate the Fibonacci number for given sequence index.")
137+
.name("weather")
138+
.description("Get the weather for the given location")
149139
.parameters(
150-
Map.of("type", "object", "properties", Map.of("n", Map.of("type", "integer"))));
140+
Map.of(
141+
"type",
142+
"object",
143+
"properties",
144+
Map.of(
145+
"location", Map.of("type", "string"),
146+
"unit", Map.of("type", "string", "enum", List.of("C", "F")))));
151147

152148
final var tool = new ChatCompletionTool().type(FUNCTION).function(function);
153149

@@ -156,8 +152,7 @@ private static long fib(int n) {
156152
.role(ChatCompletionRequestUserMessage.RoleEnum.USER)
157153
.content(
158154
ChatCompletionRequestUserMessageContent.create(
159-
"A pair of rabbits is placed in a field. Each month, every pair produces one new pair, starting from the second month. How many rabbits will there be after %s months?"
160-
.formatted(months)));
155+
"What's the weather in %s in %s?".formatted(location, unit)));
161156

162157
final var request =
163158
new CreateChatCompletionRequest()
@@ -170,11 +165,12 @@ private static long fib(int n) {
170165
final var initialResponse = client.chatCompletion(request);
171166

172167
final var toolCall = initialResponse.getChoices().get(0).getMessage().getToolCalls().get(0);
173-
String toolResponseContent;
168+
String toolResponseJson;
174169
try {
175-
var fibonacci =
176-
new ObjectMapper().readValue(toolCall.getFunction().getArguments(), Fibonacci.class);
177-
toolResponseContent = String.valueOf(fibonacci.execute());
170+
var weatherRequest =
171+
JACKSON.readValue(toolCall.getFunction().getArguments(), WeatherMethod.Request.class);
172+
final var toolResponse = new WeatherMethod().getCurrentWeather(weatherRequest);
173+
toolResponseJson = JACKSON.writeValueAsString(toolResponse);
178174
} catch (JsonProcessingException e) {
179175
throw new IllegalArgumentException("Error parsing tool call arguments", e);
180176
}
@@ -191,7 +187,7 @@ private static long fib(int n) {
191187
final var toolMessage =
192188
new ChatCompletionRequestToolMessage()
193189
.role(ChatCompletionRequestToolMessage.RoleEnum.TOOL)
194-
.content(ChatCompletionRequestToolMessageContent.create(toolResponseContent))
190+
.content(ChatCompletionRequestToolMessageContent.create(toolResponseJson))
195191
.toolCallId(toolCall.getId());
196192
request.addMessagesItem(toolMessage);
197193

0 commit comments

Comments
 (0)