PluginBench
Skill
Fail
Audit score 45

langchain4j-spring-boot-integration

giuseppe-trisciuoglio/developer-kit

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

What is langchain4j-spring-boot-integration?

Provides integration patterns for embedding LangChain4j into Spring Boot applications. Configures AI model beans, sets up chat memory with Spring context, integrates RAG pipelines with Spring Data, and handles auto-configuration and dependency injection. Use when building Java LLM applications with Spring Boot, setting up @Bean configuration, or implementing Spring AI patterns.

  • Configure AI model beans with @Bean annotations and property-based configuration
  • Create declarative AI Services using @AiService interfaces with message templates
  • Set up chat memory and conversation context with Spring dependency injection
  • Implement RAG pipelines with embedding stores and Spring Data integration
  • Support multiple AI providers (OpenAI, Azure, Ollama, Anthropic) through auto-configuration
  • Define tools as Spring components and integrate them with AI Services

How to install langchain4j-spring-boot-integration

npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-spring-boot-integration
Prerequisites
  • Spring Boot application (3.0+)
  • LangChain4j Spring Boot Starter dependency
  • API key for chosen AI provider (OpenAI, Azure, etc.)
  • Java 11 or higher
Claude Code
Cursor
Windsurf
Cline

How to use langchain4j-spring-boot-integration

  1. 1.Add langchain4j-spring-boot-starter and provider-specific starters (e.g., langchain4j-open-ai-spring-boot-starter) to your Maven pom.xml
  2. 2.Configure AI model properties in application.properties or application.yml with API keys and model parameters
  3. 3.Create a declarative AI Service interface annotated with @AiService and define methods with @SystemMessage/@UserMessage annotations
  4. 4.Enable component scanning for dev.langchain4j.service.spring in your @SpringBootApplication class
  5. 5.Inject the AI Service interface into your Spring components and call methods to interact with the LLM
  6. 6.Verify integration by starting the application and checking logs for LangChain4jSpringBootAutoConfiguration activation

Use cases

Good for
  • Building AI-powered microservices with Spring Boot and LangChain4j
  • Creating customer support assistants with conversation memory and context management
  • Implementing RAG systems that retrieve knowledge from vector databases via Spring Data
  • Setting up multi-provider AI configurations for flexibility across different LLM services
  • Developing production-ready applications with proper logging, retry mechanisms, and external configuration
Who it's for
  • Java developers building LLM applications with Spring Boot
  • Backend engineers implementing AI features in existing Spring applications
  • Microservices architects integrating AI capabilities into service-oriented architectures
  • Teams requiring production-ready AI integrations with dependency injection and auto-configuration

langchain4j-spring-boot-integration FAQ

How do I configure multiple AI providers in the same application?

Use explicit wiring mode (WiringMode.EXPLICIT) in @AiService and define separate @Bean methods for each ChatModel provider, or use property-based configuration with provider-specific prefixes like langchain4j.open-ai and langchain4j.azure.

How do I set up conversation memory with Spring context?

Use @MemoryId annotation on a parameter (e.g., userId) in your @AiService method. Spring will automatically manage conversation history per memory ID using the configured memory store.

Can I use streaming responses with Spring Boot?

Yes, implement streaming by returning Flux<String> from your @AiService method and use Project Reactor for reactive streaming responses.

How do I integrate tools with AI Services?

Define tools as Spring @Component classes with @Tool-annotated methods, then inject them into your @AiService. The framework automatically makes them available to the AI model.

What embedding store options are available for RAG?

LangChain4j supports multiple stores including PgVectorEmbeddingStore for PostgreSQL, and others. Configure via @Bean methods in a @Configuration class and reference in your RAG assistant.

Full instructions (SKILL.md)

Source of truth, from giuseppe-trisciuoglio/developer-kit.


name: langchain4j-spring-boot-integration description: Provides integration patterns for LangChain4j with Spring Boot. Configures AI model beans, sets up chat memory with Spring context, integrates RAG pipelines with Spring Data, and handles auto-configuration, dependency injection, and Spring ecosystem integration. Use when embedding LangChain4j into Spring Boot applications, building Java LLM applications with @Bean configuration, or setting up Spring AI patterns. allowed-tools: Read, Write, Edit, Bash, Glob, Grep

LangChain4j Spring Boot Integration

