langchain4j-tool-function-calling-patterns

giuseppe-trisciuoglio/developer-kit · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-tool-function-calling-patterns
0 commentsdiscussion
summary

Annotation-based and programmatic tool system for LangChain4j agents to execute external functions, APIs, and services.

  • Define tools using @Tool annotations with parameter descriptions via @P , automatically registered with AI services for LLM invocation
  • Supports static tool registration, dynamic tool provisioning based on context, concurrent execution, and immediate-return tools for quick responses
  • Includes error handling strategies, tool execution monitoring, memory context integra
skill.md

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
how to use langchain4j-tool-function-calling-patterns

How to use langchain4j-tool-function-calling-patterns on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add langchain4j-tool-function-calling-patterns
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-tool-function-calling-patterns

The skills CLI fetches langchain4j-tool-function-calling-patterns from GitHub repository giuseppe-trisciuoglio/developer-kit and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/langchain4j-tool-function-calling-patterns

Reload or restart Cursor to activate langchain4j-tool-function-calling-patterns. Access the skill through slash commands (e.g., /langchain4j-tool-function-calling-patterns) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.670 reviews
  • Dhruvi Jain· Dec 24, 2024

    Solid pick for teams standardizing on skills: langchain4j-tool-function-calling-patterns is focused, and the summary matches what you get after install.

  • Mia Harris· Dec 24, 2024

    Solid pick for teams standardizing on skills: langchain4j-tool-function-calling-patterns is focused, and the summary matches what you get after install.

  • Ava Lopez· Dec 20, 2024

    We added langchain4j-tool-function-calling-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Meera Anderson· Dec 12, 2024

    langchain4j-tool-function-calling-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Ira Agarwal· Dec 8, 2024

    Solid pick for teams standardizing on skills: langchain4j-tool-function-calling-patterns is focused, and the summary matches what you get after install.

  • Mia Thompson· Nov 23, 2024

    We added langchain4j-tool-function-calling-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Oshnikdeep· Nov 15, 2024

    We added langchain4j-tool-function-calling-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Noor Park· Nov 15, 2024

    We added langchain4j-tool-function-calling-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Naina Dixit· Nov 11, 2024

    Solid pick for teams standardizing on skills: langchain4j-tool-function-calling-patterns is focused, and the summary matches what you get after install.

  • Layla Torres· Nov 3, 2024

    langchain4j-tool-function-calling-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

showing 1-10 of 70

1 / 7