LangChain4j 与 SpringBoot 整合

https://docs.langchain4j.dev/tutorials/spring-boot-integration

无论是导入 low 还是 high 级别的依赖,可公用 yaml:

yaml 复制代码
langchain4j:
  open-ai:
    chat-model:
      api-key: ${ALI_QWEN_API_KEY} # 将会自动从本地环境变量获取
      model-name: qwen-plus
      log-requests: true
      log-responses: true
      base-url: https://dashscope.aliyuncs.com/compatible-mode/v1

低阶(Low level)集成

Spring Boot starter依赖项的命名约定是:langchain4j-{integration-name}-spring-boot-starter

例如,对于 OpenAI(langchain4j-open-ai),依赖项名称将是langchain4j-open-ai-spring-boot-starter

xml 复制代码
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
    <version>1.11.0-beta19</version>
</dependency>

controller

java 复制代码
@RestController
@RequestMapping("/low")
public class LowController {
    @Resource
    private ChatModel chatModelQwen;

    @GetMapping("/langchain4j/qwen")
    public String helloQwen(@RequestParam(value = "question", defaultValue = "你是谁?") String question) {
        String result = chatModelQwen.chat(question);
        return result;
    }
}

高阶(High level)集成

xml 复制代码
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-spring-boot-starter</artifactId>
    <version>1.11.0-beta19</version>
</dependency>

定义 AI 服务接口,使用 @AiService 声明:

java 复制代码
@AiService
public interface Assistant {
    String chat(String question);
}

注意,如果同时存在多个 ChatModelBean,请手动指定 chatModel

否则,报错:

java 复制代码
dev.langchain4j.service.IllegalConfigurationException: Conflict: multiple beans of type dev.langchain4j.model.chat.ChatModel are found: [chatModelQwen, openAiChatModel]. Please specify which one you wish to wire in the @AiService annotation like this: @AiService(wiringMode = EXPLICIT, chatModel = "<beanName>").
java 复制代码
@AiService(
        wiringMode = AiServiceWiringMode.EXPLICIT,
        chatModel = "chatModelQwen"
)
public interface Assistant {
    String chat(String question);
}

将 AI 服务接口作为 Service 使用:

java 复制代码
@RestController
@RequestMapping("/high")
public class HighController {
    @Resource
    private Assistant assistant;

    @GetMapping("/langchain4j/qwen")
    public String helloQwen(@RequestParam(value = "question", defaultValue = "你是谁?") String question) {
        return assistant.chat(question);
    }
}

http://localhost:9001/high/langchain4j/qwen?question=xxx

优先发在:https://juejin.cn/post/7606173847994122294

相关推荐
子兮曰5 分钟前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端
桦说编程5 分钟前
你的函数什么颜色?—— 深入理解异步编程的本质问题(上)
后端·性能优化·编程语言
百度地图汽车版1 小时前
【AI地图 Tech说】第九期:让智能体拥有记忆——打造千人千面的小度想想
前端·后端
臣妾没空1 小时前
Elpis 全栈框架:从构建到发布的完整实践总结
前端·后端
喷火龙8号1 小时前
单 Token 认证方案的进阶优化:透明刷新机制
后端·架构
孟沐1 小时前
Java异常处理知识点整理(大白话版)
后端
ServBay1 小时前
告别面条代码,PSL 5.0 重构 PHP 性能与安全天花板
后端·php
咕白m6252 小时前
Java 实现 Excel 转 HTML:完整示例
java
孟沐2 小时前
Java 面向对象核心知识点(封装 / 继承 / 重写 / 多态)
后端
RealPluto2 小时前
Spring AOP 失效排查
java·spring