准备
最近看到Spring官方推出了SpringAI,今天正好尝试一下。
尝试之前需要准备下面几样东西:
- OpenAI的key,国内尝鲜用户可以在淘宝上购买 几块钱就能解决。
- jdk17。
- 如果使用Idea,需要升级到相应的版本,老板本有问题,亲身踩坑。
创建SpringAI项目
1.使用spring initializr创建项目,选择Java,maven,17如下图所示
2.添加依赖,Spring web方便测试,OpenAI
3.导出到本地
4.导入Idea
创建测试类
这个我是直接拷贝的SpringAI的官方文档中的如下:
package com.example.MyTest;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class MyController {
private final ChatClient chatClient;
public MyController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/ai")
String generation(String userInput) {
return this.chatClient.prompt()
.user(userInput)
.call()
.content();
}
}
配置OpenAI
由于我是淘宝买的KEY,所以不仅需要配置key
spring.ai.openai.api-key
还需要配置base-url,我使用的是我购买商家提供的,有很详细的介绍。
spring.ai.openai.base-url
运行测试
总结
至此接入就完成啦,是不是很easy。当然这只是简单的对话,还有跟多的共能介绍请看官方文档。