2. LangChain4J 中的 Hello World
2. LangChain4J 中的 Hello World
@
1. 接入阿里百煉大模型 —— 通義千問
接入阿里百煉平臺的通義模型:https://bailian.console.aliyun.com/?tab=home#/home

大模型調用三件套:
- 獲得對應大模型的 Api-Key

- 獲得模型名:


- 獲得 baseUrl 開發地址:

假設你要換一個模型實例:




初始總 pom.xml
<?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.atguigu.stduy</groupId>
<artifactId>langchain4j-atguiguV5</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>langchain4j-atguiguV5-Maven父工程POM配置</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<!-- Spring Boot -->
<spring-boot.version>3.5.0</spring-boot.version>
<!-- Spring AI -->
<spring-ai.version>1.0.0</spring-ai.version>
<!-- Spring AI Alibaba -->
<spring-ai-alibaba.version>1.0.0-M6.1</spring-ai-alibaba.version>
<!-- langchain4j -->
<langchain4j.version>1.0.1</langchain4j.version>
<!--langchain4j-community 引入阿里云百煉平臺依賴管理清單-->
<langchain4j-community.version>1.0.1-beta6</langchain4j-community.version>
<!-- maven plugin -->
<maven-deploy-plugin.version>3.1.1</maven-deploy-plugin.version>
<flatten-maven-plugin.version>1.3.0</flatten-maven-plugin.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring AI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring AI Alibaba -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>
<!--langchain4j的依賴清單,加載BOM后所有langchain4j版本號可以被統一管理起來
https://docs.langchain4j.dev/get-started
-->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>${langchain4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--引入阿里云百煉平臺依賴管理清單
https://docs.langchain4j.dev/integrations/language-models/dashscope
-->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-bom</artifactId>
<version>${langchain4j-community.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${java.version}</release>
<compilerArgs>
<compilerArg>-parameters</compilerArg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>${flatten-maven-plugin.version}</version>
<inherited>true</inherited>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>ossrh</flattenMode>
<pomElements>
<distributionManagement>remove</distributionManagement>
<dependencyManagement>remove</dependencyManagement>
<repositories>remove</repositories>
<scm>keep</scm>
<url>keep</url>
<organization>resolve</organization>
</pomElements>
</configuration>
</execution>
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>aliyunmaven</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>




配置我們對應進入的大模型的三件套:對應大模型的 Key,模型名,調用地址:

我們可以將上述大模型三件套寫入到 application.properties 配置文件當中如下:
我們接入阿里百煉大模型——
server.port=9001
spring.application.name=langchain4j-01helloworld
# alibaba qwen-turbo-0624 help langchain4j
# https://bailian.console.aliyun.com/#/model-market/detail/qwen-turbo-0624
#langchain4j.open-ai.chat-model.api-key=${aliQwen-api}
langchain4j.open-ai.chat-model.api-key=sk-d2902588e5eb45ssssdasfaf4xxxx
langchain4j.open-ai.chat-model.model-name=qwen-plus
langchain4j.open-ai.chat-model.base-url=https://dashscope.aliyuncs.com/compatible-mode/v1

編寫對外的 Cutroller

package com.rainbowsea.langchain4j01helloworld.controller;
import dev.langchain4j.model.chat.ChatModel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class HelloLangChain4JController {
@Resource
private ChatModel chatLanguageModel;
// http://localhost:9001/langchain4j/hello?prompt=你是誰
@GetMapping(value = "/langchain4j/hello")
public String hello(@RequestParam(value = "prompt", defaultValue = "你是誰") String prompt)
{
String result = chatLanguageModel.chat(prompt);
System.out.println("通過langchain4j調用模型返回結果:\n"+result);
return result;
}
}
運行測試:


2. 接入 DeepSeek 大模型
上述我們是將大模型的 Key 配置到了,application.properties 配置文件當中。
這種方式不太安全,官方建議我們將其配置到系統變量當中。讓程序去系統變量當中獲取。



特別注意:想讓 IDEA 可以讀取到我們系統變量當中的值,需要重啟 IDEA,如果重啟 IDEA 還是讀取不到我們系統變量當中的值,則重啟系統即可。
你在系統變量名可以隨意,盡量見名之意,不要中文,對應變量名的值,就是你對應大模型的 key 的值。
在系統環境變量當中的值,有兩種獲取方式。
- 第一種就是:我們在 application.yaml / properties 配置文件當中,使用
${}占位符。如下圖所示:

- 第二種方式:就是編寫我們的 config 配置類,讀取我們系統當中的配置大模型 key 。
這里我們使用配置類的方式,配置我們連接操作 DeepSeek 大模型的三件套配置信息(大模型的 key,name,url)。這些從 DeepSeek 開發文檔當中就可以獲取到
https://api-docs.deepseek.com/zh-cn/


package com.rainbowsea.langchain4j01helloworld.config;
//import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LLMConfig {
// DeepSeek
@Bean
public ChatModel ChatLanguageModel() {
//String apiKey = System.getenv("deepseek_api");
return OpenAiChatModel.builder()
.apiKey(System.getenv("deepseek_api"))
.modelName("deepseek-chat")
.baseUrl("https://api.deepseek.com/v1")
.build();
}
// aliQwen_api
//@Bean
//public ChatModel ChatLanguageModel() {
// //String apiKey = System.getenv("aliQwen_api");
// return OpenAiChatModel.builder()
// .apiKey(System.getenv("aliQwen_api"))
// .modelName("qwen-plus")
// .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
// .build();
//}
}

還是之前的那個 Cutroller ,不同的是我們這次接入的是 DeepSeek 大模型。


3. 同時接入 DeepSeek 和 通義千問
我們可以同時接入DeepSeek 和 通義千問 兩個大模型,進行一個切換使用。
就是將這兩個大模型的配置,都編寫好,切換著使用即可。如下:
我們將這兩個大模型的配置三件套,都寫入到我們的配置類當中。如下:

package com.rainbowsea.langchain4j01helloworld.config;
//import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LLMConfig {
// DeepSeek
//@Bean
@Bean(name = "deepseek")
public ChatModel chatModelDeepSeek() {
//String apiKey = System.getenv("deepseek_api");
return OpenAiChatModel.builder()
.apiKey(System.getenv("deepseek_api"))
.modelName("deepseek-chat")
.baseUrl("https://api.deepseek.com/v1")
.build();
}
// aliQwen_api
//@Bean
@Bean(name = "qwen")
public ChatModel chatModelQwen() {
//String apiKey = System.getenv("aliQwen_api");
return OpenAiChatModel.builder()
.apiKey(System.getenv("aliQwen_api"))
.modelName("qwen-plus")
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
}
}

