SpringBoot+Spring AI Alibaba接入RAG应用实践笔记
spring-boot接入阿里百炼大模型
1.创建一个spring-boot应用,3.0以上支持springAi即可。(最新即可)
2,阿里百炼创建一个账号,获取api-key,地址:阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台
3,引入依赖
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0-M6.1</version>
</dependency>
添加如上依赖的repo
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
编写代码进行测试
@Autowired
private ChatClient chatClient;
@GetMapping("/chat")
public String chat(String input) {
return this.chatClient.prompt()
.user(input)
.call()
.content();
}
访问接口进行测试:
我问了一个弱智问题,接口正常返回了大模型的回答,虽说它是答不了这个问题的。
断点进去看可以知道默认使用的大模型是通义千问plus
如何让大模型能回答如上我问的问题?那就是建立知识库,让大模型学习这些知识。
接入阿里百炼RAG知识库
首先准备“知识”,建一个world文档,内容假设如下
未来末日市实验中学三年二班的班主任叫黄天详,大家都叫他黄老师,这位老师对学生要求比较严格。未来末日市实验中学三年一班的班主任叫李四,李四是一个非常有常识的人。未来末日市实验中学的校长叫叫李大明,乐于助力,是一个乐天派。而账务主管叫张三,张三喜欢钓鱼。
上面的文档有关于我所问问题的答案,接下来通过平台建立一个RAG知识库。方法如下图(非结构化数据)
建立知识索引
选择刚刚导入的数据即可
下一步保持默认智能切分即可。
创建RAG应用
我的应用里面直接创建即可
配置模型,把必要的配置填写一下,重点要配置知识库,选择上面创建的知识库即可。
配置完毕,在体验窗口再问一次刚刚的问题:未来末日市实验中学的校长是谁
可见模型已经按我们的文档给出回答,并且还能扩展回答。点击发布。接下来就是使用spring-boot访问我们这个应用了。
spring-boot访问RAG应用
使用官方的sdk,添加依赖
<!-- rag应用sdk -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<!-- 请将 'the-latest-version' 替换为最新版本号:https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<version>2.18.5</version>
</dependency>
编写接口
@GetMapping("/scoolChat")
public String scoolChat(String input) {
try {
String res = appCall(input);
return res;
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message:"+e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
return "请求失败";
}
private String appCall(String prompt)
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(apiKey)
.appId(scoolAppId)
.prompt(prompt)
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
return result.getOutput().getText();
}
apiKey可以在平台找到,appId可以在“我的应用”中找到。
访问接口:
可见已经生效。