用 Spring AI 調(diào)用 OpenAI 對話接口

原文地址:https://alphahinex.github.io/2024/12/01/spring-ai-chat-model/


description: "本文以調(diào)用智譜 AI 開放平臺的 OpenAI 兼容對話接口為例霜旧,演示了使用 Spring AI 對接單個或多個對話模型的方法错忱。"
date: 2024.12.01 10:34
categories:
- AI
- Spring
tags: [AI, Spring, Spring AI]
keywords: Spring AI, OpenAI, Chat Completions, ChatClient


環(huán)境準(zhǔn)備

JDK

使用 Spring AI 需要 JDK 17 及以上版本。

$ java -version
openjdk version "17.0.2" 2022-01-18
OpenJDK Runtime Environment (build 17.0.2+8-86)
OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing)

start.spring.io

https://start.spring.io/ 下載一個包含 Spring Web 依賴的 Maven 工程:

解壓颁糟,并使用其中自帶的 Maven Wrapper 進行構(gòu)建:

$ unzip demo.zip
$ cd demo
$ ./mvnw clean package
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.569 s
[INFO] Finished at: 2024-11-30T13:58:27+08:00
[INFO] ------------------------------------------------------------------------

智譜 AI 開放平臺

登錄到智譜AI開放平臺 API Keys 頁面 獲取最新版生成的用戶 API Key航背,用于調(diào)用其提供的兼容 OpenAI 對話接口的免費模型 GLM-4-Flash

$ curl --location 'https://open.bigmodel.cn/api/paas/v4/chat/completions' \
--header 'Authorization: Bearer <你的apikey>' \
--header 'Content-Type: application/json' \
--data '{
    "model": "glm-4-flash",
    "messages": [
        {
            "role": "user",
            "content": "你好"
        }
    ]
}'
{"choices":[{"finish_reason":"stop","index":0,"message":{"content":"你好??!很高興見到你棱貌,有什么可以幫助你的嗎玖媚?","role":"assistant"}}],"created":1732946586,"id":"202411301403051925a900b08f4e23","model":"glm-4-flash","request_id":"202411301403051925a900b08f4e23","usage":{"completion_tokens":16,"prompt_tokens":6,"total_tokens":22}}

添加依賴

pom.xml 中添加 Spring AI 的 相關(guān)配置及依賴

repositories

<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>
</repositories>

dependencyManagement

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-bom</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

dependency

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

使用 ChatClient 與 OpenAI 兼容模型接口對話

僅對接一個大模型時

可直接通過配置項注冊并使用 ChatClient。

application.properties 中添加 Spring AI OpenAI 的相關(guān)配置:

spring.ai.openai.base-url=https://open.bigmodel.cn/api/paas
spring.ai.openai.chat.completions-path=/v4/chat/completions
spring.ai.openai.api-key=<你的apikey>
spring.ai.openai.chat.options.model=glm-4-flash

創(chuàng)建一個配置類:

@Configuration
public class Config {

    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.build();
    }

}

在工程中自帶的 DemoApplicationTests 單元測試中婚脱,驗證對話效果:

@Autowired
ChatClient chatClient;

@Test
void autoConfig() {
    String userMsg = "who r u";
    System.out.println(chatClient.prompt().user(userMsg).call().content());
}

執(zhí)行結(jié)果如下:

I am an AI assistant named ChatGLM, which is developed based on the language model jointly trained by Tsinghua University KEG Lab and Zhipu AI Company in 2024. My job is to provide appropriate answers and support to users' questions and requests.

需要對接多個大模型時

可定義一個工場類創(chuàng)建多個 ChatClient 實例:

public class ChatClientFactory {

    public static ChatClient createOpenAiChatClient(String baseUrl, String apiKey, String model, String completionsPath) {
        if (StringUtils.isBlank(completionsPath)) {
            completionsPath = "/v1/chat/completions";
        }
        OpenAiApi openAiApi = new OpenAiApi(baseUrl, apiKey, completionsPath,
            "/v1/embeddings", RestClient.builder(), WebClient.builder(), RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
        OpenAiChatModel openAiChatModel = new OpenAiChatModel(openAiApi, OpenAiChatOptions.builder().withModel(model).build());
        return ChatClient.create(openAiChatModel);
    }

}
@Test
void multiClients() {
    ChatClient llm1 = ChatClientFactory.createOpenAiChatClient("https://open.bigmodel.cn/api/paas", "xxxx", "glm-4-flash", "/v4/chat/completions");
    ChatClient llm2 = ChatClientFactory.createOpenAiChatClient("https://open.bigmodel.cn/api/paas", "xxxx", "glm-4-flash", "/v4/chat/completions");

    String userMsg = "你是誰今魔?";
    System.out.println(llm1.prompt().user(userMsg).call().content());
    System.out.println(llm2.prompt().user(userMsg).call().content());
}

示例代碼

demo.zip

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市障贸,隨后出現(xiàn)的幾起案子错森,更是在濱河造成了極大的恐慌,老刑警劉巖篮洁,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件涩维,死亡現(xiàn)場離奇詭異,居然都是意外死亡袁波,警方通過查閱死者的電腦和手機瓦阐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來篷牌,“玉大人睡蟋,你說我怎么就攤上這事〖霞眨” “怎么了戳杀?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長夭苗。 經(jīng)常有香客問我信卡,道長,這世上最難降的妖魔是什么听诸? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任坐求,我火速辦了婚禮,結(jié)果婚禮上晌梨,老公的妹妹穿的比我還像新娘桥嗤。我一直安慰自己须妻,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布泛领。 她就那樣靜靜地躺著荒吏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪渊鞋。 梳的紋絲不亂的頭發(fā)上绰更,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機與錄音锡宋,去河邊找鬼儡湾。 笑死,一個胖子當(dāng)著我的面吹牛执俩,可吹牛的內(nèi)容都是我干的徐钠。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼役首,長吁一口氣:“原來是場噩夢啊……” “哼尝丐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起衡奥,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤爹袁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后矮固,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體失息,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年档址,在試婚紗的時候發(fā)現(xiàn)自己被綠了根时。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡辰晕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出确虱,到底是詐尸還是另有隱情含友,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布校辩,位于F島的核電站窘问,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏宜咒。R本人自食惡果不足惜惠赫,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望故黑。 院中可真熱鬧儿咱,春花似錦庭砍、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至钳宪,卻和暖如春揭北,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背吏颖。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工搔体, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人半醉。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓疚俱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親奉呛。 傳聞我的和親對象是個殘疾皇子计螺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容