赞
踩
什么是LangChain?而LangChain4j又是什么?可以点击下面的链接进行查看.
1分钟了解LangChain是什么? | 1分钟了解LangChain4j是什么? LangChain4j是LangChain的Java版本,帮助开发者很容易的接入大模型的框架。让Java也能捉住大模型的风口。
当我们想要用什么功能的时候,就使用对应的模型来创建对象,进行使用。LangChain4j提供了如下几种模型来使用。
模型
消息类型
表示来自用户(通常是应用程序的最终用户)的消息。根据模型支持的模式(文本、图像、音频、视频等),用户消息可以包含单个文本(字符串)或多个内容(可以是TextContent或ImageContent)。在未来,内容类型列表将扩展以允许更多的模式(例如音频、视频等)。用户消息还可以包含用户的名称。请注意,并非所有模型都支持UserMessage中的名称。
表示来自AI(语言模型)的响应消息。消息可以包含文本响应或执行一个/多个工具的请求。在工具执行的情况下,对该消息的响应应该是一个/多个ToolExecutionResultMessage。
表示系统消息,通常由开发人员定义。这种类型的信息通常提供有关AI行动的指示,例如其行为或响应风格。
表示响应ToolExecutionRequest的工具执行的结果。ToolExecutionRequests来自于之前的AiMessage.toolExecutionRequests()。
LangChain4j暂时所支持的大模型,如下:
Provider | Streaming | Tools | Image Inputs | Local | Native |
---|---|---|---|---|---|
Amazon Bedrock | |||||
Anthropic | ✅ | ✅ | ✅ | ✅ | |
Azure OpenAI | ✅ | ✅ | ✅ | ||
ChatGLM | |||||
DashScope | ✅ | ✅ | ✅ | ||
Google Vertex AI Gemini | ✅ | ✅ | ✅ | ||
Google Vertex AI PaLM 2 | ✅ | ||||
Hugging Face | |||||
Jlama | ✅ | ✅ | ✅ | ||
LocalAI | ✅ | ✅ | ✅ | ||
Mistral AI | ✅ | ✅ | |||
Ollama | ✅ | ✅ | ✅ | ||
OpenAI | ✅ | ✅ | ✅ | Compatible with: Groq, Ollama, LM Studio, GPT4All, etc. | ✅ |
Qianfan | ✅ | ✅ | |||
Cloudflare Workers AI | |||||
Zhipu AI | ✅ | ✅ | ✅ |
引入Maven依赖,现在我们使用LangChain4j最新的版本 0.32.0,暂时引入的模型有openAi和智普Ai的依赖。如果用其他的大模型,引入相应的依赖就可以。
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.gorgor</groupId>
- <artifactId>ai-demo</artifactId>
- <version>1.0-SNAPSHOT</version>
-
- <properties>
- <maven.compiler.source>17</maven.compiler.source>
- <maven.compiler.target>17</maven.compiler.target>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <langchain4j.version>0.32.0</langchain4j.version>
- <jackson.version>2.16.1</jackson.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
- <!-- open Ai -->
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j-open-ai</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
- <!-- 智普 Ai -->
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j-zhipu-ai</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.tinylog</groupId>
- <artifactId>tinylog-impl</artifactId>
- <version>2.6.2</version>
- </dependency>
- <dependency>
- <groupId>org.tinylog</groupId>
- <artifactId>slf4j-tinylog</artifactId>
- <version>2.6.2</version>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
-
- </dependencies>
- </project>

案例一:普通聊天
普通聊天的话,我们只需要创建ChatLanguageModel(如有不懂,可以看上面的前置知识中的解释)对象就可以,
1. 使用openAi
此时我们需要登录 openai的官网 https://openai.com/,注册账号,点击API login进行登录,然后在里面找到apikey,需要我们用手机号码注册一个apikey,但openai封掉了亚洲很多节点,所以亚洲的手机号可能都注册不了apikey,需要用其他国家地区的, 但LangChain4j有提供了openAi的demo的apikey,我们可以用demo这个apikey就可以去调openAi大模型。但这个key限制也很多,比如文生图等等就用不了。
- ChatLanguageModel model = OpenAiChatModel.builder()
- .apiKey("demo")
- .build();
- String answer = model.generate("你好,你是谁?");
- System.out.println(answer);
2. 使用智普Ai
因为openAi是国外的,有很多限制,所以下面的案例都会用智普Ai来做,智普Ai是由清华大学计算机系知识工程实验室的技术成果转化而来。官网:智谱AI开放平台 ,注册登录,并获取apikey,大家可以充一块钱去玩玩,一块钱可以玩很久。
- ChatLanguageModel chatModel = ZhipuAiChatModel.builder()
- .apiKey("智普apikey")
- .build();
- String answer = chatModel.generate("你好,你是谁?");
- System.out.println(answer);
案例二:打字机流式响应
在前面的例子中,当我们通过ChatLanguageModel的generate()方法向大模型提问时,ChatLanguageModel一次性给了整段响应结果,而不是一个字一个字打字机式的回答,不过我们可以使用OpenAiStreamingChatModel来实现打字机效果,代码如下:
- StreamingChatLanguageModel model = ZhipuAiStreamingChatModel.builder()
- .apiKey("智普apikey")
- .build();
-
- model.generate("你好,你是谁?", new StreamingResponseHandler<AiMessage>() {
- @Override
- public void onNext(String token) {
- System.out.println(token);
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- }
- @Override
- public void onError(Throwable error) {
- System.out.println(error);
- }
- });

