【langchain4j】AIservices能够实现更加灵活的chain

langchain4j中AiServices的灵活应用

一. AI service介绍

AI Service提供了比chain更加简单、灵活的能力

AI Services provide a simpler and more flexible alternative to chains.

langchain4j在# Introduction 也介绍了:

Chains:为每个常见用例建立一个链,例如聊天机器人、RAG 等。链组合了多个低级组件并协调它们之间的交互。它们的主要问题是,如果您需要定制某些东西,它们就太僵化了。 LangChain4j 仅实现了两个 Chain(ConversationalChain 和 ConversationalRetrievalChain)。

推荐使用AiService,而且langchain4j也不会开发更多的链

Represents a chain step that takes an input and produces an output. Chains are not going to be developed further, it is recommended to use AiServices instead.

1. 如何工作的

AiServices提供了调用大模型的能力:将用户输入的信息转换为ChatMessage

[!NOTE]

  • 用户定义接口,AiServices转换这个接口
    You provide the Class of your interface to AiServices along with the low-level components, and AiServices creates a proxy object implementing this interface. Currently, it uses reflection, but we are considering alternatives as well. This proxy object handles all the conversions for inputs and outputs. In this case, the input is a single String, but we are using a ChatLanguageModel which takes ChatMessage as input.

  • 将用户的消息转换为UserMessage并调用的ChatLanguageModel
    So, AiService will automatically convert it into a UserMessage and invoke ChatLanguageModel. Since the output type of the chat method is a String, after ChatLanguageModel returns AiMessage, it will be converted into a String before being returned from the chat method.

 

2. AiServices提供的能力

参考代码:dev.langchain4j.service.AiServices

目前AiServices提供了以下能力:

message相关

  • message templates:Static system message templates, configured via @SystemMessage annotation on top of the method
    • system message templates:Dynamic system message templates, configured via systemMessageProvider(Function)
    • user message templates:Static user message templates, configured via @UserMessage annotation on top of the method
    • Dynamic user message templates, configured via method parameter annotated with @UserMessage

ChatMemory相关

  • Single (shared) ChatMemory, configured via chatMemory(ChatMemory)
  • Separate (per-user) ChatMemory, configured via chatMemoryProvider(ChatMemoryProvider) and a method parameter annotated with @MemoryId

RAG的能力

  • RAG, configured via contentRetriever(ContentRetriever) or retrievalAugmentor(RetrievalAugmentor)

相关工具

  • Tools, configured via tools(List) or tools(Object…) and methods annotated with @Tool

输出结构

  • Various method return types (output parsers), see more details below

返回流

  • Streaming (use TokenStream as a return type)

StructuredPrompt:ing结构化提示作为方法参数?

  • Structured prompts as method arguments (see @StructuredPrompt)

自动审核

  • Auto-moderation, configured via @Moderate annotation

注意暂不支持多模态

AI services currently do not support multimodality, please use the low-level API for this.

 

3. 支持的返回形式

定义的接口返回形式是灵活的,可按需选择

  1. 直接回答:如果你想直接获取模型生成的文本,可以使用 StringAiMessage。这对于简单的对话或问题回答非常有用。
  2. 集合类型:如果你希望模型将回答作为一个有序集合返回,比如以列表或项目符号的形式列出多个项,可以使用 List<String>Set<String>
  3. 分类任务:如果你希望模型执行分类任务(比如判断文本的类别),你可以使用枚举类型(Enum)或布尔值(boolean)。这意味着模型会返回一个有限的类别集合或一个简单的真/假值。
  4. 数据提取:当你希望从模型的回答中提取特定数据时,可以使用基本类型(如 intDouble 等)或者 Java 的日期、时间和数字类型(如 DateLocalDateTimeBigDecimal 等)。例如,你可以从模型的回答中提取一个特定的数字或者日期。
  5. 自定义对象:如果你希望模型返回的结果是某个自定义的 Java 对象(POJO),你可以定义自己的 Java 类并让 LLM 将答案映射为这些对象。这对于需要结构化输出的场景非常有用。
  6. 访问额外信息(如令牌使用量):如果你希望不仅获取模型的核心输出,还希望获取额外的元数据(如令牌使用量、来源信息等),你可以使用 Result<T> 类型。在这种情况下,T 代表你想要的具体数据类型,比如 Result<String>Result<MyCustomPojo>
  7. JSON 模式:对于自定义 POJO,使用 JSON 格式来接收数据是一种常见做法。如果 LLM 支持 JSON 格式,OpenAI 模型支持通过设置 responseFormat("json_object") 来启用 JSON 模式,这使得从模型的响应中提取结构化数据更加容易。

简单的说,langchain4j会基于你定义的返回格式而返回,而不是像llm只返回markdown格式的内容。
这比langchain确实要灵活

 

二. 简单的例子:接收用户消息,并按规定返回

1. 接收单个变量

  1. 定义接口+注解(不同注解代表不同类型的消息)可以接收Prompt消息
  2. 返回值可由用户自定义的类型返回,如下表示了:用户定义了四种情绪,langchain4j根据用户的输入,基于大模型只返回对应的感情词。
