Skip to content

giuseppe-trisciuoglio/developer-kit / plugins/developer-kit-java/skills/langchain4j-tool-function-calling-patterns

langchain4j-tool-function-calling-patterns

Verified

Provides and generates LangChain4j tool and function calling patterns: annotates methods as tools with @Tool, configures tool executors, registers tools with AiServices, validates tool parameters, and handles tool execution errors. Use when building AI agents that call tools, define function specifications, manage tool responses, or integrate external APIs with LLM-driven applications.

references/error-handling.md

View on GitHub
# Error Handling and Resilience

## Tool Error Handling

Handle tool execution errors gracefully:

```java
AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .tools(new ExternalServiceTools())
    .toolExecutionErrorHandler((request, exception) -> {
        if (exception instanceof ApiException) {
            return "Service temporarily unavailable: " + exception.getMessage();
        }
        return "An error occurred while processing your request";
    })
    .build();
```

## Resilience Patterns

Implement circuit breakers and retries:

```java
public class ResilientService {

    private final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("external-api");

    @Tool("Get external data")
    public String getExternalData(@P("Data identifier") String id) {
        return circuitBreaker.executeSupplier(() -> {
            return externalApi.getData(id);
        });
    }
}
```

## Parameter Validation Errors

```java
.toolArgumentsErrorHandler((error, context) -> {
    return ToolErrorHandlerResult.text("Invalid arguments: " + error.getMessage());
})
```

## Hallucinated Tool Names

```java
.hallucinatedToolNameStrategy(request -> {
    return ToolExecutionResultMessage.from(request,
        "Error: Tool '" + request.name() + "' does not exist");
})
```

## Timeout Handling

```java
AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .tools(new ExternalTools())
    .toolExecutionTimeout(Duration.ofSeconds(30))
    .build();
```

## Retry Configuration

```java
public class RetryingToolService {

    private final Retry retry = Retry.ofDefaults("tool-retry");

    @Tool("Fetch remote data")
    public String fetchData(@P("URL") String url) {
        return retry.executeSupplier(() -> {
            return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        });
    }
}
```

## Monitoring and Logging

```java
AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .tools(new BusinessTools())
    .toolExecutionListener(new ToolExecutionListener() {
        @Override
        public void onToolExecuted(ToolExecution execution) {
            log.info("Tool {} executed in {}ms",
                execution.request().name(),
                execution.duration().toMillis());

            // Record metrics
            meterRegistry.timer("tool.execution",
                "tool", execution.request().name())
                .record(execution.duration());
        }

        @Override
        public void onToolExecutionError(ToolExecutionRequest request, Throwable error) {
            log.error("Tool {} execution failed: {}",
                request.name(), error.getMessage());

            // Record error metrics
            meterRegistry.counter("tool.errors",
                "tool", request.name(),
                "error", error.getClass().getSimpleName())
                .increment();
        }
    })
    .build();
```
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 321kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 321kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 321kUpdated Claude CodeCodexVerifiedInstall