前言
Spring最近刚刚推出了SpringAI,封装了AI大模型接口的使用。本文将参考Spring官网案例,一步步教你如何调用OpenAI的接口,让ChatGPT接口返回一个笑话。
前提条件
- 请下载并安装好JDK17或更新的版本,本文使用的是JDK21。JDK下载地址。
- 准备好梯子。没有梯子,调用OpenAI接口会报500错误。(也别问我梯子是啥,懂得都懂🤫)。
- 准备好OpenAI接口的API Key,淘宝上有卖的(应该不差过10元)。
- 如果你的Maven用的是阿里云仓库,建议先注释掉。AI依赖包太新了,目前阿里云还没有。
创建项目
- 使用idea创建一个新的Spring项目。File > New > Project > Spring Initializer
- Server URL一定要用Spring的:https://start.spring.io,其他的地址目前还没更新。
- JDK版本一定要大于等于17,低版本不支持Springboot3
- 依赖包选择Spring Web和OpenAI(在最下方),如下图
- 创建成功之后,等待项目自动下载依赖包。这里就看大家网速了。
配置开发
- 项目创建好之后,加入OpenAI接口配置。1. application.properties2.
spring.application.name=JavaAI# openai api-key 没有的建议自己去买一个,我这个应该很快就会失效spring.ai.openai.api-key=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# ChatGPT模型版本spring.ai.openai.chat.options.model=gpt-3.5-turbospring.ai.openai.chat.options.temperature=0.7
3. pom.xml,这里面的内容是自动生成的,一般不用改。4.<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version><relativePath/><!-- lookup parent from repository --></parent><groupId>com.gem</groupId><artifactId>JavaAI</artifactId><version>0.0.1-SNAPSHOT</version><name>JavaAI</name><description>JavaAI</description><properties><java.version>21</java.version><spring-ai.version>0.8.1</spring-ai.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.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>${spring-ai.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>
- 在你的启动类中加入代理设置,不然掉接口会报500。1. JavaAiApplication.java2.
importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassJavaAiApplication{publicstaticvoidmain(String[] args){// 设置代理,这里需要根据自己找的代理软件来调整配置System.setProperty("proxySet","true");System.setProperty("proxyType","4");// 代理地址,根据代理软件System.setProperty("proxyHost","127.0.0.1");// 代理端口(Http)System.setProperty("proxyPort","21882");SpringApplication.run(JavaAiApplication.class, args);}}
- 创建controller,使用调用OpenAI的接口。1. ChatController2.
importorg.springframework.ai.chat.ChatResponse;importorg.springframework.ai.chat.messages.UserMessage;importorg.springframework.ai.chat.prompt.Prompt;importorg.springframework.ai.openai.OpenAiChatClient;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importreactor.core.publisher.Flux;importjava.util.Map;/** * ChatGPT接口调用<br> * * @author Gem * @version 1.0 * @date 2024/4/18 */@RestControllerpublicclassChatController{privatefinalOpenAiChatClient chatClient;@AutowiredpublicChatController(OpenAiChatClient chatClient){this.chatClient = chatClient;}@GetMapping("/ai/generate")publicMapgenerate(@RequestParam(value ="message", defaultValue ="Tell me a joke")String message){returnMap.of("generation", chatClient.call(message));}@GetMapping("/ai/generateStream")publicFlux<ChatResponse>generateStream(@RequestParam(value ="message", defaultValue ="Tell me a joke")String message){Prompt prompt =newPrompt(newUserMessage(message));return chatClient.stream(prompt);}}
3. 到此,开发配置结束。
启动调试
- 启动项目,启动前请先开启梯子,默认端口号:8080。1. 启动成功日志2.
Connectedtothe target VM, address: '127.0.0.1:55997', transport:'socket'. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \(()\___ |'_ | '_|| '_ \/ _` | \ \ \ \ \\/ ___)||_)|||||||(_||)))) ' |____|.__|_||_|_||_\__,|////=========|_|==============|___/=/_/_/_/::SpringBoot::(v3.2.4)2024-04-18T17:42:27.495+08:00INFO22192---[JavaAI][ main]com.gem.javaai.JavaAiApplication:StartingJavaAiApplication using Java21.0.3withPID22192(D:\Workspace\idea\study\JavaAI\JavaAI\target\classes started by Administrator in D:\Workspace\idea\study\JavaAI\JavaAI)2024-04-18T17:42:27.497+08:00INFO22192---[JavaAI][ main]com.gem.javaai.JavaAiApplication:No active profile set, falling back to1default profile:"default"2024-04-18T17:42:28.371+08:00INFO22192---[JavaAI][ main]o.s.b.w.embedded.tomcat.TomcatWebServer:Tomcat initialized withport8080(http)2024-04-18T17:42:28.380+08:00INFO22192---[JavaAI][ main]o.apache.catalina.core.StandardService:Starting service [Tomcat]2024-04-18T17:42:28.380+08:00INFO22192---[JavaAI][ main]o.apache.catalina.core.StandardEngine:StartingServlet engine:[ApacheTomcat/10.1.19]2024-04-18T17:42:28.423+08:00INFO22192---[JavaAI][ main]o.a.c.c.C.[Tomcat].[localhost].[/]:InitializingSpring embedded WebApplicationContext2024-04-18T17:42:28.423+08:00INFO22192---[JavaAI][ main]w.s.c.ServletWebServerApplicationContext:RootWebApplicationContext: initialization completed in 744 ms2024-04-18T17:42:29.100+08:00INFO22192---[JavaAI][ main]o.s.b.w.embedded.tomcat.TomcatWebServer:Tomcat started on port 8080(http)withcontext path ''2024-04-18T17:42:29.106+08:00INFO22192---[JavaAI][ main]com.gem.javaai.JavaAiApplication:StartedJavaAiApplication in 1.95 seconds (process running for2.765)
- 启动成功后,我们可以使用IDEA自带的Http Client工具进行测试。点击方法左侧的绿色豆子即可。1.
- 使用这个工具的好处是他会记录每次的返回结果且不用额外安装。当然你也可以使用其他测试工具。1.
- 点绿色的箭头,调用成功后,会在返回结果中看到ChatGPT讲的笑话。1.
GEThttp://localhost:8080/ai/generateHTTP/1.1200 Content-Type: application/jsonTransfer-Encoding: chunkedDate: Thu,18 Apr 202410:08:37GMTKeep-Alive: timeout=60Connection: keep-alive{"generation":"Why did the scarecrow win an award? Because he was outstanding in his field!"}Response file saved.>2024-04-18T180837.200.jsonResponse code:200; Time:1602ms(1 s 602 ms); Content length:94bytes(94B)
- 程序内部调用的是这个接口地址,可以先用浏览器访问下是否能正常返回
- 本文到此结束,大家学会了么?😁
参考教程
本文转载自: https://blog.csdn.net/namelessmyth/article/details/137931504
版权归原作者 namelessmyth 所有, 如有侵权,请联系我们删除。
版权归原作者 namelessmyth 所有, 如有侵权,请联系我们删除。