Tools (Function Calling)
Some LLMs, in addition to generating text, can also trigger actions.
All LLMs supporting tools can be found here (see the "Tools" column).
Not all LLMs support tools equally well. The ability to understand, select, and correctly use tools depends heavily on the specific model and its capabilities. Some models may not support tools at all, while others might require careful prompt engineering or additional system instructions.
There is a concept known as "tools," or "function calling". It allows the LLM to call, when necessary, one or more available tools, usually defined by the developer. A tool can be anything: a web search, a call to an external API, or the execution of a specific piece of code, etc. LLMs cannot actually call the tool themselves; instead, they express the intent to call a specific tool in their response (instead of responding in plain text). We, as developers, should then execute this tool with the provided arguments and report back the results of the tool execution.
For example, we know that LLMs themselves are not very good at math. If your use case involves occasional math calculations, you might want to provide the LLM with a "math tool." By declaring one or multiple tools in the request to the LLM, it can then decide to call one of them if it deems it appropriate. Given a math question along with a set of math tools, the LLM might decide that to properly answer the question, it should first call one of the provided math tools.
Let's see how this works in practice (with and without tools):
An example of a message exchange without tools:
Request:
- messages:
- UserMessage:
- text: What is the square root of 475695037565?
Response:
- AiMessage:
- text: The square root of 475695037565 is approximately 689710.
Close, but not correct.
An example of a message exchange with the following tools:
@Tool("Sums 2 given numbers")
double sum(double a, double b) {
return a + b;
}
@Tool("Returns a square root of a given number")
double squareRoot(double x) {
return Math.sqrt(x);
}
Request 1:
- messages:
- UserMessage:
- text: What is the square root of 475695037565?
- tools:
- sum(double a, double b): Sums 2 given numbers
- squareRoot(double x): Returns a square root of a given number
Response 1:
- AiMessage:
- toolExecutionRequests:
- squareRoot(475695037565)
... here we are executing the squareRoot method with the "475695037565" argument and getting "689706.486532" as a result ...
Request 2:
- messages:
- UserMessage:
- text: What is the square root of 475695037565?
- AiMessage:
- toolExecutionRequests:
- squareRoot(475695037565)
- ToolExecutionResultMessage:
- text: 689706.486532
Response 2:
- AiMessage:
- text: The square root of 475695037565 is 689706.486532.
As you can see, when an LLM has access to tools, it can decide to call one of them when appropriate.
This is a very powerful feature.
In this simple example, we gave the LLM primitive math tools,
but imagine if we gave it, for example, googleSearch and sendEmail tools
and a query like "My friend wants to know recent news in the AI field. Send the short summary to friend@email.com,"
then it could find recent news using the googleSearch tool,
then summarize it and send the summary via email using the sendEmail tool.
To increase the chances of the LLM calling the right tool with the right arguments, we should provide a clear and unambiguous:
- name of the tool
- description of what the tool does and when it should be used
- description of every tool parameter
A good rule of thumb: if a human can understand the purpose of a tool and how to use it, chances are that the LLM can too.
LLMs are specifically fine-tuned to detect when to call tools and how to call them. Some models can even call multiple tools at once, for example, OpenAI.
Please note that not all models support tools. To see which models support tools, refer to the "Tools" column on this page.
Please note that tools/function calling is not the same as JSON mode.
2 levels of abstraction
LangChain4j provides two levels of abstraction for using tools:
- Low-level, using the
ChatModelandToolSpecificationAPIs - High-level, using AI Services and
@Tool-annotated Java methods
Low Level Tool API
At the low level, you can use the chat(ChatRequest) method
of the ChatModel. A similar method is also present in the StreamingChatModel.
You can specify one or more ToolSpecifications when creating the ChatRequest.
ToolSpecification is an object that contains all the information about the tool:
- The
nameof the tool - The
descriptionof the tool - The
parametersof the tool and their descriptions - The
metadataof the tool. By default, it is not sent to the LLM provider, you must explicitly specify which metadata keys should be sent when creating aChatModel. Currently, tool metadata is supported only by thelangchain4j-anthropicmodule. When tools are provided by the McpToolProvider,metadatacan contain MCP-specific entries.
It is recommended to provide as much information about the tool as possible: a clear name, a comprehensive description, and a description for each parameter, etc.
Creating Tool Specification
There are two ways to create a ToolSpecification:
- Manually
ToolSpecification toolSpecification = ToolSpecification.builder()
.name("getWeather")
.description("Returns the weather forecast for a given city")
.parameters(JsonObjectSchema.builder()
.addStringProperty("city", "The city for which the weather forecast should be returned")
.addEnumProperty("temperatureUnit", List.of("CELSIUS", "FAHRENHEIT"))
.required("city") // the required properties should be specified explicitly
.build())
.build();
You can find more information on JsonObjectSchema here.
- Using helper methods:
ToolSpecifications.toolSpecificationsFrom(Class)ToolSpecifications.toolSpecificationsFrom(Object)ToolSpecifications.toolSpecificationFrom(Method)
class WeatherTools {
@Tool("Returns the weather forecast for a given city")
String getWeather(
@P("The city for which the weather forecast should be returned") String city,
TemperatureUnit temperatureUnit
) {
...
}
}
List<ToolSpecification> toolSpecifications = ToolSpecifications.toolSpecificationsFrom(WeatherTools.class);
JSON Serialization
ToolSpecification can be serialized to JSON and deserialized back using toJson() and fromJson() methods.
This can be useful, for example, when you want to store tool specifications in a database or transfer them over the network.
String json = toolSpecification.toJson();
ToolSpecification deserialized = ToolSpecification.fromJson(json);
By default, a dedicated Jackson ObjectMapper is used for the JSON conversion.
You can provide your own implementation of ToolSpecificationJsonCodec via SPI
by implementing ToolSpecificationJsonCodecFactory and registering it
in META-INF/services/dev.langchain4j.spi.agent.tool.ToolSpecificationJsonCodecFactory.
Using ChatModel
Once you have a List<ToolSpecification>, you can call the model:
ChatRequest request = ChatRequest.builder()
.messages(UserMessage.from("What will the weather be like in London tomorrow?"))
.toolSpecifications(toolSpecifications)
.build();
ChatResponse response = model.chat(request);
AiMessage aiMessage = response.aiMessage();
If the LLM decides to call the tool, the returned AiMessage will contain data
in the toolExecutionRequests field.
In this case, AiMessage.hasToolExecutionRequests() will return true.
Depending on the LLM, it can contain one or multiple ToolExecutionRequest objects
(some LLMs support calling multiple tools in parallel).
Each ToolExecutionRequest should contain:
- The
idof the tool call. Please note that some LLM providers (e.g., Google, Ollama) may omit this ID. - The
nameof the tool to be called, for example:getWeather - The
arguments, for example:{ "city": "London", "temperatureUnit": "CELSIUS" }
You'll need to manually execute the tool(s) using information from the ToolExecutionRequest(s).
If you want to send the result of the tool execution back to the LLM,
you need to create a ToolExecutionResultMessage (one for each ToolExecutionRequest)
and send it along with all previous messages:
String result = "It is expected to rain in London tomorrow.";
ToolExecutionResultMessage toolExecutionResultMessage = ToolExecutionResultMessage.from(toolExecutionRequest, result);
ChatRequest request2 = ChatRequest.builder()
.messages(List.of(userMessage, aiMessage, toolExecutionResultMessage))
.toolSpecifications(toolSpecifications)
.build();
ChatResponse response2 = model.chat(request2);
Multimodal Tool Results
ToolExecutionResultMessage can also carry non-text content such as images.
Instead of using text(), you can use the builder with contents():
ToolExecutionResultMessage toolExecutionResultMessage = ToolExecutionResultMessage.builder()
.id(toolExecutionRequest.id())
.toolName(toolExecutionRequest.name())
.contents(
TextContent.from("Here is the photo"),
ImageContent.from(Image.builder()
.base64Data(base64Data)
.mimeType("image/png")
.build())
)
.build();
Not all LLM providers support multimodal tool results. See Returning Images and Multimodal Content for details on provider support.
Using StreamingChatModel
Once you have a List<ToolSpecification>, you can call the model:
ChatRequest request = ChatRequest.builder()
.messages(UserMessage.from("What will the weather be like in London tomorrow?"))
.toolSpecifications(toolSpecifications)
.build();
model.chat(request, new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse) {
System.out.println("onPartialResponse: " + partialResponse);
}
@Override
public void onPartialToolCall(PartialToolCall partialToolCall) {
System.out.println("onPartialToolCall: " + partialToolCall);
}
@Override
public void onCompleteToolCall(CompleteToolCall completeToolCall) {
System.out.println("onCompleteToolCall: " + completeToolCall);
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
System.out.println("onCompleteResponse: " + completeResponse);
}
@Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
If the LLM decides to call the tool, the onPartialToolCall(PartialToolCall) callback
will typically be called multiple times before an onCompleteToolCall(CompleteToolCall) callback
is eventually called, indicating that streaming for that tool call is finished.
Please note that not all LLM providers stream partial tool calls.
Some providers (e.g., Bedrock, Google, Mistral, Ollama) return only complete tool calls.
In those cases, onPartialToolCall callback won't be invoked - only onCompleteToolCall will be called.
Here's an example of what streaming of a single tool call might look like:
onPartialToolCall(index = 0, id = "call_abc", name = "get_weather", partialArguments = "{\"")
onPartialToolCall(index = 0, id = "call_abc", name = "get_weather", partialArguments = "city")
onPartialToolCall(index = 0, id = "call_abc", name = "get_weather", partialArguments = ""\":\"")
onPartialToolCall(index = 0, id = "call_abc", name = "get_weather", partialArguments = "London")
onPartialToolCall(index = 0, id = "call_abc", name = "get_weather", partialArguments = "\"}")
onCompleteToolCall(index = 0, id = "call_abc", name = "get_weather", arguments = "{\"city\":\"London\"}")
If the LLM initiates multiple tool calls, the index will increment, allowing you to correlate
the different PartialToolCalls with each other and with the final CompleteToolCall.
When complete response streaming is over and onCompleteResponse(ChatResponse) is invoked,
the AiMessage inside the ChatResponse will contain all the tool calls that occurred during streaming.
High Level Tool API
At a high level of abstraction, you can annotate any Java method with the @Tool annotation
and specify them when creating AI Service.
AI Service will automatically convert such methods into ToolSpecifications
and include them in the request for each interaction with the LLM.
When the LLM decides to call the tool, the AI Service will automatically execute the appropriate method,
and the return value of the method (if any) will be sent back to the LLM.
You can find implementation details in DefaultToolExecutor.
A few tool examples:
@Tool("Searches Google for relevant URLs, given the query")
public List<String> searchGoogle(@P("search query") String query) {
return googleSearchService.search(query);
}
@Tool("Returns the content of a web page, given the URL")
public String getWebPageContent(@P("URL of the page") String url) {
Document jsoupDocument = Jsoup.connect(url).get();
return jsoupDocument.body().text();
}
Tool Method Limitations
Methods annotated with @Tool:
- can be either static or non-static
- can have any visibility (public, private, etc.).
Tool Method Parameters
Methods annotated with @Tool can accept any number of parameters of various types:
- Primitive types:
int,double, etc - Object types:
String,Integer,Double, etc - Custom POJOs (can contain nested POJOs)
enums- Polymorphic types (sealed interfaces/classes or types annotated with Jackson
@JsonSubTypes/@JsonTypeInfo) — see Polymorphic Tool Parameters List<T>/Set<T>whereTis one of the above-mentioned typesMap<K,V>(you need to manually specify the types ofKandVin the parameter description with@P)
Methods without parameters are supported as well.
Parameter Name
By default, if the name attribute of @P is not specified, the parameter name is obtained via reflection.
However, without the -parameters javac option, reflection returns generic names like arg0, arg1, etc.
The semantic meaning of the parameter is lost, which may confuse the LLM.
Setting name in @P is useful in two cases:
- Missing
-parametersjavac option — to avoid genericarg0/arg1names that the LLM would otherwise see. Note that frameworks like Quarkus and Spring enable-parametersby default, so the actual method parameter names are preserved and you typically do not need to setnamewhen using those frameworks. - Custom name for the LLM — when you want the LLM to see a different parameter name than the one in the source code (for example, to match a specific API contract or to provide a more descriptive name).
Example:
@Tool
void getTemperature(
@P("Temperature value") double value,
@P("Unit of temperature") Optional<String> unit) {
...
}
Required and Optional
By default, all tool method parameters are considered required.
This means the parameter is listed in the JSON schema's required array sent to the LLM,
instructing it to produce a value.
A parameter can be made optional by annotating it with @P(required = false):
@Tool
String getTemperature(String location, @P(required = false) Unit unit) {
...
}
Alternatively, you can declare the parameter as Optional<T>:
@Tool
String getTemperature(String location, Optional<Unit> unit) {
...
}
Fields and sub-fields of complex parameters are also considered required by default.
You can make a field optional by annotating it with @JsonProperty(required = false):
record User(String name, @JsonProperty(required = false) String email) {}
@Tool
void add(User user) {
...
}
Please note that when used with structured outputs, all fields and sub-fields are considered optional by default.
The required flag controls the JSON schema sent to the LLM (required parameters are listed
in the schema's required array). The LLM is expected to honor this, but in practice it can
disregard the schema and omit an argument anyway.
In LangChain4j 1.x, this is detected only for primitive parameters (int, long, boolean, …) — a
missing primitive triggers the ToolArgumentsErrorHandler (see Error Handling
below). Missing object parameters are not validated: null is passed to the
@Tool-annotated method even though the schema marked the parameter as required.
We are planning to remove this asymmetry in LangChain4j 2.0 so that all required arguments are validated uniformly. If this planned change would affect your use case, please open an issue so we can hear your feedback before it lands.
If you want a real fallback instead of null (or instead of an error for primitive parameters), use
@P(defaultValue = ...).
Default Parameter Values
@P(defaultValue = "...") declares a value that LangChain4j substitutes when the LLM
omits the argument. It's the simplest way to make a parameter optional and supply a
sensible fallback that your tool method receives.
enum SortBy { RELEVANCE, DATE, RATING }
@Tool
List<Article> searchArticles(
String query,
@P(defaultValue = "10") int limit,
@P(defaultValue = "[\"en\"]") List<String> languages,
@P(defaultValue = "RELEVANCE") SortBy sortBy
) {
// When the LLM omits them:
// 'limit' -> 10
// 'languages' -> ["en"]
// 'sortBy' -> SortBy.RELEVANCE
}
Setting defaultValue implies optional in the JSON schema — the parameter is not
listed in the schema's required array, regardless of @P(required). The LLM is told
it may omit the argument; if it does, LangChain4j fills in the default before invoking
your method.
Supported types:
| Type | Format | Example |
|---|---|---|
String | used verbatim | defaultValue = "USD" |
| Primitive / boxed primitive | type-specific conversion | "10", "3.14", "true" |
enum | enum constant name | defaultValue = "EUR" |
UUID | UUID.fromString | "550e8400-e29b-41d4-a716-446655440000" |
BigDecimal, BigInteger | numeric literal | "1.5", "100" |
List<T> / Set<T> / array | JSON array | "[\"a\",\"b\"]", "[1,2,3]" |
Map<K,V> | JSON object | "{\"a\":1,\"b\":2}" |
| POJOs (including nested) | JSON object | "{\"name\":\"Klaus\",\"age\":42}" |
The default value string is parsed at AI Service registration time. If it cannot be
converted into the parameter's type, AI Service construction fails immediately with
IllegalConfigurationException, naming the offending parameter — typos are caught at
startup rather than on the first LLM call.
Defaults only apply to absence, not to wrong values. If the LLM provides an argument
that fails type coercion (e.g. "banana" for an int), the coercion error propagates as
usual — the default is not used as a fallback.
Defaults are re-parsed on every invocation, so a tool that mutates a defaulted
List/Map/POJO does not contaminate later calls:
@Tool
void process(@P(defaultValue = "[\"a\",\"b\"]") List<String> tags) {
tags.add("processed"); // safe — next invocation still receives ["a","b"]
}
Restrictions (rejected with IllegalConfigurationException at registration time):
defaultValuecannot be combined withOptional<T>—Optionalalready encodes "absent"; pick one mechanism.defaultValuecannot be set on LangChain4j-injected parameters (@ToolMemoryId,InvocationContext, etc.) — they don't come from the LLM.
Polymorphic Tool Parameters
A tool parameter can be a polymorphic type — a base type whose concrete subtype is decided
by the LLM at call time. Sealed interfaces and sealed classes work without annotations;
plain abstract classes and interfaces must declare their subtypes with Jackson's
@JsonSubTypes.
The schema sent to the LLM contains an anyOf over the permitted subtypes, each with a
discriminator property (defaulting to "type") so the LLM can communicate which concrete
type it produced; LangChain4j deserializes the LLM's argument into the right subtype
before invoking your tool method.
This works for the polymorphic type as a parameter, for List<T> / Set<T> of polymorphic
types, and for polymorphic types nested inside another POJO parameter.
Sealed interfaces and classes — no annotations needed:
sealed interface Animal permits Dog, Cat {}
record Dog(String name, String breed) implements Animal {}
record Cat(String name, boolean indoor) implements Animal {}
class AnimalRegistry {
@Tool("Registers a single animal")
void registerAnimal(Animal animal) { /* dispatched to Dog or Cat */ }
@Tool("Registers a batch of animals")
void registerAnimals(List<Animal> animals) { /* mixed Dog / Cat */ }
@Tool("Registers an owner with their pet")
void registerOwner(Owner owner) { /* Owner.pet is dispatched */ }
}
record Owner(String name, Animal pet) {}
Jackson @JsonSubTypes / @JsonTypeInfo are also supported and let you decouple wire
names from Java class names:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind")
@JsonSubTypes({