北京建网站上海的建设网站
2026/4/6 6:06:58 网站建设 项目流程
北京建网站,上海的建设网站,10个好用的wordpress投票_评分插件,商贸有限公司名称大全✅ LangChain4j AI Services 核心实战代码#xff08;2大高频场景#xff09; 基于官方文档「AI Services」#xff0c;为你提供 结构化输出JSON模式配置、Spring Boot多AI Service协作 两套可直接复制运行的完整代码#xff0c;包含✅依赖配置、✅核心代码、✅调用示例、…✅ LangChain4j AI Services 核心实战代码2大高频场景基于官方文档「AI Services」为你提供结构化输出JSON模式配置、Spring Boot多AI Service协作两套可直接复制运行的完整代码包含✅依赖配置、✅核心代码、✅调用示例、✅关键注解解释、✅避坑要点完美贴合生产级开发规范。 环境前置约束必满足JDK 17、Spring Boot 3.x、LangChain4j 0.26.0版本统一 场景一结构化输出 JSON模式配置核心高频✅ 核心价值解决LLM返回「非结构化文本」的痛点让大模型严格返回指定Java POJO格式数据无需手动解析JSON字符串开启JSON模式后LLM输出100%符合格式要求彻底避免解析异常是生产环境必备配置。✅ 步骤1完整Maven依赖直接复制到pom.xml?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion3.2.1/versionrelativePath//parentgroupIdcom.example/groupIdartifactIdlangchain4j-ai-service/artifactIdversion0.0.1-SNAPSHOT/versionpropertiesjava.version17/java.versionlangchain4j.version0.26.0/langchain4j.version/propertiesdependencies!-- Spring Web 基础依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- LangChain4j Spring核心启动器 --dependencygroupIddev.langchain4j/groupIdartifactIdlangchain4j-spring-boot-starter/artifactIdversion${langchain4j.version}/version/dependency!-- OpenAI适配器含JSON模式支持可替换为Ollama/通义千问 --dependencygroupIddev.langchain4j/groupIdartifactIdlangchain4j-open-ai-spring-boot-starter/artifactIdversion${langchain4j.version}/version/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project✅ 步骤2application.yml配置开启JSON模式密钥配置# 核心开启JSON模式 模型参数优化保证结构化输出准确性langchain4j:open-ai:api-key:sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx# 替换为你的真实密钥chat-model:model-name:gpt-3.5-turbo# 推荐3.5/4o均完美支持JSON模式temperature:0.0# 结构化输出建议0保证结果稳定无随机性timeout:60s# ✅ 关键配置开启JSON模式强制LLM输出标准JSONresponse-format:json_object✅ 步骤3定义结构化返回的POJO实体核心根据业务需求定义任意Java实体类支持嵌套对象、枚举、基础类型LangChain4j会自动完成LLM输出 → POJO的映射。packagecom.example.entity;importlombok.Data;importjava.util.List;/** * 示例商品信息结构化实体可根据业务自定义 */Data// Lombok简化get/set无Lombok可手动编写publicclassProductInfo{// 基础字段privateStringproductName;// 商品名称privateDoubleprice;// 商品价格privateIntegerstock;// 库存数量// 嵌套集合字段privateListStringtags;// 商品标签如热销、新品// 嵌套对象字段privateMerchantmerchant;// 商家信息/** * 嵌套实体类 */DatapublicstaticclassMerchant{privateStringmerchantName;// 商家名称privateStringcontactPhone;// 联系电话}}✅ 步骤4编写AI Service接口声明式无实现类核心特点返回值直接指定POJO类型框架自动完成「LLM JSON输出 → Java对象」的转换零解析代码。packagecom.example.service;importcom.example.entity.ProductInfo;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.UserMessage;importdev.langchain4j.service.spring.AiService;/** * 结构化输出AI服务接口核心 */AiService// ✅ 标记为AI服务框架自动生成代理实现publicinterfaceProductAnalysisService{/** * 从用户输入中提取商品信息返回结构化POJO * param userDesc 用户输入的商品描述文本 * return 结构化的商品信息实体 */SystemMessage({你是一个专业的信息提取专家严格按照要求提取数据并返回JSON格式,必须完全匹配指定的字段名字段类型严格对应价格为Double、库存为Integer,无数据的字段填充null禁止新增未定义的字段})UserMessage(从以下文本中提取商品信息{{userDesc}})ProductInfoextractProductInfo(UserMessageStringuserDesc);}✅ 步骤5调用测试Controller单元测试双版本✅ 方式1Controller接口调用Web测试packagecom.example.controller;importcom.example.entity.ProductInfo;importcom.example.service.ProductAnalysisService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassStructOutputController{AutowiredprivateProductAnalysisServiceproductAnalysisService;// 测试地址http://localhost:8080/extract?desc苹果手机15Pro售价5999元库存100台标签有旗舰、5G商家是苹果官方店电话10086GetMapping(/extract)publicProductInfoextract(RequestParamStringdesc){// ✅ 直接返回POJO框架自动完成所有转换returnproductAnalysisService.extractProductInfo(desc);}}✅ 方式2单元测试更便捷无需启动Webpackagecom.example;importcom.example.entity.ProductInfo;importcom.example.service.ProductAnalysisService;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;SpringBootTestclassAiServiceApplicationTests{AutowiredprivateProductAnalysisServiceproductAnalysisService;TestvoidtestStructOutput(){StringuserDesc华为Mate70售价4999元库存200台标签有鸿蒙、拍照、续航商家是华为旗舰店电话10010;ProductInfoproductInfoproductAnalysisService.extractProductInfo(userDesc);// 直接操作Java对象无需解析JSONSystem.out.println(商品名称productInfo.getProductName());System.out.println(商品价格productInfo.getPrice());System.out.println(商家名称productInfo.getMerchant().getMerchantName());}}✅ 结构化输出核心要点避坑✅response-format: json_object是强制配置缺失则LLM可能返回非JSON文本导致转换失败✅temperature: 0.0建议配置结构化输出追求「确定性」该参数可避免LLM生成随机内容✅ 系统提示词中明确字段约束类型、非空、字段名可大幅提升映射准确率✅ 支持的返回类型String/Boolean/Enum/任意POJO/ListPOJO完全覆盖业务场景。 场景二Spring Boot 多AI Service 协作生产级必备✅ 核心价值实际业务中AI能力往往需要拆分、复用、组合如「意图识别」→「专业问答」→「结果格式化」多AI Service协作可实现✅ 职责分离不同Service负责不同AI能力代码更整洁✅ 能力复用单个Service可被多个业务模块调用✅ 灵活组合结合Java原生逻辑if/else/循环实现复杂AI流程✅ 易测试可单独Mock某个Service不影响整体流程。✅ 整体设计思路本次实现3个AI Service协作完成「智能客服」流程 流程链路用户提问 → 「意图识别Service」判断问题类型 → 路由到「技术问答Service」/「闲聊Service」 → 返回最终结果✅ 步骤1编写3个职责分离的AI Service接口✅ ① 意图识别Service负责判断用户问题类型packagecom.example.service;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.UserMessage;importdev.langchain4j.service.spring.AiService;/** * 职责1意图识别判断用户问题是技术问题/闲聊 */AiServicepublicinterfaceIntentRecognitionService{SystemMessage({你是意图识别专家仅返回以下2个结果中的一个不返回任何额外内容,1. TECH_QUESTION技术相关问题,2. CHAT闲聊、问候等非技术问题})UserMessage(判断问题类型{{userQuestion}})StringrecognizeIntent(UserMessageStringuserQuestion);}✅ ② 技术问答Service负责解答Java/Spring技术问题packagecom.example.service;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.UserMessage;importdev.langchain4j.service.spring.AiService;/** * 职责2专业技术问答Java/Spring方向 */AiServicepublicinterfaceTechQaService{SystemMessage({你是资深Java架构师精通Spring Boot全家桶回答简洁、准确、干货,只回答技术问题非技术问题直接回复「不支持该类型问题」})UserMessage(解答技术问题{{question}})StringanswerTechQuestion(UserMessageStringquestion);}✅ ③ 闲聊Service负责处理问候、闲聊等非技术问题packagecom.example.service;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.UserMessage;importdev.langchain4j.service.spring.AiService;/** * 职责3闲聊互动处理问候、日常对话 */AiServicepublicinterfaceChatService{SystemMessage(你是一个友好的闲聊助手语气亲切回复简洁仅处理非技术闲聊)UserMessage(回复用户{{message}})Stringchat(UserMessageStringmessage);}✅ 步骤2编写「协作调度器」核心组合多AI Service创建普通Spring服务注入所有AI Service结合Java原生逻辑实现路由、组合这是多Service协作的核心入口。packagecom.example.service;importlombok.RequiredArgsConstructor;importorg.springframework.stereotype.Service;/** * 多AI Service协作调度器核心 * 整合所有AI能力对外提供统一入口 */Service// 普通Spring服务非AI ServiceRequiredArgsConstructor// Lombok注入所有依赖替代AutowiredpublicclassAiAssistantDispatcher{// ✅ 注入3个AI ServiceprivatefinalIntentRecognitionServiceintentRecognitionService;privatefinalTechQaServicetechQaService;privatefinalChatServicechatService;/** * 对外统一入口接收用户提问自动路由到对应AI Service */publicStringhandleUserQuestion(StringuserQuestion){// 1. 第一步调用意图识别Service判断问题类型StringintentintentRecognitionService.recognizeIntent(userQuestion);// 2. 第二步基于意图路由到不同的AI ServiceJava原生逻辑returnswitch(intent){caseTECH_QUESTION-techQaService.answerTechQuestion(userQuestion);caseCHAT-chatService.chat(userQuestion);default-暂无法识别你的问题类型请重新提问;};}}✅ 步骤3编写测试接口统一调用packagecom.example.controller;importcom.example.service.AiAssistantDispatcher;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassAiDispatcherController{AutowiredprivateAiAssistantDispatcheraiAssistantDispatcher;// 统一测试入口http://localhost:8080/ai/ask?questionSpring Bean生命周期是什么// 切换问题测试http://localhost:8080/ai/ask?question你好呀GetMapping(/ai/ask)publicStringask(RequestParamStringquestion){// ✅ 统一调用调度器无需关心内部多Service协作逻辑returnaiAssistantDispatcher.handleUserQuestion(question);}}✅ 多AI Service协作核心技巧生产级✅ 技巧1Service拆分原则按能力维度拆分意图识别、问答、翻译、提取、格式化各司其职按业务维度拆分订单AI服务、商品AI服务、用户AI服务贴合业务模块按模型维度拆分轻量任务用GPT-3.5复杂任务用GPT-4o低成本高性能兼顾。✅ 技巧2进阶协作方式复杂场景链式调用A→B→C前一个Service的输出作为后一个的输入如文本提取→翻译→格式化分支调用根据条件路由到不同Service本次示例并行调用多Service同时执行汇总结果如同时调用「情感分析」「关键词提取」嵌套调用在一个Service中注入另一个Service调度器模式。✅ 技巧3优雅注入替代Autowired推荐使用构造器注入LombokRequiredArgsConstructor符合Spring最佳实践所有AI Service均为单例Bean可安全注入、重复调用无性能问题。✅ 技巧4单元测试与Mock关键多Service协作时若需单独测试某个Service可通过Mock屏蔽其他依赖SpringBootTestclassTechQaServiceTest{// Mock意图识别Service避免真实调用MockBeanprivateIntentRecognitionServiceintentRecognitionService;// 注入真实的技术问答ServiceAutowiredprivateTechQaServicetechQaService;TestvoidtestTechQa(){StringresulttechQaService.answerTechQuestion(Spring Boot自动装配原理);System.out.println(result);}} 补充AI Services 核心注解速查表官方全量整理官方文档中所有高频注解开发时直接查阅无需翻文档注解核心作用AiService标记接口为AI服务框架自动生成代理实现类核心注解SystemMessage定义系统提示词约束AI角色/规则支持静态文本/资源文件加载fromResourceUserMessage定义用户输入模板支持{{变量}}占位符绑定方法参数AssistantMessage定义AI历史回复用于多轮对话上下文关联MemoryId标记会话ID实现多用户/多会话的独立记忆隔离多轮对话必备Tool标记工具方法让AI自动决定是否调用该方法完成任务Function CallingV(变量名)显式绑定方法参数到模板变量Spring环境中可省略自动匹配 最终总结结构化输出JSON模式是LangChain4j AI Services最核心的生产级能力解决了LLM输出格式混乱的痛点返回值直接用POJO接收零解析成本多AI Service协作通过「职责拆分调度组合」让AI能力复用性、可维护性翻倍完全贴合Spring开发思想核心优势声明式接口自动代理无冗余代码开发者只需关注「业务逻辑」无需关心LLM底层调用、格式转换、记忆管理版本兼容上述代码完全适配LangChain4j 0.26.0最新版与Spring Boot 3.x无缝集成。✅ 如需扩展其他能力如多轮对话记忆MemoryId、工具调用Tool、RAG集成可以随时告诉我我会为你补充对应的完整代码示例~

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询