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

一. 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 将答案映射为这些
### 集成LangChain4J与Spring Boot以提供AI服务 为了在Spring Boot项目中集成LangChain4J来提供AI服务,可以遵循以下方法: #### 1. 添加依赖项 首先,在`pom.xml`文件中加入LangChain4J库的相关依赖。这一步骤确保了开发环境能够识别并利用LangChain4J所提供的功能。 ```xml <dependency> <groupId>com.langchain4j</groupId> <artifactId>langchain4j-core</artifactId> <version>${latest.version}</version> </dependency> ``` 此操作允许开发者通过Maven管理工具轻松引入所需的类库[^1]。 #### 2. 创建配置类 接着创建一个新的Java配置类用于初始化LangChain4J组件和服务实例。此类通常会标注有`@Configuration`注解,并可能包含一些Bean定义以便于后续调用。 ```java @Configuration public class LangChainConfig { @Bean public ChainService chainService() { return new DefaultChainService(); } } ``` 这段代码展示了如何声明一个名为`chainService()`的方法返回类型为`ChainService`的对象作为Spring容器中的bean。 #### 3. 构建控制器接口 随后构建RESTful API端点供外部访问这些由LangChain4J支持的服务逻辑。这里展示了一个简单的例子——处理密码找回请求的功能实现方式。 ```java @RestController @RequestMapping("/api/langchain") public class LangChainController { private final ChainService chainService; @Autowired public LangChainController(ChainService chainService) { this.chainService = chainService; } @PostMapping("/forget-password") public ResponseEntity<Map<String, Object>> forgetPassword(@RequestBody User form, HttpServletRequest request) { try { // 调用LangChain4J业务逻辑... boolean result = chainService.forgetPassword(form.getEmail()); if (result) { return ResponseEntity.ok().body(Collections.singletonMap("message", "Email sent")); } else { throw new RuntimeException("Failed to send email"); } } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 上述示例说明了如何接收来自客户端的数据并通过注入的`chainService`对象执行具体的操作[^4]。 #### 4. 测试API 最后不要忘记编写单元测试验证新添加的功能是否按预期工作。可以通过MockMvc或其他类似的框架来进行模拟HTTP请求和响应的过程检验。 ```java @SpringBootTest class LangChainApplicationTests { @Autowired private MockMvc mockMvc; @Test void testForgetPasswordApi() throws Exception { String jsonContent = "{\"email\":\"test@example.com\"}"; MvcResult mvcResult = mockMvc.perform(post("/api/langchain/forget-password") .contentType(MediaType.APPLICATION_JSON) .content(jsonContent)) .andExpect(status().isOk()) .andReturn(); assertEquals("{\"message\":\"Email sent\"}", mvcResult.getResponse().getContentAsString()); } } ``` 以上就是将LangChain4J成功嵌入到基于Spring Boot的应用程序内的基本流程介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

roman_日积跬步-终至千里

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

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

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

打赏作者

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

抵扣说明:

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

余额充值