public static Tool convertMethodToTool()

in spring-ai-alibaba-graph/spring-ai-alibaba-graph-example/src/main/java/com/alibaba/cloud/ai/example/graph/bigtool/utils/MethodUtils.java [56:132]


	public static Tool convertMethodToTool(Method method) {
		if (method == null) {
			return null;
		}

		try {
			// Get method name and parameter information
			String methodName = method.getName();
			Class<?>[] paramTypes = method.getParameterTypes();

			// Get method Javadoc description - try different sources in layers
			String javadoc = getMethodJavadoc(method);

			// Create method description
			StringBuilder description = new StringBuilder();

			if (javadoc != null && !javadoc.isEmpty()) {
				// Use retrieved Javadoc
				description.append(javadoc);
			}
			else {
				// If Javadoc can't be retrieved, create a basic description
				description.append(methodName).append(": ");
				description.append("A method that accepts ");

				if (paramTypes.length == 0) {
					description.append("no parameters");
				}
				else {
					for (int i = 0; i < paramTypes.length; i++) {
						if (i > 0) {
							description.append(", ");
						}
						description.append(getEnglishTypeName(paramTypes[i]));
					}
				}
			}

			// Add parameter type information as supplement
			description.append(". Parameter types: ");
			if (paramTypes.length == 0) {
				description.append("none");
			}
			else {
				for (int i = 0; i < paramTypes.length; i++) {
					if (i > 0) {
						description.append(", ");
					}
					description.append(paramTypes[i].getSimpleName());
				}
			}

			// Add return type information
			description.append(", return type: ").append(method.getReturnType().getSimpleName());

			// Create tool object
			return new Tool(methodName, description.toString(), args -> {
				try {
					// Ensure parameter count matches
					if (args.length != paramTypes.length) {
						throw new IllegalArgumentException(
								"Expected " + paramTypes.length + " arguments, got " + args.length);
					}

					// Execute method
					return method.invoke(null, args);
				}
				catch (Exception e) {
					throw new RuntimeException("Error invoking method: " + methodName, e);
				}
			}, method.getParameterTypes());

		}
		catch (Exception e) {
			return null;
		}
	}