当前位置: 欣欣网 > 码农

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());
}