
在本教程中,我们将使用Spring Boot 在一些引人入胜的场景中应用AI。
将Spring AI 视为构建AI应用的工具包。它为您提供可轻松替换的基本构建块。这种灵活性让您无需复杂重编程即可调整和定制AI程序。
除了基本构建块,Spring AI 还希望提供额外功能来处理日常场景,如“询问文档相关问题”或“与文档进行对话”。随着任务变得更复杂,Spring AI 将与Spring家族的其他项目(如Spring Integration、Spring Batch 和 Spring Data)协作。
Spring AI 是一个非常新的项目,目前尚未有稳定版本。不过,我们期待未来会发布稳定版本。
Spring AI 引入了 AiClient 接口,并为 OpenAI 和 Azure OpenAI 提供了实现。
想了解更多关于Spring Boot 中 OpenAI 的操作,请查看我的以下文章:
OpenAI in Action: ChatGPT Integration with Spring Boot
让我们开始编码吧.. 😊
pom.xml 中所需的依赖
要使用Spring AI,请添加以下仓库。请注意,这是一个实验性项目,目前仅提供 snapshot 版本。
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
使用 OpenAI 时,可以添加以下依赖:
<dependency>
<groupId>org.springframework.experimental.ai</groupId>
<artifactId>spring-ai-openai spring-boot-starter</artifactId>
<version>0.2.0-SNAPSHOT</version>
</dependency>
如果使用 Azure OpenAI 而非 OpenAI,可以添加以下依赖:
<dependency>
<groupId>org.springframework.experimental.ai</groupId>
<artifactId>spring-ai-azure-openai spring-boot-starter</artifactId>
<version>0.2.0-SNAPSHOT</version>
</dependency>
本文将使用 OpenAI。
创建 OpenAI API Key
要使Spring AI 正常工作,必须提供 API Key 以建立与 OpenAI 的连接。
在此注册并创建您自己的 OpenAI API Key。

在 application.properties
文件中添加 API Key 和 OpenAI 图像生成 URL:
spring.ai.openai.apikey=REPLACE_WITH_YOUR_API_KEY
spring.ai.openai.imageUrl=https://api.openai.com/v1/images/generations
项目结构

在 services
包下创建 SpringAIService:
publicclassSpringAIService{
AiClient aiClient;
privateString apiKey;
privateString openAIImageUrl;
publicString getJoke(String topic){
PromptTemplate promptTemplate =newPromptTemplate("""
Crafting a compilation of programming jokes formy website.Would you like me to create a joke about {topic}?
""");
promptTemplate.add("topic", topic);
returnthis.aiClient.generate(promptTemplate.create()).getGeneration().getText();
}
publicString getBestBook(String category,String year){
PromptTemplate promptTemplate =newPromptTemplate("""
I want to research some books.How about you give me a book about {category}in{year} to get started?
But pick the best you can think of. I'm a book critic, after all. Ratings are a good place to start.
And who wrote it?And who help it?Can you give me a short plot summary and also it's name?
But don't give me too much information. I want to be surprised.
And please give me these details in the following JSON format: category, year, bookName, author, review, smallSummary.
""");
Map.of("category", category,"year", year).forEach(promptTemplate::add);
AiResponse generate =this.aiClient.generate(promptTemplate.create());
return generate.getGeneration().getText();
}
publicInputStreamResource getImage(@RequestParam(name ="topic")String topic)throwsURISyntaxException{
PromptTemplate promptTemplate =newPromptTemplate("""
I am really board from online memes.Can you create me a prompt about {topic}.
Elevate the given topic.Make it classy.
Make a resolution of 256x256, but ensure that it is presented in json it need to be string.
I desire only one creation.Give me as JSON format: prompt, n, size.
""");
promptTemplate.add("topic", topic);
String imagePrompt =this.aiClient.generate(promptTemplate.create()).getGeneration().getText();
RestTemplate restTemplate =newRestTemplate();
HttpHeaders headers =newHttpHeaders();
headers.add("Authorization","Bearer "+ apiKey);
headers.add("Content-Type","application/json");
HttpEntity<String> httpEntity =newHttpEntity<>(imagePrompt,headers);
String imageUrl = restTemplate.exchange(openAIImageUrl,HttpMethod.POST, httpEntity,GeneratedImage.class)
.getBody().getData().get(0).getUrl();
byte[] imageBytes = restTemplate.getForObject(new URI(imageUrl),byte[].class);
assert imageBytes !=null;
returnnewInputStreamResource(new java.io.ByteArrayInputStream(imageBytes));
}
}
让我们逐步理解代码。
Autowired 依赖
该类使用 @Autowired
注解注入 AiClient 类的实例。 AiClient 是一个与 OpenAI 服务通信的接口。
getJoke 方法
有一个名为 getJoke
的方法,接受 topic
作为参数。 它创建一个 PromptTemplate 对象,包含用于生成编程笑话的预定义模板。 模板中的 {topic}
占位符被实际的 topic
参数替换。 AI 客户端根据此提示生成响应,并返回响应的文本。
getBestBook 方法
另一个名为 getBestBook
的方法接受 category
和 year
参数。 它使用类似模式,通过模板请求特定类别和年份的最佳书籍信息。 {category}
和 {year}
占位符被提供的参数替换。 AI 客户端生成响应,并返回响应的文本。
getImage 方法
它接受 topic
作为参数,请求与该主题相关的图像。 使用 PromptTemplate 形成图像创建请求,替换 {topic}
。 生成的提示通过 AiClient 发送到AI服务,获取图像 URL。 然后从 URL 获取图像并转换为 InputStreamResource 以供进一步处理。
在 models
包下创建 GeneratedImage 实体:
publicclassGeneratedImage{
privateList<ImageUrl> data;
publicList<ImageUrl> getData(){
return data;
}
publicvoid setData(List<ImageUrl> data){
this.data = data;
}
publicstaticclassImageUrl{
privateString url;
publicString getUrl(){
return url;
}
publicvoid setUrl(String url){
this.url = url;
}
}
}
在 controllers
包下创建 SpringAIController:
"/api/v1") (
publicclassSpringAIController{
SpringAIService aiService;
"/joke") (
publicString getJoke( topic){
return aiService.getJoke(topic);
}
"/book") (
publicString getBook((name ="category")String category,(name ="year")String year){
return aiService.getBestBook(category, year);
}
"/image", produces ="image/jpeg") (value =
publicResponseEntity<InputStreamResource> getImage( (name ="topic")String topic)throwsURISyntaxException{
returnResponseEntity.ok().body(aiService.getImage(topic));
}
}
在控制器类中,我创建了3个端点:
1./api/v1/joke:根据您提供的主题生成笑话(Spring AI 实战)。

2./api/v1/book:根据您提供的类别和年份返回书籍详情(Spring AI 实战)。

3./api/v1/image:为您生成AI根据您请求创建的图像(再次 Spring AI 实战… 😊)。

Spring AI 非常棒。如果您觉得这篇文章信息丰富且有益,请考虑通过点赞 👏 表示支持。请随意与您的同行分享这篇文章。您的支持和开发者社区内的知识共享非常宝贵。

如果对你有帮助麻烦点赞、关注、转发🚀
(文:PyTorch研习社)