-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathGenerationFunctionCallSample.java
132 lines (115 loc) · 5.42 KB
/
GenerationFunctionCallSample.java
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
// 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.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 GenerationFunctionCallSample {
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 callFunctionAdd()
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("mycalc").description("calc")
.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("Call mycalc 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
GenerationParam param = GenerationParam.builder().model("qwen-max")
.messages(messages).resultFormat(ResultFormat.MESSAGE)
.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("mycalc")) {
// 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 {
callFunctionAdd();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(String.format("Exception %s", e.getMessage()));
}
System.exit(0);
}
}