Token导航 LogoToken导航TokenDH.com
开发external-servicegithub未标认证来源可访问许可证需确认审计提醒

langchain4j-tool-function-calling-patternslangchain4j tool function calling 模式

Agent Skill

langchain4j-tool-function-calling-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

480

周安装

20

GitHub Stars

217

下载量

160
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:langchain4j-tool-function-calling-patterns(langchain4j tool function calling 模式)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code
仓库路径:skills/langchain4j-tool-function-calling-patterns
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code --skill langchain4j-tool-function-calling-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

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

简介

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。

  • 适合围绕仓库状态、代码变更或协作事项进行整理。
  • 可结合来源仓库和原始 README 核验具体用法。
  • 安装前建议确认权限范围、维护状态及是否触发联网或文件读写。
  • 安装方式:通过 GitHub 仓库添加,适用于 Codex、Claude、Cursor 等宿主环境。

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(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

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

39.42%
按下载量换算63

Claude

29.46%
按下载量换算47

Cursor

18.83%
按下载量换算30

Gemini CLI

10.15%
按下载量换算16

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills