当前位置:   article > 正文

1. LangChain4j 之入门基础(简单易学)_langchain4j 教程

langchain4j 教程

一:前言

        什么是LangChain?而LangChain4j又是什么?可以点击下面的链接进行查看.

1分钟了解LangChain是什么? | 1分钟了解LangChain4j是什么? LangChain4j是LangChain的Java版本,帮助开发者很容易的接入大模型的框架。让Java也能捉住大模型的风口。


二:前置知识

        当我们想要用什么功能的时候,就使用对应的模型来创建对象,进行使用。LangChain4j提供了如下几种模型来使用。

模型

  • ChatLanguageModel:表示具有聊天界面的语言模型。
  • ImageModel:文本到图像生成器模型。文生图模型,一般我们会把生成图片的提示词输入给chatGpt,让它帮我们优化一下这个提示词,然后拿着优化的提示词用ModerationModel敏感字检查,检查通过后,拿着这个优化的提示词,输入给ImageModel 模型
  • StreamingLanguageModel:表示一种语言模型,该模型具有简单的文本界面(与聊天界面相对),并且每次可以流式传输一个令牌响应。(可以做到打字机流式响应)
  • ModerationModel:表示可以调节文本的模型,判断输入的文字是否有敏感词。
  • EmbeddingModel:表示可以将给定文本转换为嵌入(文本的向量表示)的模型
  • ScoringModel:能够根据查询对文本进行评分的模型。在针对同一查询对多个文本进行评分时,用于识别最相关的文本。评分模型可以用于重新排名的目的。

消息类型

  • UserMessage 用户发送给大模型的消息

        表示来自用户(通常是应用程序的最终用户)的消息。根据模型支持的模式(文本、图像、音频、视频等),用户消息可以包含单个文本(字符串)或多个内容(可以是TextContent或ImageContent)。在未来,内容类型列表将扩展以允许更多的模式(例如音频、视频等)。用户消息还可以包含用户的名称。请注意,并非所有模型都支持UserMessage中的名称。

  • AiMessage  大模型响应给用户的消息

        表示来自AI(语言模型)的响应消息。消息可以包含文本响应或执行一个/多个工具的请求。在工具执行的情况下,对该消息的响应应该是一个/多个ToolExecutionResultMessage。

  • SystemMessage  发送给大模型配置的消息

        表示系统消息,通常由开发人员定义。这种类型的信息通常提供有关AI行动的指示,例如其行为或响应风格。

  • ToolExecutionResultMessage 工具执行的结果消息

        表示响应ToolExecutionRequest的工具执行的结果。ToolExecutionRequests来自于之前的AiMessage.toolExecutionRequests()。

LangChain4j暂时所支持的大模型,如下:

ProviderStreamingToolsImage InputsLocalNative
Amazon Bedrock
Anthropic
Azure OpenAI
ChatGLM
DashScope
Google Vertex AI Gemini
Google Vertex AI PaLM 2
Hugging Face
Jlama
LocalAI
Mistral AI
Ollama
OpenAICompatible with: Groq, Ollama, LM Studio, GPT4All, etc.
Qianfan
Cloudflare Workers AI
Zhipu AI

三:案例实践

引入Maven依赖,现在我们使用LangChain4j最新的版本 0.32.0,暂时引入的模型有openAi和智普Ai的依赖。如果用其他的大模型,引入相应的依赖就可以。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.gorgor</groupId>
  7. <artifactId>ai-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <maven.compiler.source>17</maven.compiler.source>
  11. <maven.compiler.target>17</maven.compiler.target>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <langchain4j.version>0.32.0</langchain4j.version>
  14. <jackson.version>2.16.1</jackson.version>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>dev.langchain4j</groupId>
  19. <artifactId>langchain4j</artifactId>
  20. <version>${langchain4j.version}</version>
  21. </dependency>
  22. <!-- open Ai -->
  23. <dependency>
  24. <groupId>dev.langchain4j</groupId>
  25. <artifactId>langchain4j-open-ai</artifactId>
  26. <version>${langchain4j.version}</version>
  27. </dependency>
  28. <!-- 智普 Ai -->
  29. <dependency>
  30. <groupId>dev.langchain4j</groupId>
  31. <artifactId>langchain4j-zhipu-ai</artifactId>
  32. <version>${langchain4j.version}</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.tinylog</groupId>
  36. <artifactId>tinylog-impl</artifactId>
  37. <version>2.6.2</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.tinylog</groupId>
  41. <artifactId>slf4j-tinylog</artifactId>
  42. <version>2.6.2</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>com.fasterxml.jackson.core</groupId>
  46. <artifactId>jackson-databind</artifactId>
  47. <version>${jackson.version}</version>
  48. </dependency>
  49. </dependencies>
  50. </project>

