Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
giuseppe-trisciuoglio avatar

Langchain4j Tool Function Calling Patterns

  • 1.8k installs
  • 318 repo stars
  • Updated June 22, 2026
  • giuseppe-trisciuoglio/developer-kit

Patterns for annotating Java methods as LLM-callable tools, registering them with AI services, validating parameters, and handling execution errors in LangChain4j.

About

Teaches patterns for building tool-calling AI agents in LangChain4j using @Tool and @P annotations to expose Java methods as LLM-callable functions. Covers tool registration with AiServices, parameter validation, error handling, concurrent execution, and dynamic tool provisioning. Essential for building agents that integrate external services like weather APIs, databases, or business systems where the LLM needs to invoke actions beyond text generation. Includes timeout configuration, hallucinated tool detection, and audit logging patterns for production safety.

  • Annotate methods with @Tool and @P to define callable functions with LLM-readable descriptions
  • Register tool instances with AiServices.builder().tools() to enable LLM invocation
  • Handle execution errors, timeouts, and hallucinated tool names with dedicated error handlers
  • Enable concurrent tool execution and timeouts to prevent hangs and optimize performance
  • Validate parameters inside tools and return safe error messages instead of exposing stack traces

Langchain4j Tool Function Calling Patterns by the numbers

  • 1,800 all-time installs (skills.sh)
  • +144 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Ranked #713 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
At a glance

langchain4j-tool-function-calling-patterns capabilities & compatibility

Capabilities
define tool specifications with @tool and @p ann · register tools with ai services and chat models · handle tool execution errors and timeout conditi · validate tool parameters before invocation · execute tools concurrently for independent calls · implement dynamic tool providers based on user c
Use cases
api development · orchestration · code review
Platforms
macOS · Windows · Linux
Runs
Runs locally
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-tool-function-calling-patterns

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1.8k
repo stars318
Security audit2 / 3 scanners passed
Last updatedJune 22, 2026
Repositorygiuseppe-trisciuoglio/developer-kit

What it does

Expose Java methods as callable functions for LLM-driven agents to perform external API calls, database queries, and business system integrations.

Who is it for?

Building AI agents that call databases, REST APIs, weather services, stock feeds, or business system integrations; defining function specifications for LLM tool use; managing large conditional tool sets.

Skip if: Simple chatbots that only generate text; agents that do not need external integrations; synchronous request-response systems without AI decision-making.

When should I use this skill?

Starting to build an AI agent; adding tool invocation to an existing LangChain4j service; scaling tool sets to handle many functions or conditional access.

What you get

Developers can build AI agents that reliably invoke external tools, APIs, and business systems with validated parameters, graceful error handling, and production-safe error messages.

  • Tool class with @Tool-annotated methods
  • AiServices instance with registered tools
  • Error handlers for execution failures

By the numbers

  • Supports @ToolMemoryId for context-aware tool execution with conversation IDs
  • Provides .toolExecutionTimeout() for configurable per-tool execution deadlines
  • Includes .executeToolsConcurrently() for parallel invocation of independent tools

Files

SKILL.mdMarkdownGitHub ↗

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.

public class WeatherTools {
    private final WeatherService weatherService;

