langchain4j-tool-function-calling-patterns

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

Works with

Claude CodeCursorClineWindsurfCodexGooseGitHub CopilotZed

0

total installs

0

this week

194

GitHub stars

0

upvotes

Install Skill

Run in your terminal

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

0

installs

0

this week

194

stars

What it does

  • 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

Category

AI/ML

Last updated

Apr 8, 2026

Installation Guide

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 machine
  • Node.js 16+ with npm — verify with node --version
  • Active project directory where you want to add langchain4j-tool-function-calling-patterns
2

Run the install 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

Fetches langchain4j-tool-function-calling-patterns from giuseppe-trisciuoglio/developer-kit and configures it for Cursor.

3

Select Cursor when prompted

The CLI shows a list of agents. Use arrow keys and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ────────────────
│ · Cline · Codex · Goose · Windsurf
│ ●Cursor(selected)
│ · Cursor · Aider · Continue
4

Verify installation

Confirm successful installation by checking the skill directory location:

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

Restart Cursor to activate langchain4j-tool-function-calling-patterns. Access via /langchain4j-tool-function-calling-patterns in your agent's command palette.

Security 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 environment. Always review source, verify the publisher, and test in isolation before production.

Documentation

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

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

Steps

  1. 1Install skill using provided installation command
  2. 2Test with simple use case relevant to your work
  3. 3Evaluate output quality and relevance
  4. 4Iterate on prompts to improve results
  5. 5Integrate 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

Related Skills

Reviews

4.670 reviews
  • D
    Dhruvi JainDec 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.

  • M
    Mia HarrisDec 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.

  • A
    Ava LopezDec 20, 2024

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

  • M
    Meera AndersonDec 12, 2024

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

  • I
    Ira AgarwalDec 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.

  • M
    Mia ThompsonNov 23, 2024

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

  • O
    OshnikdeepNov 15, 2024

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

  • N
    Noor ParkNov 15, 2024

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

  • N
    Naina DixitNov 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.

  • L
    Layla TorresNov 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

Discussion

Comments — not star reviews
  • No comments yet — start the thread.