1. LangChain4j 基础概念解析
LangChain4j 是一个专为 Java 生态设计的开源库,旨在简化大型语言模型(LLM)在 Java 应用中的集成过程。与 Python 生态中的 LangChain 不同,它并非简单移植,而是完全基于 Java 语言特性重新设计,包括类型安全、POJO、注解等 Java 开发者熟悉的编程范式。
这个库的核心价值在于提供了统一的 API 抽象层,目前已经整合了 20+ 主流 LLM 服务提供商和 30+ 向量数据库。想象一下,如果你需要从 OpenAI 切换到 Google Vertex AI,或者从 Pinecone 迁移到 Milvus,LangChain4j 让你只需修改配置而无需重写业务代码。
2. 环境准备与基础配置
2.1 依赖管理
对于 Maven 项目,首先需要在 pom.xml 中添加核心依赖:
<dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-core</artifactId> <version>0.35.0</version> </dependency>如果使用 Spring Boot,推荐使用专门的 starter:
<dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-spring-boot-starter</artifactId> <version>0.35.0</version> </dependency>2.2 基础配置示例
配置 OpenAI 服务的典型示例:
OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("your-api-key") .modelName("gpt-4") .temperature(0.3) .timeout(Duration.ofSeconds(60)) .build();关键参数说明:
modelName: 指定使用的模型版本temperature: 控制生成结果的随机性(0-1)timeout: 设置请求超时时间
3. 核心功能实践
3.1 对话记忆管理
LangChain4j 提供了完善的对话上下文管理机制:
ConversationMemory memory = MessageWindowChatMemory.withMaxMessages(10); AiServices<ChatAgent> agent = AiServices.builder(ChatAgent.class) .chatLanguageModel(model) .chatMemory(memory) .build(); String response = agent.chat("你好,我是小明"); // 后续对话会自动保持上下文 agent.chat("我刚才说我叫什么名字?");提示:对于生产环境,建议使用持久化存储的 ChatMemory 实现,如 RedisChatMemory
3.2 工具调用(Function Calling)
定义和使用自定义工具的完整流程:
- 首先定义工具接口:
interface Calculator { @Tool("计算两个数字的和") double add(double a, double b); }- 注册工具并创建服务:
Calculator calculator = new Calculator() { @Override public double add(double a, double b) { return a + b; } }; ChatAgent agent = AiServices.builder(ChatAgent.class) .chatLanguageModel(model) .tools(calculator) .build();- 使用工具:
String response = agent.chat("请计算3.14加2.71等于多少"); // 模型会自动调用计算工具并返回结果4. RAG 实现详解
检索增强生成(RAG)是 LangChain4j 的核心应用场景之一。以下是完整实现步骤:
4.1 文档处理流水线
// 1. 文档加载 DocumentLoader loader = new FileSystemDocumentLoader(Paths.get("data")); List<Document> documents = loader.load(); // 2. 文档分割 DocumentSplitter splitter = new DocumentByParagraphSplitter(500, 50); List<TextSegment> segments = splitter.split(documents); // 3. 向量化 EmbeddingModel embeddingModel = new OpenAiEmbeddingModel("your-api-key"); List<Embedding> embeddings = embeddingModel.embedAll(segments).content(); // 4. 存储到向量数据库 EmbeddingStore<TextSegment> store = new InMemoryEmbeddingStore<>(); store.addAll(embeddings, segments);4.2 检索与生成
Retriever<TextSegment> retriever = EmbeddingStoreRetriever.from(store, embeddingModel, 3); ChatModel chatModel = OpenAiChatModel.withApiKey("your-api-key"); Assistant assistant = AiServices.builder(Assistant.class) .chatLanguageModel(chatModel) .retriever(retriever) .build(); String answer = assistant.chat("请解释量子计算的基本原理");5. 性能优化与生产实践
5.1 批处理与缓存
// 启用嵌入缓存 EmbeddingModel embeddingModel = CachingEmbeddingModel.wrap( new OpenAiEmbeddingModel("your-api-key"), new RedisEmbeddingCache("redis://localhost") ); // 批量处理文档 List<Document> documents = // 加载文档 List<List<TextSegment>> batches = ListUtil.partition( splitter.split(documents), 50 // 每批50个片段 ); batches.forEach(batch -> { List<Embedding> embeddings = embeddingModel.embedAll(batch).content(); store.addAll(embeddings, batch); });5.2 监控与指标
集成 Micrometer 进行监控:
OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("your-api-key") .monitoring(new MicrometerChatModelMonitoring(meterRegistry)) .build();关键监控指标包括:
- 请求延迟分布
- 令牌使用量
- 错误率
- 速率限制情况
6. 常见问题排查
6.1 超时问题处理
OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("your-api-key") .timeout(Duration.ofSeconds(30)) .maxRetries(3) .retryer(Retryer.fixed(500)) // 500ms间隔重试 .build();6.2 内存管理
对于大文档处理:
DocumentSplitter splitter = new DocumentBySentenceSplitter( 300, // 最大token数 50, // 重叠token数 new OpenAiTokenizer("gpt-4") // 精确计算token );6.3 生产环境建议
- 使用连接池管理LLM API连接
- 实现回退策略(如主备模型切换)
- 添加速率限制和熔断机制
- 对敏感数据进行脱敏处理
7. 高级功能探索
7.1 自定义 ChatModelListener
Spring Boot 中实现自定义监听器:
@Component public class AuditChatModelListener implements ChatModelListener { private final AuditLogRepository repository; @Override public void onStart(ChatModelRequest request) { repository.logStart(request); } @Override public void onComplete(ChatModelResponse response) { repository.logComplete(response); } @Override public void onError(Throwable error) { repository.logError(error); } }注册监听器:
@Bean ChatModel openAiChatModel(List<ChatModelListener> listeners) { return OpenAiChatModel.builder() .apiKey(apiKey) .listeners(listeners) .build(); }7.2 与 Milvus 集成
EmbeddingStore<TextSegment> store = MilvusEmbeddingStore.builder() .host("localhost") .port(19530) .collectionName("docs") .dimension(1536) // OpenAI 嵌入维度 .build();关键配置参数:
metricType: 相似度计算方式(如 COSINE)indexType: 索引类型(如 IVF_FLAT)consistencyLevel: 一致性级别
8. 版本升级指南
从 0.34.x 升级到 0.35.0 的主要变化:
- 新增对 Google Gemini 1.5 的支持
- 优化了 RAG 流水线的内存效率
- 改进了 Spring Boot 自动配置
- 废弃了部分过时的 API
迁移注意事项:
- 检查自定义 EmbeddingStore 实现是否兼容新接口
- 测试 ChatMemory 的序列化兼容性
- 验证工具调用的参数传递方式