使用Spring AI接入OpenAI,Java開(kāi)發(fā)者快速上手大模型
在本教程中,將學(xué)習(xí)Spring AI的基本概念,以及如何在項(xiàng)目中實(shí)現(xiàn)它。本文將在Spring Boot應(yīng)用程序中創(chuàng)建一個(gè)AI助手,幫助學(xué)生練習(xí)外語(yǔ)。
一、演示項(xiàng)目
1.1 構(gòu)想 ??
想象一下,你是一名外語(yǔ)學(xué)生,想要練習(xí)新詞匯和語(yǔ)法。如果你是自學(xué),可以考慮一個(gè)想要描述的情境。例如,我今天早上吃了什么早餐,我昨天做了什么,等等。
然而,反復(fù)練習(xí)相同的情境可能會(huì)感到無(wú)聊。單獨(dú)思考新的練習(xí)對(duì)話情境是具有挑戰(zhàn)性的。如果有人開(kāi)始一個(gè)故事供你繼續(xù),這將很有幫助。
假設(shè)你剛剛完成了一節(jié)關(guān)于衣服的課程,想用一個(gè)有趣的情境來(lái)練習(xí)新的詞匯。這就是AI助手的作用所在。它具有豐富的想象力,可以為你編造各種故事供你繼續(xù)講下去。?
1.2 技術(shù)背景 ??
1.2.1 什么是Spring AI?
Spring AI簡(jiǎn)化了集成AI功能的應(yīng)用程序開(kāi)發(fā)。它為Spring應(yīng)用程序中的AI模型和服務(wù)提供了一系列方便的抽象。
1.2.3 SpringAI的應(yīng)用場(chǎng)景
Spring AI可以幫助開(kāi)發(fā)聊天機(jī)器人,用于自然語(yǔ)言交互、內(nèi)容生成和總結(jié)、數(shù)據(jù)分析及可視化、圖像識(shí)別和自然語(yǔ)言處理。
它擅長(zhǎng)為你個(gè)性化推薦事物,預(yù)測(cè)機(jī)器可能發(fā)生故障的時(shí)間以避免問(wèn)題,并在提高安全性的同時(shí)迅速識(shí)別欺詐行為。
1.3 項(xiàng)目設(shè)置 ??
- 在這個(gè)演示中將使用Maven,需要以下依賴項(xiàng)。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.experimental.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.7.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
請(qǐng)注意,spring-ai依賴項(xiàng)可以通過(guò)Milestones和Snapshots倉(cāng)庫(kù)獲取,將以下內(nèi)容添加到pom.xml的 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>
- 本項(xiàng)目需要一個(gè)OpenAI API密鑰。如果你尚未擁有,請(qǐng)按照說(shuō)明進(jìn)行操作。
【OpenAI API密鑰】:https://platform.openai.com/api-keys
- 生成密鑰后,將其添加到項(xiàng)目中的application.yml中。
spring:
ai:
openai.api-key: YOUR_KEY
這就是開(kāi)始所需的一切,接下來(lái)繼續(xù)編碼部分。
- 創(chuàng)建一個(gè)RestController。
@RestController
@RequiredArgsConstructor
public class PromptController {
private final PromptService promptService;
@PostMapping("/starter")
public ResponseEntity<String> generateSentenceStarter(@RequestBody Map<String, String> params) {
String language = params.get("language");
String topic = params.get("topic");
return ResponseEntity.ok(promptService.generateSentences(language, topic));
}
}
generateSentenceStarter方法通過(guò)/starter端點(diǎn)接收傳入的POST請(qǐng)求。學(xué)生將提供他們想要練習(xí)的主題和所學(xué)語(yǔ)言。
- 以下是PromptService的代碼。
@Service
@RequiredArgsConstructor
public class PromptService {
private final AiClient aiClient;
public String generateSentences(String language, String topic) {
String userText = """
Start a sentence in {language} about this topic {topic} and ask the student to think about continuing the story to practice grammar and new words.
If the sentence is in Japanese,
always write back in Hiragana and provide the Romaji equivalent in brackets.
Also, translate it into English.
""";
PromptTemplate userPromptTemplate = new PromptTemplate(userText);
Message userMessage = userPromptTemplate.createMessage(Map.of("language", language, "topic", topic));
String systemText = """
You are a helpful AI assistant that helps students in practicing foreign languages. Respond in the style of an encouraging teacher.
""";
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
Message systemMessage = systemPromptTemplate.createMessage();
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
return aiClient.generate(prompt).getGeneration().getText();
}
}
1.4 基本概念
AiClient是一個(gè)抽象接口,用于啟用生成性AI API的使用。目前,它有兩種實(shí)現(xiàn)方式:OpenAI和Azure OpenAI。
在Spring AI中,Prompt告訴AI要生成什么輸出。
PromptTemplate使用模型對(duì)象來(lái)填充模板中的占位符。我們將渲染的字符串作為提示提供給AI模型。
Roles指的是提示中的特定部分,它們?cè)谥谱髯罱K回復(fù)時(shí)發(fā)揮著不同的功能。這些角色有助于構(gòu)建提供給人工智能模型的信息結(jié)構(gòu),使輸出結(jié)果更有針對(duì)性和意義。
AI提示中的角色介紹如下。
- 系統(tǒng)角色:通過(guò)設(shè)置解釋和響應(yīng)風(fēng)格規(guī)則來(lái)引導(dǎo)AI的行為。
- 用戶角色:代表用戶的輸入,形成AI響應(yīng)的基礎(chǔ)。
- 助手角色:AI的響應(yīng)保持對(duì)話的流暢性和上下文。
- 功能角色:專注于特定任務(wù),例如計(jì)算或數(shù)據(jù)提取,超出對(duì)話范圍在需要時(shí)提供實(shí)際幫助。
Message接口的不同實(shí)現(xiàn)方式與AI模型可以處理的消息類別相一致。消息類別根據(jù)模型中的對(duì)話角色進(jìn)行區(qū)分。這一區(qū)分通過(guò)MessageType實(shí)現(xiàn)。
以上是理論部分。接下來(lái)測(cè)試一下應(yīng)用程序。
二、測(cè)試應(yīng)用程序??
啟動(dòng)應(yīng)用程序,并使用curl發(fā)送帶有類似參數(shù)的POST請(qǐng)求。
curl -X POST -H "Content-Type: application/json" -d '{"language": "japanese", "topic": "clothes"}' http://localhost:8080/starter
以下是生成的響應(yīng)。
あなたは明日友達(dá)とショッピングに行く予定です。何を著て行く予定ですか?
(Anata wa ashita tomodachi to shoppingu ni iku yotei desu. Nani o kite iku yotei desu ka?)
Translation: You are planning to go shopping with your friend tomorrow. What are you planning to wear?
這個(gè)回應(yīng)看起來(lái)是正確的,這是一個(gè)很好的句子開(kāi)頭。
接下來(lái)再嘗試另一個(gè)角色。這次,學(xué)生希望對(duì)他們的文本提供反饋。
在PromptService中添加以下這種方法。
public String provideFeedback(String userText) {
Message userMessage = new UserMessage("Is this sentence correct: " + userText);
String instructions = """
You are a helpful AI assistant that helps students in practicing foreign languages.
You should provide feedback to the students to correct the grammar and make the sentence in the foreign language sound native.
Check and correct the user text {text}. Tell the student if the sentence is correct. If the sentence is in Japanese,
always write back in Hiragana and provide the Romaji equivalent in brackets.
""";
AssistantPromptTemplate assistantPromptTemplate = new AssistantPromptTemplate(instructions);
Message assistantPromptTemplateMessage = assistantPromptTemplate.createMessage(Map.of("text", userText));
Prompt prompt = new Prompt(List.of(userMessage, assistantPromptTemplateMessage));
return aiClient.generate(prompt).getGeneration().getText();
}
如你所見(jiàn),它使用了助手角色。
將新端點(diǎn)添加到RestController中。
@PostMapping("/feedback")
public ResponseEntity<String> provideFeedback(@RequestBody Map<String, String> params) {
String text = params.get("text");
return ResponseEntity.ok(promptService.provideFeedback(text));
}
應(yīng)用程序?qū)⒈O(jiān)聽(tīng)/feedback端點(diǎn),并將學(xué)生的文本發(fā)送給AI助手。它將返回更正后的答案。
接下來(lái)嘗試一下。
curl -X POST -H "Content-Type: application/json" -d '{"text": "Kirei dzubon o kaimashita. Murasakiiro no sukaato mo kaimashita. Kono sukaato wa kirei da ga takai desu."}' http://localhost:8080/feedback
以下是AI的回復(fù)。
The sentence you provided is mostly correct. Here is the corrected version:
きれいなズボンを買(mǎi)いました。紫色のスカートも買(mǎi)いました。このスカートはきれいだが高いです。
(Kirei na zubon o kaimashita. Murasakiiro no sukāto mo kaimashita. Kono sukāto wa kirei da ga takai desu.)
Translation: I bought a nice pair of pants. I also bought a purple skirt. This skirt is beautiful, but expensive.
Well done! Your sentence is grammatically correct and the vocabulary usage is appropriate. Keep up the good work!
它理解了我想要表達(dá)的意思,還糾正了我的錯(cuò)誤。這令人印象深刻!
但當(dāng)然,我們應(yīng)該謹(jǐn)慎對(duì)待反饋,因?yàn)锳I可能會(huì)出錯(cuò)。始終仔細(xì)檢查答案是個(gè)好主意。
三、結(jié)論
在本教程中,你學(xué)會(huì)了如何開(kāi)始使用Spring AI,還熟悉了特定術(shù)語(yǔ),如Prompt、Role、Message和PromptTemplate。
現(xiàn)在,你可以根據(jù)自己的需求使用Spring AI創(chuàng)建自己的應(yīng)用程序。本文示例項(xiàng)目的完整代碼可以在以下GitHub倉(cāng)庫(kù)中找到。
四、參考資料
- 【Spring AI API文檔】:https://docs.spring.io/spring-ai/reference/api/
- 【GitHub倉(cāng)庫(kù)】:https://github.com/kirshiyin89/spring-ai-demo/tree/main