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

相关推荐
rlpp2 小时前
FrankenPHP实践
java
Zachery Pole2 小时前
JAVA_07_面向对象
java·开发语言
shalou29012 小时前
mysql-connector-java 和 mysql-connector-j的区别
android·java·mysql
lipiaoshuigood2 小时前
Linux下启动redis
java
dc_00122 小时前
Java进阶——IO 流
java·开发语言·python
a1117762 小时前
Live2D 虚拟主播软件(开源Python)
java·linux·运维
me8322 小时前
【Java面试】Java核心关键字解析(static_final_访问修饰符)小白易懂
java·开发语言·面试
undefinedType2 小时前
rails知识扫盲
数据库·后端·敏捷开发
小飞学编程...2 小时前
【Java相关八股文(一)】
android·java·开发语言