Provides and generates LangChain4j tool and function calling patterns: annotates methods as tools with @Tool, configures tool executors, registers tools with AiServices, validates tool parameters, and handles tool execution errors. Use when building AI agents that call tools, define function specifications, manage tool responses, or integrate external APIs with LLM-driven applications.
Provides and generates LangChain4j tool and function calling patterns: annotates methods as tools with @Tool, configures tool executors, registers tools with AiServices, validates tool parameters, and handles tool execution errors. Use when building AI agents that call tools, define function specifications, manage tool responses, or integrate external APIs with LLM-driven applications.
allowed-tools
Read, Write, Edit, Bash, Glob, Grep, WebFetch
LangChain4j Tool & Function Calling Patterns
Provides patterns for annotating methods as tools, configuring tool executors, registering tools with AI services, validating parameters, and handling tool execution errors in LangChain4j applications.
Overview
LangChain4j uses the @Tool annotation to expose Java methods as callable functions for AI agents. The AiServices builder registers tools with a chat model, enabling LLMs to perform actions beyond text generation: database queries, API calls, calculations, and business system integrations. Parameters use @P for descriptions that guide the LLM.
When to Use
Building AI agents that call external tools (weather, stocks, database queries)
Defining function specifications for LLM tool use (@Tool, @P annotations)
Registering and managing tool sets with AiServices.builder().tools()
Handling tool execution errors, timeouts, and hallucinated tool names
Implementing context-aware tools that inject user state via @ToolMemoryId
Configuring dynamic tool providers for large or conditional tool sets
Instructions
1. Annotate Methods with @Tool
Define a tool class with methods annotated @Tool. Provide a description as the first parameter. Use @P for each parameter description.
publicclassWeatherTools {
privatefinal WeatherService weatherService;
publicWeatherTools(WeatherService weatherService) {
this.weatherService = weatherService;
}
@Tool("Get current weather for a city")public String getWeather(
@P("City name") String city,
@P("Temperature unit: celsius or fahrenheit") String unit) {
return weatherService.getWeather(city, unit);
}
}
Validate: Create an instance and confirm the class loads without errors.
2. Register Tools with AiServices
Use AiServices.builder() to register tool instances with the chat model.