赞
踩
一说到调用openAI的api或者做一些小项目,大部分例子都是python或者node实现的,后来发现spring出了对于openai的支持框架,所以尝试用一用。这里是SpringAI的地址,有兴趣的可以去官网看:Spring AI
首先声明,因为我是从0搭建的项目,所以我用的全部都是最新版,JDK22,springboot3.3.0,以下是对于spring AI的引用:
<properties> <java.version>17</java.version> <spring-ai.version>1.0.0-M1</spring-ai.version> <spring-cloud.version>2023.0.0</spring-cloud.version> </properties> <dependencies> <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> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-zhipuai-spring-boot-starter</artifactId> </dependency>
因为众所周知的原因,国内调用openAI是掉不通的,所以就出现了众多的代理服务,所以代码中也不能去调用openAI的官方域名,要改成自己的配置,此处打广告:代理地址,可以通过我的推荐链接注册:smnet1,会赠送¥1000 token
如下:
spring: ai: openai: # 全局配置 api-key: sk-this-is-key # 申请的api-key base-url: https://api.smnet1.asia/ #代理地址,可以通过我的推荐链接注册:https://api.smnet1.asia/register?aff=xg61,会赠送¥1000 token # 嵌入API配置 embedding: options: model: kimi #我使用的代理支持多种模型,所以这里填写自己想用的模型就可以 # 聊天API配置 chat: #指定某一个API配置(覆盖全局配置) api-key: sk-this-is-key # 申请的api-key base-url: https://api.smnet1.asia/ #openAi访问地址(不写默认) options: model: kimi #我使用的代理支持多种模型,所以这里填写自己想用的模型就可以 zhipuai: api-key: this-is-zhipu-key # 申请的api-key base-url: https://open.bigmodel.cn/api/paas/ #填写zhipu的访问地址 chat: enabled: true
配置搞好了,就到了实际使用的部分,这个真的开箱即用,如果没啥个性化需求的话,不需要另外的配置了,直接开调:
@RestController @RequestMapping("/ai") public class ChatController { @Autowired private OpenAiChatModel chatClient; @GetMapping(value = "/easyChat", params = "message", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<String>> easyChat(@RequestParam String message) { System.out.println(1111); //Prompt prompt = new Prompt(message); 如果这里不想另外指定,直接用这个就可以 Prompt prompt = new Prompt(message, OpenAiChatOptions.builder() .withModel("kimi") //大模型用哪个 .withTemperature(0.9f) //温度高,更发散,准确性降低,温度低,更保守,准确性高 .build()); System.out.println(chatClient.call(prompt)); //如果想直接拿到结果,用这个call方法就可以 //下面是流类型的返回,一个字一个字的返回,如果你像我一样用kimi,kimi不支持这样,需要用 return chatClient.stream(prompt) .filter(Objects::nonNull) .filter(chatResponse -> chatResponse.getResults() != null) .flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults())) .filter(Objects::nonNull) .map(Generation::getOutput) .filter(Objects::nonNull) .filter(content -> Objects.nonNull(content.getContent())) .map(AssistantMessage::getContent) .filter(Objects::nonNull) .map(content -> ServerSentEvent.builder(content).build()) .doOnNext(System.out::println) .concatWith(Flux.just(ServerSentEvent.builder("complete").build())); // Optionally, you can add a completion signal } }
现在想使用大模型真的门槛超低了,不管是直接使用还是api调用,怎么用这个问题解决起来还是很快的,不过我的问题大部分还是不知道用它做什么,我自己的能力不足以支撑我很好的使用它。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。