當前位置: 妍妍網 > 碼農

Spring AI上架,打造專屬業務大模型,AI開發再也不是難事!

2024-03-01碼農

Spring AI 來了

Spring AI 是 AI 工程師的一個套用框架,它提供了一個友好的 API 和開發 AI 套用的抽象,旨在簡化 AI 套用的開發工序。

提供對常見模型的接入能力,目前已經上架 https://start.spring.io/,提供大家測試存取。(請註意雖然已經上架 start.spring.io,但目前還是在 Spring 私服,未釋出至 Maven 中央倉庫)

以 ChatGPT 模型為例

1. 添加依賴

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<!-- 配置 Spring 倉庫 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

2. 配置 OpenAI 相關參數

spring:
ai:
openai:
base-url: # 支持 openai-sb、openai-hk 等中轉站點,如用官方則不填
api-key: sk-xxxx

API 使用

1. 聊天 API

@Autowired
private OpenAiChatClient chatClient;
@Test
voidtestChatClient(){
String message = """
樹上有 9 只鳥,獵人開槍打死一只,樹上還剩下多少只鳥?
"
"";
System.out.println(chatClient.call(message));
}

2. 生成影像

@Autowired
private OpenAiImageClient openaiImageClient;
@Test
voidtestImageClient(){
ImageResponse response = openaiImageClient
.call(new ImagePrompt("A light cream colored mini golden doodle", OpenAiImageOptions.builder()
.withQuality("hd").withN(4).withHeight(1024).withWidth(1024).build())
);
}

3. Prompts 提示詞 API

@Test
voidtestPrompts(){
String systemText = """
You are a helpful AI assistant that helps people find information.
Your name is {name}
You should reply to the user's request with your name.
"
"";
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
String userText = """
Tell me about three famous pirates from the Golden Age of Piracy and why they did.
Write at least a sentence for each pirate.
"
"";
Message userMessage = new UserMessage(userText);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name""lengleng"));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
List<Generation> response = chatClient.call(prompt).getResults();
for (Generation generation : response){
System.out.println(generation.getOutput().getContent());
}
}



進階:開發業務大模型

目標:在自然語言交流中,可透過呼叫外部工具來回答問題; 將自然語言轉換為 API 呼叫參數或查詢資料庫的條件;提取文本中的結構化數據

1. 建立 Function Calling

public classMockMathScoreServiceimplementsFunction<MockMathScoreService.RequestMockMathScoreService.Response{
/**
* 請求此模型必須入參的數據維度有哪些 (姓名)
* <p>
* input: 張三同學的數學成績怎麽樣?
*/

@JsonInclude(Include.NON_NULL)
@Json classDescription("數學行業")
public record Request(@JsonProperty(required = true,
value = "username")
 @JsonPropertyDescription("學生姓名") String username) 
{
}

/**
* 返回大模型的數據維度有哪些 (姓名,成績)
*/

public record Response(String username, double score){
}
/**
* 實際的資料來源提供邏輯,根據使用者輸入 username 查詢本地資料庫,返回給大模型
*
@param request the function argument username
@return Response
*/

@Override
public Response apply(Request request){
if (request.username.contains("張三")) {
returnnew Response("張三"100);
elseif (request.username.contains("李四")) {
returnnew Response("李四"99.5);
}
returnnew Response("null"0);
}
}

2. 呼叫

@Test
void testCallFunc(){
String promptText= "張三同學的數學成績怎麽樣?";
UserMessage userMessage = new UserMessage(promptText);
var promptOptions = OpenAiChatOptions.builder()
.withFunctionCallbacks(List.of(new FunctionCallbackWrapper<>(
"MathScoreService",
"教育行業AI機器人",
new MockMathScoreService())))
.build();
ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions));
System.out.println(response.getResult().getOutput().getContent());
}