Thursday, 17 July 2025

Tool Method Parameters in LangChain4j: Required, Optional, and Complex Types Explained

When building AI agents using LangChain4j, understanding how to correctly define tool method parameters is important. Whether you're dealing with simple types, complex nested POJOs, or recursive structures, knowing how to make these parameters required or optional can greatly influence how the LLM interprets and utilizes your tools.

This guide explains essentials of method parameter support in LangChain4j, including how to work with various data types and customize parameter behavior for optimal LLM integration.

 

Supported Parameter Types

You can define tool methods with any number of parameters. These parameters can be of the following types:

 

·      Primitive types: such as int, double, boolean, etc.

·      Wrapper and object types: including Integer, Double, String, etc.

·      Custom POJOs (Plain Old Java Objects): These can include nested structures for more complex input data.

·      Enumerations (enums): Useful for predefined constant sets.

·      Collections:

·      List<T> and Set<T> where T is one of the supported primitive/object/POJO/enum types.

·      Map<K, V> where both key (K) and value (V) types must be explicitly defined using the @P annotation in the method parameter description.

 

You can also define tool methods without any parameters.

 

Required vs Optional Parameters

By default, all parameters in a tool method are required. This means the LLM is expected to generate a value for each parameter when calling the tool.

 

To make a parameter optional, annotate it with @P(required = false).

@Tool
public void search(String personName, @P(required = false) String hobbies) {
    // logic here
}

When using custom objects or nested POJOs, all fields are also treated as required by default. To mark specific fields as optional, use Jackson's @JsonProperty(required = false).

public class User {
    private String name;

    @JsonProperty(required = false)
    private String nickname;
}

Recursive Structures

LangChain4j currently supports recursive parameters, such as a class containing a reference to a list of its own type (e.g., an Employee class with Set<Employee> reportees; as a property). Right now it is only supported when using OpenAI models.

 

By carefully structuring your tool methods and parameter definitions, you can effectively use  the LLM to interact with your backend more accurately. Whether you're working with basic inputs or designing rich, nested data structures, LangChain4j provides the annotations and flexibility you need to build robust AI-driven tools.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment