FCP是一个基于注解的Java工具库,只需使用@Function
和@Property
注解,即可轻松将Java方法转换为大模型可识别的FunctionCall格式,并且还支持方法的快速回调。
- 通过注解将Java方法解析为大模型的函数调用格式
- 自动执行大模型返回的函数调用
- JDK 11 或更高版本
<dependency>
<groupId>io.github.azirzsk</groupId>
<artifactId>function-call-processor</artifactId>
<version>1.0.0</version>
</dependency>
implementation 'io.github.azirzsk:function-call-processor:1.0.0'
将Java对象中的方法解析为大模型可识别的FunctionCall格式:
public class Calculator {
@Function(desc = "将两个数字相加")
public int add(@Property(desc = "第一个数字") int a,
@Property(desc = "第二个数字") int b) {
return a + b;
}
@Function(desc = "将两个数字相乘")
public int multiply(@Property(desc = "第一个数字") int x,
@Property(desc = "第二个数字") int y) {
return x * y;
}
}
然后使用FCP解析这个类:
// 创建FCP实例
FCP fcp = FCP.create();
// 传入需要解析的对象
Calculator calculator = new Calculator();
String functionCallJson = fcp.parse(calculator);
解析后得到的JSON格式如下:
[
{
"type": "function",
"function": {
"name": "add",
"description": "将两个数字相加",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "integer",
"description": "第一个数字"
},
"b": {
"type": "integer",
"description": "第二个数字"
}
},
"required": [
"a",
"b"
]
}
}
},
{
"type": "function",
"function": {
"name": "multiply",
"description": "将两个数字相乘",
"parameters": {
"type": "object",
"properties": {
"x": {
"type": "integer",
"description": "第一个数字"
},
"y": {
"type": "integer",
"description": "第二个数字"
}
},
"required": [
"x",
"y"
]
}
}
}
]
接收大模型返回的FunctionCall并执行对应的方法。
// 创建FCP实例(如果已创建可以复用)
FCP fcp = FCP.create();
// 传入需要解析的对象(如果已传入可以复用)
Calculator calculator = new Calculator();
fcp.parse(calculator);
// 大模型返回的tool_calls格式
String llmResponse = """
{
"tool_calls": [
{
"id": "call_123456",
"type": "function",
"function": {
"name": "add",
"arguments": "{\\"a\\": 1, \\"b\\": 2}"
}
}
]
}
""";
// 从大模型响应中提取函数名和参数
String functionName = "add"; // 从llmResponse中解析function.name
String argumentsJson = "{\"a\": 1, \"b\": 2}"; // 从llmResponse中解析function.arguments
// 执行函数调用
Object result = fcp.functionCall(functionName, argumentsJson);
System.out.println(result); // 输出: 3