    public WeatherTools(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.

MathAssistant assistant = AiServices.builder(MathAssistant.class)
    .chatModel(chatModel)
    .tools(new Calculator(), new WeatherTools(weatherService))
    .build();

Validate: Call assistant.chat("What is 2 + 2?") and verify the LLM responds without throwing.

3. Test Tool Invocation End-to-End

Send a prompt that triggers tool usage and verify the tool executes and its result is incorporated.

String response = assistant.chat("What is the weather in Rome?");
System.out.println(response);

Validate: Check logs for tool invocation and confirm the response uses the tool output.

4. Handle Tool Execution Errors

Add error handlers to gracefully manage failures without exposing stack traces.

AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .tools(new ExternalServiceTools())
    .toolExecutionErrorHandler((request, exception) -> {
        logger.error("Tool '{}' failed: {}", request.name(), exception.getMessage());
        return "An error occurred while processing your request";
    })
    .hallucinatedToolNameStrategy(request ->
        ToolExecutionResultMessage.from(request,
            "Error: tool '" + request.name() + "' does not exist"))
    .toolArgumentsErrorHandler((error, context) ->
        ToolErrorHandlerResult.text("Invalid arguments: " + error.getMessage()))
    .build();

Validate: Trigger an error condition and confirm the LLM receives a safe error message.

5. Optimize for Performance and Scale

Enable concurrent tool execution and set timeouts for long-running tools.

AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .tools(new DbTools(), new HttpTools())
    .executeToolsConcurrently(Executors.newFixedThreadPool(5))
    .toolExecutionTimeout(Duration.ofSeconds(30))
    .build();

Validate: Run concurrent requests and confirm no thread contention or deadlocks.

Examples

Calculator Tool with Full Class

public class Calculator {
    @Tool("Perform basic arithmetic")
    public double calculate(
            @P("Expression like 2+2 or 10*5") String expression) {
        // Parse and evaluate expression
        return eval(expression);
    }
}

Assistant assistant = AiServices.builder(Assistant.class)
    .chatModel(ChatModel.builder()
        .apiKey(System.getenv("API_KEY"))
        .model("gpt-4o")
        .build())
    .tools(new Calculator())
    .build();

Immediate Return Tool (No LLM Response)

@Tool(value = "Send email notification", returnBehavior = ReturnBehavior.IMMEDIATELY)
public void sendEmail(@P("Recipient email address") String to,
                     @P("Email subject") String subject,
                     @P("Email body") String body) {
    emailService.send(to, subject, body);
}

Dynamic Tool Provider

ToolProvider provider = request -> {
    if (request.userContext().contains("admin")) {
        return List.of(new AdminTools());
    }
    return List.of(new UserTools());
};

AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .toolProvider(provider)
    .build();

Best Practices

  • Descriptive `@Tool` names: Use imperative verbs ("Get", "Send", "Calculate") with clear scope
  • Precise `@P` descriptions: Include format, constraints, and valid values — vague descriptions cause incorrect LLM calls
  • Safe error handling: Never expose stack traces; return user-friendly error strings
  • Timeout configuration: Always set .toolExecutionTimeout() for external service calls
  • Concurrent execution: Enable .executeToolsConcurrently() when tools are independent
  • Input validation: Validate parameters inside the tool method; return descriptive errors
  • Permission checks: Perform authorization inside the tool, not at the AI service level
  • Audit logging: Log tool name, parameters, and execution result for debugging and compliance

Common Issues and Solutions

IssueSolution
LLM calls non-existent toolAdd .hallucinatedToolNameStrategy() returning a safe error message
Tools receive wrong parametersRefine @P descriptions; add .toolArgumentsErrorHandler()
Tool execution hangsSet .toolExecutionTimeout(Duration.ofSeconds(N))
Rate limit errors from external APIAdd retry logic or rate limiter inside the tool method
LLM ignores tool outputEnsure the tool returns a string the LLM can interpret

See references/error-handling.md for resilience patterns and references/core-patterns.md for parameter and return type details.

Quick Reference

Annotation / APIPurpose
@ToolMarks a method as a callable tool
@PDescribes a tool parameter for the LLM
@ToolMemoryIdInjects conversation/user ID into the tool
AiServices.builder()Creates AI service with registered tools
ReturnBehavior.IMMEDIATELYExecute tool without waiting for LLM response
ToolProviderDynamic tool provisioning based on context
executeToolsConcurrently()Run independent tool calls in parallel
toolExecutionTimeout()Timeout for individual tool calls

Constraints and Warnings

  • Sensitive data: Never pass API keys, passwords, or credentials in @Tool or @P descriptions
  • Side effects: Tools that modify data should warn in their description; AI models may call them multiple times
  • Large tool sets: Excessive tools confuse LLM models — use ToolProvider for conditional registration
  • Blocking operations: Tools should not perform long synchronous I/O without timeout configuration
  • Stack trace exposure: Always route exceptions through error handlers that return safe strings
  • Parameter precision: Vague @P descriptions directly cause incorrect tool calls — be specific about formats and constraints
  • Concurrent safety: Ensure tool classes are stateless or thread-safe when using executeToolsConcurrently()

Related Skills

  • langchain4j-ai-services-patterns — High-level AI service configuration
  • langchain4j-rag-implementation-patterns — RAG retrieval with tool integration
  • langchain4j-spring-boot-integration — Tool registration in Spring Boot applications

References

  • [references/setup-configuration.md](references/setup-configuration.md) — Maven setup, chat model configuration, first tool registration
  • [references/core-patterns.md](references/core-patterns.md) — Basic tool definition, complex parameters, return types
  • [references/advanced-features.md](references/advanced-features.md) — Memory context, dynamic tool providers, streaming, immediate return
  • [references/error-handling.md](references/error-handling.md) — Error handlers, retry logic, monitoring
  • [references/integration-examples.md](references/integration-examples.md) — Database, REST API, and context-aware tool examples

Related skills

Forks & variants (1)

Langchain4j Tool Function Calling Patterns has 1 known copy in the catalog totaling 21 installs. They canonicalize to this original listing.

How it compares

Use this skill for Java LangChain4j tool design; pick Python agent skills when the stack is not on the JVM.

FAQ

What is the @Tool annotation for?

@Tool marks a Java method as a callable function the LLM can invoke. It requires a description string that guides the LLM on when to call it.

How do I prevent the LLM from calling tools that don't exist?

Use .hallucinatedToolNameStrategy() to catch requests for non-existent tools and return a safe error message instead of failing.

How do I run tools without waiting for the LLM to process the result?

Set ReturnBehavior.IMMEDIATELY on the @Tool annotation to execute the tool without returning control to the LLM.

Is Langchain4j Tool Function Calling Patterns safe to install?

skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.