-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathGenerationToolChoice.java
More file actions
267 lines (232 loc) · 11.7 KB
/
GenerationToolChoice.java
File metadata and controls
267 lines (232 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright (c) Alibaba, Inc. and its affiliates.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput.Choice;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolCallBase;
import com.alibaba.dashscope.tools.ToolCallFunction;
import com.alibaba.dashscope.tools.ToolChoice;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
public class GenerationToolChoice {
public class AddFunctionTool {
private int left;
private int right;
public AddFunctionTool(int left, int right) {
this.left = left;
this.right = right;
}
public int call() {
return left + right;
}
}
public static void disableToolCall()
throws NoApiKeyException, ApiException, InputRequiredException {
// create jsonschema generator
SchemaGeneratorConfigBuilder configBuilder =
new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
// generate jsonSchema of function.
ObjectNode jsonSchema = generator.generateSchema(AddFunctionTool.class);
// call with tools of function call, jsonSchema.toString() is jsonschema String.
FunctionDefinition fd = FunctionDefinition.builder().name("add").description("add two number")
.parameters(JsonUtils.parseString(jsonSchema.toString()).getAsJsonObject()).build();
// build system message
Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
.content("You are a helpful assistant. When asked a question, use tools wherever possible.")
.build();
// user message to call function.
Message userMsg =
Message.builder().role(Role.USER.getValue()).content("Add 32393 and 88909").build();
// messages to store message request and response.
List<Message> messages = new ArrayList<>();
messages.addAll(Arrays.asList(systemMsg, userMsg));
// create generation call parameter, disable tools
GenerationParam param = GenerationParam.builder().model(Generation.Models.QWEN_MAX)
.messages(messages).resultFormat(ResultFormat.MESSAGE).toolChoice("none")
.tools(Arrays.asList(ToolFunction.builder().function(fd).build())).build();
// call the Generation
Generation gen = new Generation();
GenerationResult result = gen.call(param);
// print the result.
System.out.println(JsonUtils.toJson(result));
// process the response
for (Choice choice : result.getOutput().getChoices()) {
// add the assistant message to list for next Generation call.
messages.add(choice.getMessage());
// should no tool call.
assert result.getOutput().getChoices().get(0).getMessage().getToolCalls() == null;
}
}
public static void forceCallFunctionAdd()
throws NoApiKeyException, ApiException, InputRequiredException {
// create jsonschema generator
SchemaGeneratorConfigBuilder configBuilder =
new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
// generate jsonSchema of function.
ObjectNode jsonSchema = generator.generateSchema(AddFunctionTool.class);
// call with tools of function call, jsonSchema.toString() is jsonschema String.
FunctionDefinition fd = FunctionDefinition.builder().name("add").description("add two number")
.parameters(JsonUtils.parseString(jsonSchema.toString()).getAsJsonObject()).build();
// build system message
Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
.content("You are a helpful assistant. When asked a question, use tools wherever possible.")
.build();
// user message to call function.
Message userMsg =
Message.builder().role(Role.USER.getValue()).content("Add 32393 and 88909").build();
// messages to store message request and response.
List<Message> messages = new ArrayList<>();
messages.addAll(Arrays.asList(systemMsg, userMsg));
ToolFunction toolFunction =
ToolFunction.builder().function(FunctionDefinition.builder().name("add").build()).build();
// create generation call parameter
GenerationParam param = GenerationParam.builder().model(Generation.Models.QWEN_MAX)
.messages(messages).resultFormat(ResultFormat.MESSAGE).toolChoice(toolFunction)
.tools(Arrays.asList(ToolFunction.builder().function(fd).build())).build();
// call the Generation
Generation gen = new Generation();
GenerationResult result = gen.call(param);
// print the result.
System.out.println(JsonUtils.toJson(result));
// process the response
for (Choice choice : result.getOutput().getChoices()) {
// add the assistant message to list for next Generation call.
messages.add(choice.getMessage());
// check if we need call tool.
if (result.getOutput().getChoices().get(0).getMessage().getToolCalls() != null) {
// iterator the tool calls
for (ToolCallBase toolCall : result.getOutput().getChoices().get(0).getMessage()
.getToolCalls()) {
// get function call.
if (toolCall.getType().equals("function")) {
// get function call name and argument, both String.
String functionName = ((ToolCallFunction) toolCall).getFunction().getName();
String functionArgument = ((ToolCallFunction) toolCall).getFunction().getArguments();
if (functionName.equals("add")) {
// Create the function object.
AddFunctionTool addFunction =
JsonUtils.fromJson(functionArgument, AddFunctionTool.class);
// call function.
int sum = addFunction.call();
// create the tool message
Message toolResultMessage = Message.builder().role("tool")
.content(String.valueOf(sum)).toolCallId(toolCall.getId()).build();
// add the tool message to messages list.
messages.add(toolResultMessage);
System.out.println(sum);
}
}
}
}
}
// new Generation call with messages include tool result.
param.setMessages(messages);
result = gen.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void parallelToolCalls()
throws NoApiKeyException, ApiException, InputRequiredException {
// create jsonschema generator
SchemaGeneratorConfigBuilder configBuilder =
new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
// generate jsonSchema of function.
ObjectNode jsonSchema = generator.generateSchema(AddFunctionTool.class);
// call with tools of function call, jsonSchema.toString() is jsonschema String.
FunctionDefinition fd = FunctionDefinition.builder().name("add").description("add two number")
.parameters(JsonUtils.parseString(jsonSchema.toString()).getAsJsonObject()).build();
// build system message
Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
.content("You are a helpful assistant. When asked a question, use tools wherever possible.")
.build();
// user message to call function.
Message userMsg =
Message.builder().role(Role.USER.getValue()).content("Add 1234 and 4321, Add 2345 and 5432").build();
// messages to store message request and response.
List<Message> messages = new ArrayList<>();
messages.addAll(Arrays.asList(systemMsg, userMsg));
ToolFunction toolFunction =
ToolFunction.builder().function(FunctionDefinition.builder().name("add").build()).build();
// create generation call parameter
GenerationParam param = GenerationParam.builder().model(Generation.Models.QWEN_MAX)
.messages(messages).resultFormat(ResultFormat.MESSAGE).toolChoice(toolFunction)
.tools(Arrays.asList(ToolFunction.builder().function(fd).build()))
.parallelToolCalls(true)
.build();
// call the Generation
Generation gen = new Generation();
GenerationResult result = gen.call(param);
// print the result.
System.out.println(JsonUtils.toJson(result));
// process the response
for (Choice choice : result.getOutput().getChoices()) {
// add the assistant message to list for next Generation call.
messages.add(choice.getMessage());
// check if we need call tool.
if (result.getOutput().getChoices().get(0).getMessage().getToolCalls() != null) {
// iterator the tool calls
for (ToolCallBase toolCall : result.getOutput().getChoices().get(0).getMessage()
.getToolCalls()) {
// get function call.
if (toolCall.getType().equals("function")) {
// get function call name and argument, both String.
String functionName = ((ToolCallFunction) toolCall).getFunction().getName();
String functionArgument = ((ToolCallFunction) toolCall).getFunction().getArguments();
if (functionName.equals("add")) {
// Create the function object.
AddFunctionTool addFunction =
JsonUtils.fromJson(functionArgument, AddFunctionTool.class);
// call function.
int sum = addFunction.call();
// create the tool message
Message toolResultMessage = Message.builder().role("tool")
.content(String.valueOf(sum)).toolCallId(toolCall.getId()).build();
// add the tool message to messages list.
messages.add(toolResultMessage);
System.out.println(sum);
}
}
}
}
}
// new Generation call with messages include tool result.
param.setMessages(messages);
result = gen.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
// disableToolCall();
// forceCallFunctionAdd();
parallelToolCalls();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(String.format("Exception %s", e.getMessage()));
}
System.exit(0);
}
}