
Langchain4j Tool Function Calling Patterns
Wire LangChain4j @Tool methods, memory-aware parameters, and dynamic ToolProvider routing when building Java AI assistants that call your APIs.
Overview
langchain4j-tool-function-calling-patterns is an agent skill for the Build phase that shows how to implement LangChain4j @Tool, dynamic ToolProvider, memory IDs, immediate return, and streaming tool execution in Java.
Install
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-tool-function-calling-patternsWhat is this skill?
- Personalized tools with @ToolMemoryId and @P parameter binding for user-scoped calls
- ContextAwareToolProvider that adds weather or calculator tools based on user message keywords
- @Tool(returnBehavior = ReturnBehavior.IMMEDIATE) for answers without waiting for full model completion
- StreamingAssistant TokenStream pattern alongside tool execution in AiServices
- Java LangChain4j annotations and ToolProviderResult builder for production agent wiring
Adoption & trust: 1.2k installs on skills.sh; 271 GitHub stars; 2/3 security scanners passed (skills.sh audits).
What problem does it solve?
Your Java agent can chat but you lack clear patterns for scoped parameters, conditional tool exposure, and fast tool-only replies.
Who is it for?
Indie builders adding function calling to a LangChain4j/Java stack with existing domain services.
Skip if: Teams only using Python LangChain, pure prompt-only bots with no tools, or non-JVM products with no plan to adopt LangChain4j.
When should I use this skill?
Implementing or extending LangChain4j tool calling, ToolProvider, or streaming assistants in a Java agent project.
What do I get? / Deliverables
You can copy proven LangChain4j integrations so assistants call the right executors with user context, streaming, and immediate tool results.
- @Tool class implementations
- Optional ContextAwareToolProvider
- Streaming assistant interface wired to tools
Recommended Skills
Journey fit
Tool-calling patterns are implemented while integrating LLM agents with backend services and domain executors. Integrations is the shelf for connecting agent runtimes to callable functions, streaming, and context-specific tool catalogs.
How it compares
Reference patterns for JVM tool calling—not a hosted MCP server or no-code agent builder.
Common Questions / FAQ
Who is langchain4j-tool-function-calling-patterns for?
Java developers and solo builders using LangChain4j AiServices who need production-grade tool registration, memory-aware args, and dynamic tool sets.
When should I use langchain4j-tool-function-calling-patterns?
During Build integrations when wiring @Tool classes, ToolProvider routing, or streaming TokenStream assistants, and when debugging why tools fire too slowly or with wrong user context.
Is langchain4j-tool-function-calling-patterns safe to install?
Treat it as documentation-style guidance; review the Security Audits panel on this page and restrict tool executors to least-privilege APIs before enabling network or secrets in your agent runtime.
SKILL.md
READMESKILL.md - Langchain4j Tool Function Calling Patterns
# Advanced Features ## Memory Context Integration Access user context using `@ToolMemoryId`: ```java public class PersonalizedTools { @Tool("Get user preferences") public String getPreferences( @ToolMemoryId String userId, @P("Preference category") String category) { return preferenceService.getPreferences(userId, category); } } ``` ## Dynamic Tool Provisioning Create tools that change based on context: ```java public class ContextAwareToolProvider implements ToolProvider { @Override public ToolProviderResult provideTools(ToolProviderRequest request) { String message = request.userMessage().singleText().toLowerCase(); var builder = ToolProviderResult.builder(); if (message.contains("weather")) { builder.add(weatherToolSpec, weatherExecutor); } if (message.contains("calculate")) { builder.add(calcToolSpec, calcExecutor); } return builder.build(); } } ``` ## Immediate Return Tools Return results immediately without full AI response: ```java public class QuickTools { @Tool(value = "Get current time", returnBehavior = ReturnBehavior.IMMEDIATE) public String getCurrentTime() { return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } } ``` ## Streaming with Tool Execution ```java interface StreamingAssistant { TokenStream chat(String message); } StreamingAssistant assistant = AiServices.builder(StreamingAssistant.class) .streamingChatModel(streamingChatModel) .tools(new Tools()) .build(); TokenStream stream = assistant.chat("What's the weather and calculate 15*8?"); stream .onToolExecuted(execution -> System.out.println("Executed: " + execution.request().name())) .onPartialResponse(System.out::print) .onComplete(response -> System.out.println("Complete!")) .start(); ``` ## Tool Specification Builder ```java ToolSpecification toolSpec = ToolSpecification.builder() .name("advanced_search") .description("Search across multiple data sources") .addParameter("query", type("string"), description("Search query")) .addParameter("sources", type("array"), description("Data sources to search")) .addParameter("filters", type("object"), description("Search filters"), required(false) .build(); ``` # Core Patterns ## Basic Tool Definition Use `@Tool` annotation to define methods as executable tools: ```java public class BasicTools { @Tool("Add two numbers") public int add(@P("first number") int a, @P("second number") int b) { return a + b; } @Tool("Get greeting") public String greet(@P("name to greet") String name) { return "Hello, " + name + "!"; } } ``` ## Parameter Descriptions and Validation Provide clear parameter descriptions using `@P` annotation: ```java public class WeatherService { @Tool("Get current weather conditions") public String getCurrentWeather( @P("City name or coordinates") String location, @P("Temperature unit (celsius, fahrenheit)", required = false) String unit) { // Implementation with validation if (location == null || location.trim().isEmpty()) { return "Location is required"; } return weatherClient.getCurrentWeather(location, unit); } } ``` ## Complex Parameter Types Use Java records and descriptions for complex objects: ```java public class OrderService { @Description("Customer order information") public record OrderRequest( @Description("Customer ID") String customerId, @Description("List of items") List<OrderItem> items, @JsonProperty(required = false) @Description("Delivery instructions") String instructions ) {} @Tool("Create customer order") public String createOrder(OrderRequest order) { return orderService.processOrder(order); } } ``` ## Return Types Tool methods can return variou