//因为只有一个变量,不用使用注解定义接收的变量名
public class Test {  
    public static void main(String[] args) {  

        SentimentAnalyzer assistant = AiServices  
                .builder(SentimentAnalyzer.class)  
                .chatLanguageModel(  
                        OpenAiChatModel.withApiKey(OPENAI_API_KEY)) // Deprecated it should use OpenAI LLM  
                .build();  
  
        Sentiment sentiment = assistant.analyzeSentimentOf("I love you"); 
        //输出结果是用户自定义的枚举中的一个 
        System.out.println(sentiment); // POSITIVE  
    }  
}  
  
enum Sentiment {  
    POSITIVE, NEUTRAL, NEGATIVE  
}  


interface SentimentAnalyzer {  
    @UserMessage("Analyze sentiment of {{it}}")  
    Sentiment analyzeSentimentOf(String text);  
}

 

2. 接收更多动态变量

接收两个变量需要通过注解来说明,文本(system、user的Prompt)中哪些变量被替换

/**
* 接收user和system的消息
* 动态接收language、text的值
*/
interface Translator {  
  
    @SystemMessage("You are a professional translator into {{language}}")  
    @UserMessage("Translate the following text: {{text}}")  
    String translate(@V("text") String text, @V("language") String language);  
}

了解了AiServices的基础使用,下面我们尝试一些RAG的能力
 

三. advanced RAG

提供如下能力:

  • QueryTransformer:转换查询
  • QueryRouter:路由查询
  • ContentRetriever:检索query
  • ContentAggregator:内容聚合
  • ContentInjector:内容注入

如下图展示了这些组件是如何配合构成一个复杂的chain
在这里插入图片描述

过程如下:

  1. 用户生成一个 UserMessage,该消息被转换为一个 Query。
  2. QueryTransformer 将 Query 转换为一个或多个 Query。
  3. 每个 Query 由 QueryRouter 路由到一个或多个 ContentRetriever。
  4. 每个 ContentRetriever 为每个 Query 检索相关的内容。
  5. ContentAggregator 将所有检索到的内容合并成一个最终的排序列表。
  6. 这个内容列表被注入到原始的 UserMessage 中。
  7. 最后,包含原始查询和注入的相关内容的 UserMessage 被发送到 LLM。

 

四. Chaining multiple AI Services:多个AiSerives合并到一起

AI Services可以与if/elseswitchfor/while进行结合判断

[!NOTE]
AI Services can be used as and combined with regular (deterministic) software components:

  • You can call one AI Service after another (aka chaining).
  • You can use deterministic and LLM-powered if/else statements (AI Services can return a boolean).
  • You can use deterministic and LLM-powered switch statements (AI Services can return an enum).
  • You can use deterministic and LLM-powered for/while loops (AI Services can return int and other numerical types).
  • You can mock an AI Service (since it is an interface) in your unit tests.
  • You can integration test each AI Service in isolation.
  • You can evaluate and find the optimal parameters for each AI Service separately.

如下连接两个AiServices的例子:
基于大模型的返回,java判断如果是简单的问候则直接输出预知好的文字,AiServices:ChatBot。


//1.我们使用了成本较低的 **Llama2** 来完成判断文本是否为问候语的简单任务,而使用成本较高的 **GPT-4** 结合内容检索器(RAG)来处理更复杂的任务。
//2.可以分别对 **GreetingExpert** 和 **ChatBot** 进行评估,找到每个子任务的最优参数,或者从长远来看,甚至为每个特定子任务微调一个小型的专用模型。

package com.qihoo.middle.nltosql.langchain4j.service;  
  
import dev.langchain4j.service.AiServices;  
import dev.langchain4j.service.SystemMessage;  
import dev.langchain4j.service.UserMessage;  
  
public class Test {  
    public static void main(String[] args) {  
        GreetingExpert greetingExpert = AiServices.create(GreetingExpert.class, llama2);  
  
        ChatBot chatBot = AiServices.builder(ChatBot.class)  
                .chatLanguageModel(gpt4)  
                .contentRetriever(milesOfSmilesContentRetriever)  
                .build();  
  
        MilesOfSmiles milesOfSmiles = new MilesOfSmiles(greetingExpert, chatBot);  
  
        String greeting = milesOfSmiles.handle("Hello");  
        System.out.println(greeting); // Greetings from Miles of Smiles! How can I make your day better?  
  
        String answer = milesOfSmiles.handle("Which services do you provide?");  
        System.out.println(answer); // At Miles of Smiles, we provide a wide range of services ...  
    }  
}  
interface GreetingExpert {  
    @UserMessage("Is the following text a greeting? Text: {{it}}")  
    boolean isGreeting(String text);  
}  
  
interface ChatBot {  
    @SystemMessage("You are a polite chatbot of a company called Miles of Smiles.")  
    String reply(String userMessage);  
}  
  
class MilesOfSmiles {  
  
    private final GreetingExpert greetingExpert;  
    private final ChatBot chatBot;  
    //通过java的逻辑来判断与大模型对话的意图。
    public String handle(String userMessage) {  
        if (greetingExpert.isGreeting(userMessage)) {  
            return "Greetings from Miles of Smiles! How can I make your day better?";  
        } else {  
            return chatBot.reply(userMessage);  
        }  
    }  
}

对于更复杂AiServices的交互逻辑,我们可以通过使用java的设计模型来串联起这些复杂的逻辑。

 

五. 相关教程:LangChain4j AiServices Tutorial

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

roman_日积跬步-终至千里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值