Integrate LangChain4j with Spring Boot using declarative AI Services, auto-configuration, and Spring Boot starters. Configure AI model beans, set up chat memory, implement RAG pipelines with Spring Data, and build production-ready AI applications.

When to Use

Use this skill when:

  • Integrating LangChain4j into existing Spring Boot applications
  • Building AI-powered microservices with Spring Boot
  • Configuring AI model beans with @Bean annotations
  • Setting up auto-configuration for AI models and services
  • Creating declarative AI Services with Spring dependency injection
  • Implementing RAG systems with Spring Data integrations
  • Setting up chat memory with Spring context management
  • Configuring multiple AI providers (OpenAI, Azure, Ollama, Anthropic)
  • Building production-ready AI applications with Spring Boot

Overview

LangChain4j Spring Boot integration provides declarative AI Services through Spring Boot starters, enabling automatic configuration of AI components based on properties. Combine Spring dependency injection with LangChain4j's AI capabilities using interface-based definitions with annotations.

Instructions

1. Add Dependencies

<!-- Core LangChain4j Spring Boot Starter -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>

<!-- OpenAI Spring Boot Starter -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>

2. Configure Application Properties

# application.properties
langchain4j.open-ai.chat-model.api-key=${OPENAI_API_KEY}
langchain4j.open-ai.chat-model.model-name=gpt-4o-mini
langchain4j.open-ai.chat-model.temperature=0.7
langchain4j.open-ai.chat-model.timeout=PT60S
langchain4j.open-ai.chat-model.max-tokens=1000

Or using YAML:

langchain4j:
  open-ai:
    chat-model:
      api-key: ${OPENAI_API_KEY}
      model-name: gpt-4o-mini
      temperature: 0.7
      timeout: 60s
      max-tokens: 1000

3. Create Declarative AI Service

import dev.langchain4j.service.spring.AiService;

@AiService
public interface CustomerSupportAssistant {

    @SystemMessage("You are a helpful customer support agent for TechCorp.")
    String handleInquiry(String customerMessage);

    @UserMessage("Translate to {{language}}: {{text}}")
    String translate(String text, String language);
}

4. Enable Component Scanning

@SpringBootApplication
@ComponentScan(basePackages = {
    "com.yourcompany",
    "dev.langchain4j.service.spring"
})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5. Inject and Use the AI Service

@Service
public class CustomerService {

    private final CustomerSupportAssistant assistant;

    public CustomerService(CustomerSupportAssistant assistant) {
        this.assistant = assistant;
    }

    public String processCustomerQuery(String query) {
        return assistant.handleInquiry(query);
    }
}

6. Verify the Integration

After setup, verify the configuration:

  1. Start the application and check logs for LangChain4jSpringBootAutoConfiguration activation
  2. Confirm AI service beans are registered: look for CustomerSupportAssistant in Spring context
  3. Test the service: invoke assistant.handleInquiry("test") and verify a response is returned

Configuration

Property-Based Configuration: Configure AI models through application.properties for different providers.

Manual Bean Configuration: For advanced configurations, define beans manually:

@Configuration
public class AiConfig {

    @Bean
    public ChatModel chatModel(@Value("${OPENAI_API_KEY}") String apiKey) {
        return OpenAiChatModel.builder()
            .apiKey(apiKey)
            .modelName("gpt-4o-mini")
            .temperature(0.7)
            .build();
    }
}

Multiple Providers: Use explicit wiring when configuring multiple AI providers:

@AiService(wiringMode = WiringMode.EXPLICIT)
interface MultiProviderAssistant {
    @AiServiceAnnotation
    ChatModel openAiModel;

    @AiServiceAnnotation
    ChatModel azureModel;
}

Declarative AI Services

Basic AI Service: Create interfaces with @AiService annotation and define methods with message templates.

Streaming AI Service: Implement streaming responses using Project Reactor:

@AiService
public interface StreamingAssistant {
    @SystemMessage("You are a helpful assistant.")
    Flux<String> chatStream(String message);
}

Chat Memory: Set up conversation memory with Spring context:

@AiService
public interface ConversationalAssistant {
    @SystemMessage("You are a helpful assistant with memory.")
    String chat(@MemoryId String userId, String message);
}

RAG Implementation

Embedding Stores: Configure embedding stores for RAG pipelines with Spring Data:

@Configuration
public class RagConfig {