package com.rainbowsea.langchain4j01helloworld.controller;
import dev.langchain4j.model.chat.ChatModel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
*/
@RestController
@Slf4j
public class MultiModelController
{
@Resource(name = "qwen")
private ChatModel chatModelQwen;
@Resource(name = "deepseek")
private ChatModel chatModelDeepSeek;
// http://localhost:9001/multimodel/qwen
@GetMapping(value = "/multimodel/qwen")
public String qwenCall(@RequestParam(value = "prompt", defaultValue = "你是誰") String prompt)
{
String result = chatModelQwen.chat(prompt);
System.out.println("通過langchain4j調用模型返回結果:\n"+result);
return result;
}
// http://localhost:9001/multimodel/deepseek
@GetMapping(value = "/multimodel/deepseek")
public String deepseekCall(@RequestParam(value = "prompt", defaultValue = "你是誰") String prompt)
{
String result = chatModelDeepSeek.chat(prompt);
System.out.println("通過langchain4j調用模型返回結果:\n"+result);
return result;
}
}
測試:


web開發中的 token 和 大模型中的 token 的區別:?
用途不同:
- Web開發中的Token通過加密字符串驗證用戶身份或授權訪問資源,例如JWT令牌用于API訪問權限控制。
- 大模型中的Token將文本拆分為最小處理單元(如詞元),用于模型計算,例如將中文句子拆分為字、詞或符號序列。
生成機制不同:
- Web Token通常由加密算法生成唯一字符串(如JWT包含用戶信息)。
- 大模型Token通過特定算法(如分詞規則)對文本進行拆分,不同模型拆分規則可能不同。

4. 最后:
“在這個最后的篇章中,我要表達我對每一位讀者的感激之情。你們的關注和回復是我創作的動力源泉,我從你們身上吸取了無盡的靈感與勇氣。我會將你們的鼓勵留在心底,繼續在其他的領域奮斗。感謝你們,我們總會在某個時刻再次相遇。”


浙公網安備 33010602011771號