使用Spring AI接入OpenAI,Java開發者快速上手大模型
在本教程中,將學習Spring AI的基本概念,以及如何在項目中實現它。本文將在Spring Boot應用程序中創建一個AI助手,幫助學生練習外語。
一、演示項目
1.1 構想 ??
想象一下,你是一名外語學生,想要練習新詞匯和語法。如果你是自學,可以考慮一個想要描述的情境。例如,我今天早上吃了什么早餐,我昨天做了什么,等等。
然而,反復練習相同的情境可能會感到無聊。單獨思考新的練習對話情境是具有挑戰性的。如果有人開始一個故事供你繼續,這將很有幫助。
假設你剛剛完成了一節關于衣服的課程,想用一個有趣的情境來練習新的詞匯。這就是AI助手的作用所在。它具有豐富的想象力,可以為你編造各種故事供你繼續講下去。?
1.2 技術背景 ??
1.2.1 什么是Spring AI?
Spring AI簡化了集成AI功能的應用程序開發。它為Spring應用程序中的AI模型和服務提供了一系列方便的抽象。
1.2.3 SpringAI的應用場景
Spring AI可以幫助開發聊天機器人,用于自然語言交互、內容生成和總結、數據分析及可視化、圖像識別和自然語言處理。
它擅長為你個性化推薦事物,預測機器可能發生故障的時間以避免問題,并在提高安全性的同時迅速識別欺詐行為。
1.3 項目設置 ??
- 在這個演示中將使用Maven,需要以下依賴項。
<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>
請注意,spring-ai依賴項可以通過Milestones和Snapshots倉庫獲取,將以下內容添加到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>
- 本項目需要一個OpenAI API密鑰。如果你尚未擁有,請按照說明進行操作。
【OpenAI API密鑰】:https://platform.openai.com/api-keys
- 生成密鑰后,將其添加到項目中的application.yml中。
spring:
ai:
openai.api-key: YOUR_KEY
這就是開始所需的一切,接下來繼續編碼部分。
- 創建一個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方法通過/starter端點接收傳入的POST請求。學生將提供他們想要練習的主題和所學語言。
- 以下是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是一個抽象接口,用于啟用生成性AI API的使用。目前,它有兩種實現方式:OpenAI和Azure OpenAI。
在Spring AI中,Prompt告訴AI要生成什么輸出。
PromptTemplate使用模型對象來填充模板中的占位符。我們將渲染的字符串作為提示提供給AI模型。
Roles指的是提示中的特定部分,它們在制作最終回復時發揮著不同的功能。這些角色有助于構建提供給人工智能模型的信息結構,使輸出結果更有針對性和意義。
AI提示中的角色介紹如下。
- 系統角色:通過設置解釋和響應風格規則來引導AI的行為。
- 用戶角色:代表用戶的輸入,形成AI響應的基礎。
- 助手角色:AI的響應保持對話的流暢性和上下文。
- 功能角色:專注于特定任務,例如計算或數據提取,超出對話范圍在需要時提供實際幫助。
Message接口的不同實現方式與AI模型可以處理的消息類別相一致。消息類別根據模型中的對話角色進行區分。這一區分通過MessageType實現。
以上是理論部分。接下來測試一下應用程序。
二、測試應用程序??
啟動應用程序,并使用curl發送帶有類似參數的POST請求。
curl -X POST -H "Content-Type: application/json" -d '{"language": "japanese", "topic": "clothes"}' http://localhost:8080/starter
以下是生成的響應。
あなたは明日友達とショッピングに行く予定です。何を著て行く予定ですか?
(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?
這個回應看起來是正確的,這是一個很好的句子開頭。
接下來再嘗試另一個角色。這次,學生希望對他們的文本提供反饋。
在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();
}
如你所見,它使用了助手角色。
將新端點添加到RestController中。
@PostMapping("/feedback")
public ResponseEntity<String> provideFeedback(@RequestBody Map<String, String> params) {
String text = params.get("text");
return ResponseEntity.ok(promptService.provideFeedback(text));
}
應用程序將監聽/feedback端點,并將學生的文本發送給AI助手。它將返回更正后的答案。
接下來嘗試一下。
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的回復。
The sentence you provided is mostly correct. Here is the corrected version:
きれいなズボンを買いました。紫色のスカートも買いました。このスカートはきれいだが高いです。
(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!
它理解了我想要表達的意思,還糾正了我的錯誤。這令人印象深刻!
但當然,我們應該謹慎對待反饋,因為AI可能會出錯。始終仔細檢查答案是個好主意。
三、結論
在本教程中,你學會了如何開始使用Spring AI,還熟悉了特定術語,如Prompt、Role、Message和PromptTemplate。
現在,你可以根據自己的需求使用Spring AI創建自己的應用程序。本文示例項目的完整代碼可以在以下GitHub倉庫中找到。
四、參考資料
- 【Spring AI API文檔】:https://docs.spring.io/spring-ai/reference/api/
- 【GitHub倉庫】:https://github.com/kirshiyin89/spring-ai-demo/tree/main