Skip to content

feat: Add support for generic argument types in tool callbacks #3082

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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,102 @@
/*
* Copyright 2023-2024 the original author or 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
*
* https://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 org.springframework.ai.anthropic.client;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.anthropic.AnthropicTestConfiguration;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(classes = AnthropicTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "ANTHROPIC_API_KEY", matches = ".+")
class ChatClientToolsWithGenericArgumentTypesIT {

private static final Logger logger = LoggerFactory.getLogger(ChatClientToolsWithGenericArgumentTypesIT.class);

public static Map<String, Object> arguments = new ConcurrentHashMap<>();

public static AtomicLong callCounter = new AtomicLong(0);

@BeforeEach
void beforeEach() {
arguments.clear();
}

@Autowired
ChatModel chatModel;

@Test
void toolWithGenericArgumentTypes() {
// @formatter:off
String response = ChatClient.create(this.chatModel).prompt()
.user("Turn light red in the living room and the kitchen. Please group the romms with the same color in a single tool call.")
.tools(new TestToolProvider())
.call()
.content();
// @formatter:on

logger.info("Response: {}", response);

assertThat(arguments).containsEntry("living room", LightColor.RED);
assertThat(arguments).containsEntry("kitchen", LightColor.RED);

assertThat(callCounter.get()).isEqualTo(1);
}

record Room(String name) {
}

enum LightColor {

RED, GREEN, BLUE

}

public static class TestToolProvider {

@Tool(description = "Change the lamp color in a room.")
public void changeRoomLightColor(
@ToolParam(description = "List of rooms to change the ligth color for") List<Room> rooms,
@ToolParam(description = "light color to change to") LightColor color) {

logger.info("Change light color in rooms: {} to color: {}", rooms, color);

for (Room room : rooms) {
arguments.put(room.name(), color);
}
callCounter.incrementAndGet();
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2023-2024 the original author or 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
*
* https://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 org.springframework.ai.openai.chat.client;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.openai.OpenAiTestConfiguration;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(classes = OpenAiTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
@ActiveProfiles("logging-test")
class ChatClientToolsWithGenericArgumentTypesIT {

private static final Logger logger = LoggerFactory.getLogger(ChatClientToolsWithGenericArgumentTypesIT.class);

public static Map<String, Object> arguments = new ConcurrentHashMap<>();

public static AtomicLong callCounter = new AtomicLong(0);

@BeforeEach
void beforeEach() {
arguments.clear();
}

@Autowired
ChatModel chatModel;

@Test
void toolWithGenericArgumentTypes() {
// @formatter:off
String response = ChatClient.create(this.chatModel).prompt()
.user("Turn light red in the living room and the kitchen. Please group the romms with the same color in a single tool call.")
.tools(new TestToolProvider())
.call()
.content();
// @formatter:on

logger.info("Response: {}", response);

assertThat(arguments).containsEntry("living room", LightColor.RED);
assertThat(arguments).containsEntry("kitchen", LightColor.RED);

assertThat(callCounter.get()).isEqualTo(1);
}

record Room(String name) {
}

enum LightColor {

RED, GREEN, BLUE

}

public static class TestToolProvider {

@Tool(description = "Change the lamp color in a room.")
public void changeRoomLightColor(
@ToolParam(description = "List of rooms to change the ligth color for") List<Room> rooms,
@ToolParam(description = "light color to change to") LightColor color) {

logger.info("Change light color in rooms: {} to color: {}", rooms, color);

for (Room room : rooms) {
arguments.put(room.name(), color);
}
callCounter.incrementAndGet();
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

@SpringBootTest(classes = OpenAiTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
@ActiveProfiles("logging-test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,23 @@ private Object[] buildMethodArguments(Map<String, Object> toolInputArguments, @N
return toolContext;
}
Object rawArgument = toolInputArguments.get(parameter.getName());
return buildTypedArgument(rawArgument, parameter.getType());
return buildTypedArgument(rawArgument, parameter.getParameterizedType());
}).toArray();
}

@Nullable
private Object buildTypedArgument(@Nullable Object value, Class<?> type) {
private Object buildTypedArgument(@Nullable Object value, Type type) {
if (value == null) {
return null;
}
return JsonParser.toTypedObject(value, type);

if (type instanceof Class<?>) {
return JsonParser.toTypedObject(value, (Class<?>) type);
}

// For generic types, use the fromJson method that accepts Type
String json = JsonParser.toJson(value);
return JsonParser.fromJson(json, type);
}

@Nullable
Expand Down
Loading