|
| 1 | +package com.genexus.springboot; |
| 2 | + |
| 3 | +import com.genexus.diagnostics.core.ILogger; |
| 4 | +import com.genexus.specific.java.Connect; |
| 5 | +import com.genexus.specific.java.LogManager; |
| 6 | +import org.springframework.ai.tool.ToolCallbackProvider; |
| 7 | +import org.springframework.ai.tool.method.MethodToolCallbackProvider; |
| 8 | +import org.springframework.ai.tool.annotation.Tool; |
| 9 | +import org.reflections.Reflections; |
| 10 | + |
| 11 | +import java.lang.reflect.Method; |
| 12 | +import java.util.Set; |
| 13 | + |
| 14 | +public class GXUtils { |
| 15 | + public static final ILogger logger = com.genexus.diagnostics.core.LogManager.getLogger(GXUtils.class); |
| 16 | + |
| 17 | + public static ToolCallbackProvider operationsTools(String packageName) { |
| 18 | + Connect.init(); |
| 19 | + LogManager.initialize("."); |
| 20 | + |
| 21 | + Reflections reflections = new Reflections( |
| 22 | + new org.reflections.util.ConfigurationBuilder() |
| 23 | + .forPackages(packageName) |
| 24 | + .addScanners(org.reflections.scanners.Scanners.MethodsAnnotated) |
| 25 | + ); |
| 26 | + |
| 27 | + Set<Method> toolMethods = reflections.getMethodsAnnotatedWith(Tool.class); |
| 28 | + |
| 29 | + MethodToolCallbackProvider.Builder builder = MethodToolCallbackProvider.builder(); |
| 30 | + |
| 31 | + // Keep track of classes that have already been added |
| 32 | + Set<Class<?>> processedClasses = new java.util.HashSet<>(); |
| 33 | + |
| 34 | + for (Method method : toolMethods) { |
| 35 | + Class<?> clazz = method.getDeclaringClass(); |
| 36 | + |
| 37 | + // Skip if we've already processed this class |
| 38 | + if (processedClasses.contains(clazz)) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + Object instance = clazz.getConstructor(int.class).newInstance(-1); |
| 44 | + builder.toolObjects(instance); |
| 45 | + processedClasses.add(clazz); |
| 46 | + |
| 47 | + Tool toolAnnotation = method.getAnnotation(Tool.class); |
| 48 | + logger.debug(String.format("Registered tool: %s - %s", |
| 49 | + toolAnnotation.name().isEmpty() ? method.getName() : toolAnnotation.name(), |
| 50 | + toolAnnotation.description())); |
| 51 | + } catch (Exception e) { |
| 52 | + logger.error("Error instantiating tool class: " + clazz.getName(), e); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (!toolMethods.isEmpty()) |
| 57 | + return builder.build(); |
| 58 | + |
| 59 | + return null; |
| 60 | + } |
| 61 | +} |
0 commit comments