案例三: 检测是否存在敏感内容
ModerationModel能够校验输入中是否存在敏感内容。在智普Ai中没找到提供这个敏感内容检测的api,所有下面案例用openai写。
- ModerationModel moderationModel = OpenAiModerationModel.withApiKey("demo");
- Response<Moderation> response = moderationModel.moderate("我要杀了你");
- System.out.println(response.content().flaggedText());
案例四:文生图
ImageModel可以根据提示词来生成图片,一般我们会把生成图片的提示词输入给chatGpt,让它帮我们优化一下这个提示词,然后拿着优化的提示词用ModerationModel敏感字检查,检查通过后,拿着这个优化的提示词,输入给ImageModel 模型
- ImageModel imageModel = ZhipuAiImageModel.builder()
- .apiKey("智普apikey")
- .build();
- Response<Image> response = imageModel.generate("小猫");
- System.out.println(response.content().url());
案例五:获取当前时间
对于大模型而言,数据都是基于过往历史数据进行训练的,如果你问他"今天是几号?",可能他会懵逼,回答补上来.此时就要用到LangChain4j的Tools工具,而在Spring Ai中不叫Tools,而是Function call.
执行流程: 先请求智普Ai大模型 --->得到执行工具请求-->执行本地工具->再次通过请求问题,执行工具请求和执行工具结果,去调用智普Ai大模型,得到最终的接口. 执行了本地工具后,不是得到结果了吗?为什么还需要调大模型, 是因为执行工具后的结果只是几月几号,而不像人回复那样,所以重新调了一次.
- ChatLanguageModel chatModel = ZhipuAiChatModel.builder()
- .apiKey("智普apikey")
- .build();
-
- ToolSpecification currentTime = ToolSpecification.builder()
- .name("currentTime")
- .description("currentTime")
- .build();
- // given
- UserMessage userMessage = userMessage("今天是几号?");
- List<ToolSpecification> toolSpecifications = singletonList(currentTime);
- // when
- //执行工具响应(请求),大模型回调工具
- Response<AiMessage> response = chatModel.generate(singletonList(userMessage), toolSpecifications);
- // then
- AiMessage aiMessage = response.content();
-
- ToolExecutionRequest toolExecutionRequest = aiMessage.toolExecutionRequests().get(0);
-
- // given
- //执行工具结果
- ToolExecutionResultMessage toolExecutionResultMessage = from(toolExecutionRequest, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
- // 请求问题(userMessage) | 执行工具响应(aiMessage) | 执行工具结果(toolExecutionResultMessage)
- List<ChatMessage> messages = asList(userMessage, aiMessage, toolExecutionResultMessage);
-
- // when
- //最终结果
- Response<AiMessage> secondResponse = chatModel.generate(messages);
- System.out.println(secondResponse.content().text());

本来是想对接智普Ai的,但好像没看到智普Ai跟springboot整合的maven包, 但百度的qianfan就有. 下面用openai整个springboot.
maven依赖
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.gorgor</groupId>
- <artifactId>ai-demo</artifactId>
- <version>1.0-SNAPSHOT</version>
-
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>3.2.1</version>
- </parent>
-
- <properties>
- <maven.compiler.source>17</maven.compiler.source>
- <maven.compiler.target>17</maven.compiler.target>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <langchain4j.version>0.32.0</langchain4j.version>
- <jackson.version>2.16.1</jackson.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
-
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
- <!-- open Ai -->
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j-open-ai</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
- <!-- 智普 Ai -->
- <dependency>
- <groupId>dev.langchain4j</groupId>
- <artifactId>langchain4j-zhipu-ai</artifactId>
- <version>${langchain4j.version}</version>
- </dependency>
-
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
-
- </dependencies>
- </project>

application.yml 配置文件
- langchain4j:
- open-ai:
- chat-model:
- api-key: demo
代码:
- @RestController
- public class Demo {
-
- @Autowired
- private ChatLanguageModel chatLanguageModel;
-
- @GetMapping("testSpringboot")
- public String testSpringboot(String name){
- return chatLanguageModel.generate(name);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。