案例一:普通聊天

        普通聊天的话,我们只需要创建ChatLanguageModel(如有不懂,可以看上面的前置知识中的解释)对象就可以,

1. 使用openAi

   此时我们需要登录 openai的官网 https://openai.com/,注册账号,点击API login进行登录,然后在里面找到apikey,需要我们用手机号码注册一个apikey,但openai封掉了亚洲很多节点,所以亚洲的手机号可能都注册不了apikey,需要用其他国家地区的, 但LangChain4j有提供了openAi的demo的apikey,我们可以用demo这个apikey就可以去调openAi大模型。但这个key限制也很多,比如文生图等等就用不了。

  1. ChatLanguageModel model = OpenAiChatModel.builder()
  2. .apiKey("demo")
  3. .build();
  4. String answer = model.generate("你好,你是谁?");
  5. System.out.println(answer);

 2. 使用智普Ai

         因为openAi是国外的,有很多限制,所以下面的案例都会用智普Ai来做,智普Ai是由清华大学计算机系知识工程实验室的技术成果转化而来。官网:智谱AI开放平台 ,注册登录,并获取apikey,大家可以充一块钱去玩玩,一块钱可以玩很久。

  1. ChatLanguageModel chatModel = ZhipuAiChatModel.builder()
  2. .apiKey("智普apikey")
  3. .build();
  4. String answer = chatModel.generate("你好,你是谁?");
  5. System.out.println(answer);

案例二:打字机流式响应

在前面的例子中,当我们通过ChatLanguageModel的generate()方法向大模型提问时,ChatLanguageModel一次性给了整段响应结果,而不是一个字一个字打字机式的回答,不过我们可以使用OpenAiStreamingChatModel来实现打字机效果,代码如下:

  1. StreamingChatLanguageModel model = ZhipuAiStreamingChatModel.builder()
  2. .apiKey("智普apikey")
  3. .build();
  4. model.generate("你好,你是谁?", new StreamingResponseHandler<AiMessage>() {
  5. @Override
  6. public void onNext(String token) {
  7. System.out.println(token);
  8. try {
  9. TimeUnit.SECONDS.sleep(1);
  10. } catch (InterruptedException e) {
  11. throw new RuntimeException(e);
  12. }
  13. }
  14. @Override
  15. public void onError(Throwable error) {
  16. System.out.println(error);
  17. }
  18. });

案例三: 检测是否存在敏感内容

 ModerationModel能够校验输入中是否存在敏感内容。在智普Ai中没找到提供这个敏感内容检测的api,所有下面案例用openai写。

  1. ModerationModel moderationModel = OpenAiModerationModel.withApiKey("demo");
  2. Response<Moderation> response = moderationModel.moderate("我要杀了你");
  3. System.out.println(response.content().flaggedText());

案例四:文生图

ImageModel可以根据提示词来生成图片,一般我们会把生成图片的提示词输入给chatGpt,让它帮我们优化一下这个提示词,然后拿着优化的提示词用ModerationModel敏感字检查,检查通过后,拿着这个优化的提示词,输入给ImageModel 模型

  1. ImageModel imageModel = ZhipuAiImageModel.builder()
  2. .apiKey("智普apikey")
  3. .build();
  4. Response<Image> response = imageModel.generate("小猫");
  5. System.out.println(response.content().url());

 案例五:获取当前时间

  对于大模型而言,数据都是基于过往历史数据进行训练的,如果你问他"今天是几号?",可能他会懵逼,回答补上来.此时就要用到LangChain4j的Tools工具,而在Spring Ai中不叫Tools,而是Function call.

