Thursday, 17 July 2025

Tool Method Return Types in LangChain4j: void, String, and JSON Explained

In LangChain4j, the @Tool annotation allows methods to be exposed for interaction with language models (LLMs). It's important to understand how different return types behave when these methods are invoked. This ensures developers can design tools that communicate effectively with the LLM.

 

When using the @Tool annotation in LangChain4j, it's essential to consider the return type of your annotated methods. Here’s how different return types are handled:

 

·      void Return Type: If a method returns void, the LLM receives the string "Success" upon successful execution. This is useful for actions where no response data is necessary.

 

·      String Return Type: If the method returns a String, the returned string is passed directly to the LLM without any transformation. This is ideal for clear, plain-text feedback or responses.

 

·      Other Return Types (e.g., Objects, Lists, Maps): Any return type other than void or String is automatically serialized to a JSON string before being sent to the LLM. This enables structured data exchange and richer interactions.

 

 

In summary, design your @Tool methods with the return type in mind to control how results are communicated to the LLM. Whether it's a simple confirmation or structured data, LangChain4j ensures seamless integration with language models.

 

Example

@Tool("Take radians as input and return the equivalant value in degrees")
public Double radiansToDegrees(double radians) {
  System.out.println("***Converting Radians to Degrees***");
  return Math.toDegrees(radians);
}

 

Above snippet define a tool that returns Double value.

   

Previous                                                    Next                                                    Home

No comments:

Post a Comment