langchain4j-ai-services-patterns
giuseppe-trisciuoglio/developer-kit
Build type-safe, declarative AI services in Java with LangChain4j using interface patterns and annotations.
What is langchain4j-ai-services-patterns?
LangChain4j AI Services Patterns provides a framework for creating declarative AI services in Java using interface-based patterns, annotations, and memory management. Use this when building conversational AI, chatbots, AI agents with function calling, or any LLM-integrated Java application with minimal boilerplate.
- Define AI services using Java interfaces with @SystemMessage and @UserMessage annotations
- Manage multi-turn conversations with @MemoryId for memory isolation across users
- Integrate tools and function calling with @Tool annotations for AI-driven execution
- Generate type-safe responses including structured data (enums, POJOs, lists)
- Build RAG patterns declaratively with integrated retrieval and generation
- Handle streaming responses and error cases with custom handlers
How to install langchain4j-ai-services-patterns
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-ai-services-patterns- Java development environment
- LangChain4j library (1.8.0+) and chat model provider (e.g., langchain4j-open-ai)
- Understanding of Java interfaces and annotations
How to use langchain4j-ai-services-patterns
- 1.Define a Java interface with method signatures for AI interactions
- 2.Add @SystemMessage and @UserMessage annotations to specify prompts and templates
- 3.Create an AI service instance using AiServices.create() or AiServices.builder()
- 4.For multi-user scenarios, add @MemoryId parameters and configure a chat memory provider
- 5.Register tools by annotating methods with @Tool and passing tool instances to the builder
- 6.Test with sample inputs, validate structured outputs, and verify memory isolation between users
Use cases
- Building customer support chatbots with context-aware memory across sessions
- Creating AI agents that call external tools (calculators, APIs) based on user queries
- Implementing multi-user assistants with isolated conversation memory per user
- Extracting structured data from unstructured text using type-safe return types
- Developing conversational search or RAG systems with declarative patterns
- Java developers building LLM-integrated applications
- Teams implementing conversational AI or chatbot systems
- Developers creating AI agents with function-calling capabilities
- Architects designing type-safe, low-boilerplate AI services
langchain4j-ai-services-patterns FAQ
Define a Java interface with a method, add @SystemMessage and @UserMessage annotations, then instantiate it with AiServices.create(YourInterface.class, chatModel).
Use @MemoryId parameter on your interface methods and configure a chatMemoryProvider in the AiServices builder with appropriate message limits.
Yes, register tools by annotating methods with @Tool and passing tool instances to the AiServices builder. The AI model will call them based on user queries.
AI services support String, enums, POJOs, lists, and other structured types. The framework handles serialization and type conversion automatically.
No, LLM responses are non-deterministic. Tests should account for variability and validate outputs rather than expecting exact matches.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
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:
interface Assistant {
String chat(String userMessage);
}
2. Add Annotations for System and User Messages
Use @SystemMessage and @UserMessage annotations to define prompts:
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:
// 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:
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:
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:
// 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 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.
Best Practices
- Use type-safe interfaces instead of string-based prompts
- Implement proper memory management with appropriate limits
- Design clear tool descriptions with parameter documentation
- Handle errors gracefully with custom error handlers
- Use structured output for predictable responses
- Implement validation for user inputs
- Monitor performance for production deployments
Dependencies
<!-- 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
implementation 'dev.langchain4j:langchain4j:1.8.0'
implementation 'dev.langchain4j:langchain4j-open-ai:1.8.0'
References
- LangChain4j Documentation
- LangChain4j AI Services - API References
- LangChain4j AI Services - Practical Examples
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.
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

langchain4j-mcp-server-patterns
LangChain4j patterns for building and integrating MCP servers with tool calling and secure agent workflows.

langchain4j-rag-implementation-patterns
RAG implementation patterns with LangChain4j for Java: document ingestion, embeddings, and semantic search.

langchain4j-spring-boot-integration
Integrate LangChain4j with Spring Boot using declarative AI Services, auto-configuration, and dependency injection.

langchain4j-testing-strategies
Unit, integration, and mock testing patterns for LangChain4j Java AI services and RAG workflows.

langchain4j-tool-function-calling-patterns
Annotate Java methods as LLM-callable tools, register with AiServices, and handle execution errors in LangChain4j agents.

langchain4j-vector-stores-configuration
Configure LangChain4J vector stores for RAG applications with PostgreSQL, Pinecone, MongoDB, Milvus, and Neo4j.