执行流程: 先请求智普Ai大模型 --->得到执行工具请求-->执行本地工具->再次通过请求问题,执行工具请求和执行工具结果,去调用智普Ai大模型,得到最终的接口. 执行了本地工具后,不是得到结果了吗?为什么还需要调大模型, 是因为执行工具后的结果只是几月几号,而不像人回复那样,所以重新调了一次.

  1. ChatLanguageModel chatModel = ZhipuAiChatModel.builder()
  2. .apiKey("智普apikey")
  3. .build();
  4. ToolSpecification currentTime = ToolSpecification.builder()
  5. .name("currentTime")
  6. .description("currentTime")
  7. .build();
  8. // given
  9. UserMessage userMessage = userMessage("今天是几号?");
  10. List<ToolSpecification> toolSpecifications = singletonList(currentTime);
  11. // when
  12. //执行工具响应(请求),大模型回调工具
  13. Response<AiMessage> response = chatModel.generate(singletonList(userMessage), toolSpecifications);
  14. // then
  15. AiMessage aiMessage = response.content();
  16. ToolExecutionRequest toolExecutionRequest = aiMessage.toolExecutionRequests().get(0);
  17. // given
  18. //执行工具结果
  19. ToolExecutionResultMessage toolExecutionResultMessage = from(toolExecutionRequest, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  20. // 请求问题(userMessage) | 执行工具响应(aiMessage) | 执行工具结果(toolExecutionResultMessage)
  21. List<ChatMessage> messages = asList(userMessage, aiMessage, toolExecutionResultMessage);
  22. // when
  23. //最终结果
  24. Response<AiMessage> secondResponse = chatModel.generate(messages);
  25. System.out.println(secondResponse.content().text());

四: LangChain4j和SpringBoot整合

        本来是想对接智普Ai的,但好像没看到智普Ai跟springboot整合的maven包, 但百度的qianfan就有. 下面用openai整个springboot.

maven依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.gorgor</groupId>
  7. <artifactId>ai-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>3.2.1</version>
  13. </parent>
  14. <properties>
  15. <maven.compiler.source>17</maven.compiler.source>
  16. <maven.compiler.target>17</maven.compiler.target>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <langchain4j.version>0.32.0</langchain4j.version>
  19. <jackson.version>2.16.1</jackson.version>
  20. </properties>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>dev.langchain4j</groupId>
  28. <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
  29. <version>${langchain4j.version}</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>dev.langchain4j</groupId>
  33. <artifactId>langchain4j</artifactId>
  34. <version>${langchain4j.version}</version>
  35. </dependency>
  36. <!-- open Ai -->
  37. <dependency>
  38. <groupId>dev.langchain4j</groupId>
  39. <artifactId>langchain4j-open-ai</artifactId>
  40. <version>${langchain4j.version}</version>
  41. </dependency>
  42. <!-- 智普 Ai -->
  43. <dependency>
  44. <groupId>dev.langchain4j</groupId>
  45. <artifactId>langchain4j-zhipu-ai</artifactId>
  46. <version>${langchain4j.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>com.fasterxml.jackson.core</groupId>
  50. <artifactId>jackson-databind</artifactId>
  51. <version>${jackson.version}</version>
  52. </dependency>
  53. </dependencies>
  54. </project>

application.yml 配置文件

  1. langchain4j:
  2. open-ai:
  3. chat-model:
  4. api-key: demo

代码:

  1. @RestController
  2. public class Demo {
  3. @Autowired
  4. private ChatLanguageModel chatLanguageModel;
  5. @GetMapping("testSpringboot")
  6. public String testSpringboot(String name){
  7. return chatLanguageModel.generate(name);
  8. }
  9. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/978542
推荐阅读
相关标签
  

闽ICP备14008679号