Skip to main content
skill CX Codex

langchain4j-ai-services-patterns — Claude Code skill: Java AI Services

A skill that walks your agent through declarative AI Services in LangChain4j: interfaces, annotations, memory and tool calling.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-ai-services-patterns -a claude-code
Open on GitHub

What langchain4j-ai-services-patterns does

The skill lays out the steps in order. First a Java interface with methods for talking to the model, then @SystemMessage and @UserMessage annotations for prompts, then instantiation through AiServices.create or the builder. Multi-turn conversations get memory via @MemoryId and chatMemoryProvider, and function calling comes from registering classes with @Tool. Working Java snippets ship inside, along with an API reference and a longer example set in references.md and examples.md.

Worth installing if you build Java apps on top of an LLM and are tired of assembling prompt strings by hand. The interface approach is typed: a service method can return an enum, a POJO or a list instead of a bare string. You need dev.langchain4j:langchain4j and dev.langchain4j:langchain4j-open-ai at version 1.8.0 in Maven or Gradle.

Model output is non-deterministic, so tests have to tolerate variation. Memory providers keep conversation history, and in multi-user setups that history needs cleanup or sessions bleed into each other. Tool execution can get expensive, and tools with side effects may fire when you did not expect it. Keep API keys and passwords out of system and user messages.

What it helps with

  • define an AI service as an interface instead of concatenating prompt strings
  • add memory to a multi-turn chat with per-user separation
  • wire up function calling through the @Tool annotation
  • get structured output from the model — enum, POJO or list
  • build a RAG flow declaratively without managing context by hand

Example prompts for the agent

  • create a LangChain4j AI Service: an interface with a chat method and a @SystemMessage annotation
  • add memory to this service with @MemoryId and a chatMemoryProvider for multiple users
  • register Calculator as a tool with @Tool and call it from the service

How to install langchain4j-ai-services-patterns

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-ai-services-patterns -a claude-code

2Manually: put the files in place

~/.claude/skills/langchain4j-ai-services-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/langchain4j-ai-services-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about langchain4j-ai-services-patterns

How do I install langchain4j-ai-services-patterns in Claude?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-ai-services-patterns -a claude-code. The skill file then lives at ~/.claude/skills/langchain4j-ai-services-patterns/SKILL.md.

What does langchain4j-ai-services-patterns do?

It provides patterns for declarative AI Services with LangChain4j: annotated interfaces, memory management, tool calling and structured output. The agent applies them while you write Java code that talks to an LLM.

What do I need before using it?

The dev.langchain4j:langchain4j and dev.langchain4j:langchain4j-open-ai dependencies at version 1.8.0, in Maven or Gradle. You also need access to a chat model, since AI Services run on top of one.

Source text

SKILL.md · MIT
---
name: langchain4j-ai-services-patterns
description: Provides patterns to build declarative AI Services with LangChain4j for LLM integration, chatbot development, AI agent implementation, and conversational AI in Java. Generates type-safe AI services using interface-based patterns, annotations, memory management, and tools integration. Use when creating AI-powered Java applications with minimal boilerplate, implementing conversational AI with memory, or building AI agents with function calling.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# LangChain4j AI Services Patterns

This skill provides guidance for building declarative AI Services with LangChain4j using interface-based patterns, annotations for system and user messages, memory management, tools integration, and advanced AI application patterns that abstract away low-level LLM interactions.

## Overview

LangChain4j AI Services define AI functionality using Java interfaces with annotations, providing type-safe, declarative AI with minimal boilerplate.

## When to Use

Use this skill when:
- Building declarative AI services with minimal boilerplate using Java interfaces
- Creating type-safe conversational AI with memory management
- Implementing AI agents with function/tool calling capabilities
- Designing AI services returning structured data (enums, POJOs, lists)
- Integrating RAG patterns declaratively

## Instructions

Follow these steps to create declarative AI Services with LangChain4j:

### 1. Define AI Service Interface

Create a Java interface with method signatures for AI interactions:

```java
interface Assistant {
    String chat(String userMessage);
}
```

### 2. Add Annotations for System and User Messages

Use `@SystemMessage` and `@UserMessage` annotations to define prompts:

```java
interface CustomerSupportBot {
    @SystemMessage("You are a helpful customer support agent for TechCorp")
    String handleInquiry(String customerMessage);

    @UserMessage("Analyze sentiment: {{it}}")
    Sentiment analyzeSentiment(String feedback);
}
```

### 3. Create AI Service Instance

Use `AiServices` builder or create to instantiate the service:

```java
// Simple creation
Assistant assistant = AiServices.create(Assistant.class, chatModel);

// Or with builder for advanced configuration
Assistant assistant = AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .build();
```

### 4. Configure Memory for Multi-turn Conversations

Add memory management using `@MemoryId` for multi-user scenarios:

