关于 langchain4j-spring-boot-integration
面向在 Spring Boot 应用中集成 LangChain4j 的开发者,介绍自动配置、声明式 AI 服务和模型配置。还涵盖对话记忆、RAG、工具集成及多模型提供方配置。
主要功能
- 01通过属性配置模型与自动装配
- 02定义声明式 AI 服务
- 03设置对话记忆与流式响应
- 04集成 Spring Data RAG
- 05将 Spring 组件注册为工具
- 06显式配置多个模型提供方
适用场景
- 01为现有 Spring Boot 应用加入 AI 能力
- 02构建 AI 微服务
- 03创建具备对话记忆的服务
- 04在 Spring 应用中实现 RAG 和工具调用
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ giuseppe-trisciuoglio/ developer-kit --skill langchain4j-spring-boot-integration安装后在 Claude Code 中输入/langchain4j-spring-boot-integration确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/configuration.mdexamples.mdreferences.md详细介绍
LangChain4j Spring Boot 集成
通过声明式 AI 服务、自动配置和 Spring Boot starter 将 LangChain4j 集成到 Spring Boot。配置 AI 模型 Bean,设置聊天记忆,使用 Spring Data 实现 RAG 管道,并构建可用于生产环境的 AI 应用。
适用场景
在以下情况下使用此技能:
- 将 LangChain4j 集成到现有的 Spring Boot 应用中
- 使用 Spring Boot 构建 AI 驱动的微服务
- 使用
@Bean注解配置 AI 模型 Bean - 为 AI 模型和服务设置自动配置
- 使用 Spring 依赖注入创建声明式 AI 服务
- 通过 Spring Data 集成实现 RAG 系统
- 使用 Spring 上下文管理设置聊天记忆
- 配置多个 AI 提供商(OpenAI、Azure、Ollama、Anthropic)
- 使用 Spring Boot 构建可用于生产环境的 AI 应用
概述
LangChain4j Spring Boot 集成通过 Spring Boot starter 提供声明式 AI 服务,可根据属性自动配置 AI 组件。使用基于接口定义和注解的方式,将 Spring 依赖注入与 LangChain4j 的 AI 功能结合起来。
说明
1. 添加依赖
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
2. 配置应用属性
# 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
或者使用 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. 创建声明式 AI 服务
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. 启用组件扫描
@SpringBootApplication
@ComponentScan(basePackages = {
"com.yourcompany",
"dev.langchain4j.service.spring"
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. 注入并使用 AI 服务
@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. 验证集成
完成设置后,验证配置:
- 启动应用,并检查日志中是否已激活
LangChain4jSpringBootAutoConfiguration - 确认 AI 服务 Bean 已注册:在 Spring 上下文中查找
CustomerSupportAssistant - 测试服务:调用
assistant.handleInquiry("test"),并确认返回了响应
配置
基于属性的配置: 通过 application.properties 为不同提供商配置 AI 模型。
手动 Bean 配置: 如需高级配置,可手动定义 Bean:
@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();
}
}
多个提供商: 配置多个 AI 提供商时,使用显式连接:
@AiService(wiringMode = WiringMode.EXPLICIT)
interface MultiProviderAssistant {
@AiServiceAnnotation
ChatModel openAiModel;
@AiServiceAnnotation
ChatModel azureModel;
}
声明式 AI 服务
基本 AI 服务: 使用 @AiService 注解创建接口,并通过消息模板定义方法。
流式 AI 服务: 使用 Project Reactor 实现流式响应:
@AiService
public interface StreamingAssistant {
@SystemMessage("You are a helpful assistant.")
Flux<String> chatStream(String message);
}
聊天记忆: 使用 Spring 上下文设置对话记忆:
@AiService
public interface ConversationalAssistant {
@SystemMessage("You are a helpful assistant with memory.")
String chat(@MemoryId String userId, String message);
}
RAG 实现
嵌入存储: 为 RAG 管道配置 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);
}
文档摄取: 使用 ContentInjector 和 DocumentSplitter 处理文档。
内容检索: 配置 EmbeddingStoreContentRetriever 以增强知识。
工具集成
Spring 组件工具: 将工具定义为 Spring 组件:
@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);
}
示例
基本 AI 服务
@AiService
public interface ChatAssistant {
@SystemMessage("You are a helpful assistant.")
String chat(String message);
}
带记忆的 AI 服务
@AiService
public interface ConversationalAssistant {
@SystemMessage("You are a helpful assistant with memory of conversations.")
String chat(@MemoryId String userId, String message);
}
带工具的 AI 服务
@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);
}
更多示例(包括 RAG 配置、流式助手和多提供商设置),请参阅 references/examples.md。
最佳实践
- 使用基于属性的配置: 优先使用外部配置,而非硬编码值
- 使用 Profiles: 为开发、测试和生产环境分离配置
- 添加适当的日志记录: 调试 AI 服务调用并监控性能
- 实现重试机制: 使用退避策略处理暂时性故障
- 监控 Token 用量: 跟踪 Token 消耗并设置限制
参考资料
如需详细的 API 参考和高级配置:
约束和警告
- 使用环境变量或密钥管理系统安全地存储 API 密钥
- AI 模型的响应具有非确定性;测试应考虑这种可变性
- AI 提供商可能会实施速率限制;请采用适当的重试和退避策略
- 记忆提供商会存储对话历史;在多用户场景中,请实施清理机制
- Token 成本会迅速累积;请监控用量并设置 Token 限制
- 流式响应需要妥善处理部分失败
- 请查阅特定提供商的文档,了解支持的功能
- 配置了多个聊天模型时,请使用显式连线模式
- 在生产系统中使用 AI 生成的输出前,请先进行验证