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博客

  • 26
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值