```java
interface MultiUserAssistant {
    String chat(@MemoryId String userId, String userMessage);
}

Assistant assistant = AiServices.builder(MultiUserAssistant.class)
    .chatModel(model)
    .chatMemoryProvider(userId -> MessageWindowChatMemory.withMaxMessages(10))
    .build();
```

### 5. Integrate Tools for Function Calling

Register tools using `@Tool` annotation to enable AI function execution:

```java
class Calculator {
    @Tool("Add two numbers") double add(double a, double b) { return a + b; }
}

interface MathGenius {
    String ask(String question);
}

MathGenius mathGenius = AiServices.builder(MathGenius.class)
    .chatModel(model)
    .tools(new Calculator())
    .build();
```

### 6. Validate and Test

Test AI services with concrete validation patterns:

```java
// 1. Test with sample inputs
String response = assistant.chat("Hello, how are you?");
assert response != null && !response.isEmpty();

// 2. Validate structured outputs with assertions
Sentiment result = bot.analyzeSentiment("Great product!");
assert result == Sentiment.POSITIVE;

// 3. Log tool calls with side effects for audit
MathGenius math = AiServices.builder(MathGenius.class)
    .chatModel(model)
    .tools(new Calculator())
    .build();

// 4. Test memory isolation between users
String userA = assistant.chat("User A message", "session-a");
String userB = assistant.chat("User B message", "session-b");
assert !userA.equals(userB); // Verify memory isolation
```

## Examples

See [examples.md](references/examples.md) for comprehensive practical examples including:
- Basic chat interfaces
- Stateful assistants with memory
- Multi-user scenarios
- Structured output extraction
- Tool calling and function execution
- Streaming responses
- Error handling
- RAG integration
- Production patterns

## API Reference

Complete API documentation, annotations, interfaces, and configuration patterns are available in [references.md](references/references.md).

## Best Practices

1. **Use type-safe interfaces** instead of string-based prompts
2. **Implement proper memory management** with appropriate limits
3. **Design clear tool descriptions** with parameter documentation
4. **Handle errors gracefully** with custom error handlers
5. **Use structured output** for predictable responses
6. **Implement validation** for user inputs
7. **Monitor performance** for production deployments

## Dependencies

```xml
<!-- Maven -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai</artifactId>
    <version>1.8.0</version>
</dependency>
```

```gradle
// Gradle
implementation 'dev.langchain4j:langchain4j:1.8.0'
implementation 'dev.langchain4j:langchain4j-open-ai:1.8.0'
```

## References

- [LangChain4j Documentation](https://langchain4j.com/docs/)
- [LangChain4j AI Services - API References](references/references.md)
- [LangChain4j AI Services - Practical Examples](references/examples.md)

## Constraints and Warnings

- AI Services rely on LLM responses which are non-deterministic; tests should account for variability.
- Memory providers store conversation history; ensure proper cleanup for multi-user scenarios.
- Tool execution can be expensive; implement rate limiting and timeout handling.
- Never pass sensitive data (API keys, passwords) in system or user messages.
- Large context windows can lead to high token costs; implement message pruning strategies.
- Streaming responses require proper error handling for partial failures.
- AI-generated outputs should be validated before use in production systems.
- Be cautious with tools that have side effects; AI models may call them unexpectedly.
- Token limits vary by model; ensure prompts and context fit within model constraints.

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

Everything for AI and ML →

From the same set93

langchain4j-vector-stores-configuration A skill that shows how to wire a LangChain4J vector store for RAG: connections, embedding dimensions, metadata filters. CX Codex +1 3,700installs unit-test-application-events Unit test patterns for Spring events: verify publishing through ApplicationEventPublisher and exercise @EventListener handlers without booting the context. CX Codex +1 3,700installs unit-test-config-properties Provides JUnit 5 patterns to unit test Spring Boot @ConfigurationProperties using ApplicationContextRunner without starting a full application context. CX Codex +1 3,700installs unit-test-caching Unit test patterns for Spring Cache annotations: cache hits and misses, eviction, SpEL keys, all without booting a full Spring context. CX Codex +1 3,700installs qdrant Provides integration patterns for the Qdrant vector database in Java and Spring Boot with LangChain4j. Helps build semantic search and vector stores for RAG. CX Codex +1 3,700installs unit-test-mapper-converter A skill for unit-testing MapStruct mappers and converters: field mapping, null handling, nested objects and round-trip conversion. CX Codex +1 3,700installs unit-test-exception-handler Patterns for unit testing @ExceptionHandler and @ControllerAdvice in Spring Boot: status codes, JSON error bodies and field-level validation errors. CX Codex +1 3,700installs rag Guides the creation of Retrieval-Augmented Generation pipelines, covering document chunking, embedding generation, vector database selection, and retrieval. CX Codex +1 3,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor