LangChain4j LangChain集成到JAVA应用

一、LangChain4j 介绍

github地址:

https://github.com/langchain4j/langchain4j

首先介绍LangChain4j是什么:

LangChain4j 的目标是简化将 AI/LLM 功能集成到 Java 应用程序中。

可以看下官网介绍:

  1. Unified APIs: LLM providers (like OpenAI or Google Vertex AI) and embedding (vector) stores (such as Pinecone or Vespa) use proprietary APIs. LangChain4j offers a unified API to avoid the need for learning and implementing specific APIs for each of them. To experiment with a different LLM or embedding store, you can easily switch between them without the need to rewrite your code. LangChain4j currently supports over 10 popular LLM providers and more than 15 embedding stores. Think of it as a Hibernate, but for LLMs and embedding stores.
  2. Comprehensive Toolbox: During the past year, the community has been building numerous LLM-powered applications, identifying common patterns, abstractions, and techniques. LangChain4j has refined these into practical code. Our toolbox includes tools ranging from low-level prompt templating, memory management, and output parsing to high-level patterns like Agents and RAGs. For each pattern and abstraction, we provide an interface along with multiple ready-to-use implementations based on proven techniques. Whether you're building a chatbot or developing a RAG with a complete pipeline from data ingestion to retrieval, LangChain4j offers a wide variety of options.
  3. Numerous Examples: These examples showcase how to begin creating various LLM-powered applications, providing inspiration and enabling you to start building quickly.

二、项目集成

1. 下载Maven依赖

依赖地址如下:

  <dependency>
      <groupId>dev.langchain4j</groupId>
      <artifactId>langchain4j-open-ai</artifactId>
      <version>0.29.1</version>
  </dependency>

除了openAi,LangChain4j 还集成了多种LLMS,基本hugging face 热门的LLMS LangChain4j 都有兼容。

2. ChatLanguageModel

ChatLanguageModel接收多个CharMessages作为输入并返回的AiMessage,ChatLanguageModel属于LangChain4j的基础API,下面我们看下调用示例:

    public static void main(String[] args) {
        String me = "helloWord!";
        System.out.println("用户:" + me);
        OpenAiChatModel demo = OpenAiChatModel.withApiKey("demo");
        String content = demo.generate(me);
        System.out.println("AI:" + content);
    }

该示例通过generate方法将String作为输入并返回String类型的content作为输出。

注:这只是最简单的实现方式,OpenAiChatModel提供了多种属性用于灵活配置自己的LLM。

OpenAiChatModel chatGlmChatModel = OpenAiChatModel.builder()
                // 模型地址
                .baseUrl("http://127.0.0.1:8305/v1/")
                // 模型key
                .apiKey("EMPTY")
                // 最大令牌数
                .maxTokens(1000)
                // 精确度
                .temperature(0d)
                // 超时时间
                .timeout(Duration.ofSeconds(3))
                // 模型名称
                .modelName("chat-gpt")
                // 重试次数
                .maxRetries(3)
                .build();

三、ChatMessage

1.ChatMessage

通过上面的方法,我们可以实现和AI和对话并得到AI输出的答案,但实际开发中generate实际接受的是ChatMessage类型的参数。

ChatMessage代表聊天消息的基本接口。

2. 消息类型

LangChain4j目前支持四种类型的聊天信息,每种类型对应消息的来源:

UserMessage:用户类型消息,可以包含文本(String)或者图像(Image)。

AiMessage:AI类型消息,通常是响应UserMessage,OpenAiChatModel的generate方法在接受到Message类型的消息时,会返回一个Reponse。

 UserMessage userForm = UserMessage.from("hello!");
 Response<AiMessage> generate = chatGlmChatModel.generate(userForm);
 System.out.println(generate);

ToolExecutionResultMessage:这是 ToolExecutionRequest 的结果。

SystemMessage:系统类型消息,作为开发人员在构建prompt的时候,需要提前引导LLM在这次对话中的角色、表现、风格等,LLM受过训练,它更关注SystemMessage类型的消息,所以SystemMessage类型的消息一般放在开头。

3. 多轮ChatMessage

上面所演示的所有情况只是单轮对话的输入输出,如果想支持多轮对话,要注意的是管理对话的状态,假设您想构建一个聊天机器人。想象一下用户和聊天机器人 (AI) 之间的简单多轮对话:

  • 用户:你好,我叫克劳斯
  • AI:嗨,Klaus,有什么可以帮您的吗?
  • 用户:我叫什么名字?
  • 人工智能:克劳斯

交互状态如下所示:

UserMessage firstUserMessage = UserMessage.from("Hello, my name is Klaus");
AiMessage firstAiMessage = model.generate(firstUserMessage).content(); // Hi Klaus, how can I help you?
UserMessage secondUserMessage = UserMessage.from("What is my name?");
AiMessage secondAiMessage = model.generate(firstUserMessage, firstAiMessage, secondUserMessage).content(); // Klaus

我们在第二次的generate方法中,不仅提供了secondUserMessage 还提供对话中之前的消息firstUserMessage。

但是手动管理和维护这些消息链非常麻烦,因此LangChain4j 提供了ChatMemory用来管理消息。

后续ChatMemory相关内容:

LangChain4j AiServices 实现聊天记忆-CSDN博客

### 如何将 LangChain4J 与 Spring Boot 集成 LangChain4J 是一种用于构建链式调用的语言模型库,而 Spring Boot 则是一个流行的微服务框架。为了实现两者的集成,可以遵循以下方法: #### 创建 Maven 或 Gradle 项目结构 确保项目的 `pom.xml` 文件中包含了必要的依赖项来支持 LangChain4J 和 Spring Boot 的功能。 对于 Maven 用户来说,在 pom 中加入如下依赖: ```xml <dependency> <groupId>com.langchain4j</groupId> <artifactId>langchain4j-core</artifactId> <version>${langchain4j.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 而对于使用 Gradle 构建工具的人来说,则应在 build.gradle 添加这些行: ```groovy implementation 'com.langchain4j:langchain4j-core:${langchain4j_version}' implementation 'org.springframework.boot:spring-boot-starter-web' ``` #### 初始化配置类 创建一个新的 Java 类并标注为 `@Configuration` 来定义应用程序上下文中所需的 Bean 实例化逻辑。这一步骤类似于通过启用 JPA 存储库的方式来进行设置[^2]。 ```java import com.langchain4j.LangChain; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public LangChain langChain() { return new LangChain.Builder().build(); } } ``` #### 控制器层开发 编写 RESTful API 接口以便外部系统能够访问由 LangChain 提供的服务。这里展示了一个简单的例子,其中 GET 请求会触发一次基于 LangChain 的处理过程。 ```java @RestController @RequestMapping("/api/langchain") public class LangChainController { private final LangChain langChain; public LangChainController(LangChain langChain) { this.langChain = langChain; } @GetMapping("/process") public String processRequest(@RequestParam String inputText) { // 使用 LangChain 进行业务逻辑操作... var result = langChain.process(inputText); return "Processed text: " + result; } } ``` 以上就是关于如何把 LangChain4J 融入到现有的 Spring Boot 应用程序中的基本指导说明。需要注意的是实际应用过程中可能还需要考虑更多细节问题比如异常捕获机制、日志记录策略等方面的内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值