Spring AI,调用OpenAI大模型接口,让ChatGPT给你讲笑话

2024-04-19 00:20

本文主要是介绍Spring AI,调用OpenAI大模型接口,让ChatGPT给你讲笑话,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

Spring最近刚刚推出了SpringAI,封装了AI大模型接口的使用。本文将参考Spring官网案例,一步步教你如何调用OpenAI的接口,让ChatGPT接口返回一个笑话。

前提条件

  • 请下载并安装好JDK17或更新的版本,本文使用的是JDK21。JDK下载地址。
  • 准备好梯子。没有梯子,调用OpenAI接口会报500错误。(也别问我梯子是啥,懂得都懂🤫)。
  • 准备好OpenAI接口的API Key,淘宝上有卖的(应该不差过10元)。
  • 如果你的Maven用的是阿里云仓库,建议先注释掉。AI依赖包太新了,目前阿里云还没有。

创建项目

  1. 使用idea创建一个新的Spring项目。File > New > Project > Spring Initializer

  2. Server URL一定要用Spring的:https://start.spring.io,其他的地址目前还没更新。

  3. JDK版本一定要大于等于17,低版本不支持Springboot3

  4. 在这里插入图片描述

  5. 依赖包选择Spring Web和OpenAI(在最下方),如下图

  6. 在这里插入图片描述

  7. 创建成功之后,等待项目自动下载依赖包。这里就看大家网速了。

配置开发

  1. 项目创建好之后,加入OpenAI接口配置。

    1. application.properties

    2. 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-turbo
      spring.ai.openai.chat.options.temperature=0.7
      
    3. pom.xml,这里面的内容是自动生成的,一般不用改。

    4. <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="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>
      
  2. 在你的启动类中加入代理设置,不然掉接口会报500。

    1. JavaAiApplication.java

    2. import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
      public class JavaAiApplication {public static void main(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);}
      }
      
  3. 创建controller,使用调用OpenAI的接口。

    1. ChatController

    2. import org.springframework.ai.chat.ChatResponse;
      import org.springframework.ai.chat.messages.UserMessage;
      import org.springframework.ai.chat.prompt.Prompt;
      import org.springframework.ai.openai.OpenAiChatClient;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.bind.annotation.RestController;
      import reactor.core.publisher.Flux;import java.util.Map;/*** ChatGPT接口调用<br>** @author Gem* @version 1.0* @date 2024/4/18*/
      @RestController
      public class ChatController {private final OpenAiChatClient chatClient;@Autowiredpublic ChatController(OpenAiChatClient chatClient) {this.chatClient = chatClient;}@GetMapping("/ai/generate")public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {return Map.of("generation", chatClient.call(message));}@GetMapping("/ai/generateStream")public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {Prompt prompt = new Prompt(new UserMessage(message));return chatClient.stream(prompt);}
      }
      
    3. 到此,开发配置结束。

启动调试

  1. 启动项目,启动前请先开启梯子,默认端口号:8080。

    1. 启动成功日志

    2. Connected to the target VM, address: '127.0.0.1:55997', transport: 'socket'.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
      ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::                (v3.2.4)2024-04-18T17:42:27.495+08:00  INFO 22192 --- [JavaAI] [           main] com.gem.javaai.JavaAiApplication         : Starting JavaAiApplication using Java 21.0.3 with PID 22192 (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:00  INFO 22192 --- [JavaAI] [           main] com.gem.javaai.JavaAiApplication         : No active profile set, falling back to 1 default profile: "default"
      2024-04-18T17:42:28.371+08:00  INFO 22192 --- [JavaAI] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
      2024-04-18T17:42:28.380+08:00  INFO 22192 --- [JavaAI] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
      2024-04-18T17:42:28.380+08:00  INFO 22192 --- [JavaAI] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.19]
      2024-04-18T17:42:28.423+08:00  INFO 22192 --- [JavaAI] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
      2024-04-18T17:42:28.423+08:00  INFO 22192 --- [JavaAI] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 744 ms
      2024-04-18T17:42:29.100+08:00  INFO 22192 --- [JavaAI] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path ''
      2024-04-18T17:42:29.106+08:00  INFO 22192 --- [JavaAI] [           main] com.gem.javaai.JavaAiApplication         : Started JavaAiApplication in 1.95 seconds (process running for 2.765)
      
  2. 启动成功后,我们可以使用IDEA自带的Http Client工具进行测试。点击方法左侧的绿色豆子即可。

    1. 在这里插入图片描述
  3. 使用这个工具的好处是他会记录每次的返回结果且不用额外安装。当然你也可以使用其他测试工具。

    1. 在这里插入图片描述
  4. 点绿色的箭头,调用成功后,会在返回结果中看到ChatGPT讲的笑话。

    1. GET http://localhost:8080/ai/generateHTTP/1.1 200 
      Content-Type: application/json
      Transfer-Encoding: chunked
      Date: Thu, 18 Apr 2024 10:08:37 GMT
      Keep-Alive: timeout=60
      Connection: 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: 94 bytes (94 B)
      
  5. 程序内部调用的是这个接口地址,可以先用浏览器访问下是否能正常返回

  6. 本文到此结束,大家学会了么?😁

参考教程

https://www.bilibili.com/video/BV1HJ4m1L7qw/?spm_id_from=333.337.search-card.all.click&vd_source=cbae38ae3b5a4c826df018bbf1c10a9d

这篇关于Spring AI,调用OpenAI大模型接口,让ChatGPT给你讲笑话的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/916174

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.