Skip to content

Commit ac5f107

Browse files
committed
Add getFunctionsAsTools() to easily turn functions into tool messages
1 parent 76f5ac6 commit ac5f107

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

service/src/main/java/com/theokanning/openai/service/FunctionExecutor.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,16 @@ public List<ChatFunction> getFunctions() {
138138
return new ArrayList<>(FUNCTIONS.values());
139139
}
140140

141+
public List<ChatTool> getFunctionsAsTools() {
142+
return FUNCTIONS.values().stream()
143+
.map(function -> {
144+
ChatTool tool = new ChatTool();
145+
tool.setFunction(function);
146+
return tool;
147+
})
148+
.collect(Collectors.toList());
149+
}
150+
141151
public void setFunctions(List<ChatFunction> functions) {
142152
this.FUNCTIONS.clear();
143153
functions.forEach(f -> this.FUNCTIONS.put(f.getName(), f));

service/src/test/java/com/theokanning/openai/service/ChatCompletionTest.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -308,8 +308,6 @@ void createChatCompletionWithToolFunctions() {
308308
.executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, 25, "sunny"))
309309
.build());
310310
final FunctionExecutor functionExecutor = new FunctionExecutor(functions);
311-
final ChatTool tool = new ChatTool();
312-
tool.setFunction(functionExecutor.getFunctions().get(0));
313311
final List<ChatMessage> messages = new ArrayList<>();
314312
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a helpful assistant.");
315313
final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "What is the weather in Monterrey, Nuevo León?");
@@ -320,7 +318,7 @@ void createChatCompletionWithToolFunctions() {
320318
.builder()
321319
.model("gpt-3.5-turbo-0613")
322320
.messages(messages)
323-
.tools(List.of(tool))
321+
.tools(functionExecutor.getFunctionsAsTools())
324322
.toolChoice("auto")
325323
.n(1)
326324
.maxTokens(100)
@@ -364,7 +362,7 @@ void createChatCompletionWithToolFunctions() {
364362
.builder()
365363
.model("gpt-3.5-turbo-0613")
366364
.messages(messages)
367-
.tools(List.of(tool))
365+
.tools(functionExecutor.getFunctionsAsTools())
368366
.toolChoice("auto")
369367
.n(1)
370368
.maxTokens(100)

0 commit comments

Comments
 (0)