    @Bean
    public EmbeddingStore<TextSegment> embeddingStore() {
        return PgVectorEmbeddingStore.builder()
            .host("localhost")
            .port(5432)
            .database("vectordb")
            .table("embeddings")
            .dimension(1536)
            .build();
    }

    @Bean
    public EmbeddingModel embeddingModel() {
        return OpenAiEmbeddingModel.withApiKey(System.getenv("OPENAI_API_KEY"));
    }
}

@AiService
public interface RagAssistant {
    String answer(@UserMessage("Question: {{question}}") String question);
}

Document Ingestion: Use ContentInjector and DocumentSplitter for processing documents. Content Retrieval: Configure EmbeddingStoreContentRetriever for knowledge augmentation.

Tool Integration

Spring Component Tools: Define tools as Spring components:

@Component
public class Calculator {
    @Tool("Calculate the sum of two numbers")
    public double add(double a, double b) {
        return a + b;
    }
}

@AiService
public interface MathAssistant {
    String solve(String problem);
}

Examples

Basic AI Service

@AiService
public interface ChatAssistant {
    @SystemMessage("You are a helpful assistant.")
    String chat(String message);
}

AI Service with Memory

@AiService
public interface ConversationalAssistant {
    @SystemMessage("You are a helpful assistant with memory of conversations.")
    String chat(@MemoryId String userId, String message);
}

AI Service with Tools

@Component
public class WeatherService {
    @Tool("Get weather for a city")
    public String getWeather(String city) {
        return "Sunny, 22°C in " + city;
    }
}

@AiService
public interface WeatherAssistant {
    String getWeatherForCity(String city);
}

For more examples (including RAG configurations, streaming assistants, and multi-provider setups), refer to references/examples.md.

Best Practices

  • Use Property-Based Configuration: External configuration over hardcoded values
  • Use Profiles: Separate configurations for development, testing, and production
  • Add Proper Logging: Debug AI service calls and monitor performance
  • Implement Retry Mechanisms: Handle transient failures with backoff strategies
  • Monitor Token Usage: Track token consumption and implement limits

References

For detailed API references and advanced configurations:

Constraints and Warnings

  • Store API keys securely using environment variables or secret management systems
  • AI model responses are non-deterministic; tests should account for variability
  • Rate limits may apply to AI providers; implement proper retry and backoff strategies
  • Memory providers store conversation history; implement cleanup for multi-user scenarios
  • Token costs accumulate quickly; monitor usage and implement token limits
  • Streaming responses require proper error handling for partial failures
  • Check provider-specific documentation for supported features
  • Use explicit wiring mode when multiple chat models are configured
  • Validate AI-generated outputs before use in production systems

Related skills

More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

LAlangchain4j-testing-strategies logo

langchain4j-testing-strategies

giuseppe-trisciuoglio/developer-kit

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

1.4k installsAudited
LAlangchain4j-tool-function-calling-patterns logo

langchain4j-tool-function-calling-patterns

giuseppe-trisciuoglio/developer-kit

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

1.4k installs
LAlangchain4j-vector-stores-configuration logo

langchain4j-vector-stores-configuration

giuseppe-trisciuoglio/developer-kit

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

1.4k installsAudited
LElearn logo

learn

giuseppe-trisciuoglio/developer-kit

Provides autonomous project pattern learning by analyzing the codebase to discover development conventions, architectural patterns, and coding standards, then generates project rule files in .claude/rules/. Use when user asks to "learn from project", "extract project rules", "analyze codebase conventions", "discover project patterns", or wants to auto-generate Claude Code rules for the current project.

953 installsAudited
MEmemory-md-management logo

memory-md-management

giuseppe-trisciuoglio/developer-kit

Provides comprehensive memory file management capabilities including auditing, quality assessment, and targeted improvements for files such as CLAUDE.md. Use when user asks to check, audit, update, improve, fix, maintain, or validate project memory files. Also triggers for "project memory optimization", "CLAUDE.md quality check", "documentation review", or when a project memory file needs to be created from scratch. This skill scans memory files, evaluates quality against standardized criteria, outputs detailed quality reports with scores and recommendations, then makes targeted updates with user approval.

1.1k installsAudited
NEnestjs logo

nestjs

giuseppe-trisciuoglio/developer-kit

NestJS framework patterns with Drizzle ORM for building scalable REST/GraphQL APIs and microservices.

1.8k installs