作者 钟来

Default Changelist

正在显示 22 个修改的文件 包含 996 行增加2 行删除
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <modelVersion>4.0.0</modelVersion>
  6 + <parent>
  7 + <groupId>com.zhonglai.luhui</groupId>
  8 + <artifactId>Luhui</artifactId>
  9 + <version>1.0-SNAPSHOT</version>
  10 + </parent>
  11 +
  12 + <artifactId>lh-chatgpt-api</artifactId>
  13 +
  14 + <properties>
  15 + <maven.compiler.source>8</maven.compiler.source>
  16 + <maven.compiler.target>8</maven.compiler.target>
  17 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18 + </properties>
  19 +
  20 + <dependencies>
  21 + <dependency>
  22 + <groupId>org.springframework.boot</groupId>
  23 + <artifactId>spring-boot-devtools</artifactId>
  24 + <optional>true</optional> <!-- 表示依赖不会传递 -->
  25 + </dependency>
  26 +
  27 + <!-- SpringBoot Web容器 -->
  28 + <dependency>
  29 + <groupId>org.springframework.boot</groupId>
  30 + <artifactId>spring-boot-starter-web</artifactId>
  31 + </dependency>
  32 + <!-- SpringWeb模块 -->
  33 + <dependency>
  34 + <groupId>org.springframework</groupId>
  35 + <artifactId>spring-web</artifactId>
  36 + </dependency>
  37 + <!-- servlet包 -->
  38 + <dependency>
  39 + <groupId>javax.servlet</groupId>
  40 + <artifactId>javax.servlet-api</artifactId>
  41 + </dependency>
  42 + <dependency>
  43 + <groupId>org.apache.commons</groupId>
  44 + <artifactId>commons-text</artifactId>
  45 + </dependency>
  46 +
  47 + <!-- 文档 -->
  48 + <dependency>
  49 + <groupId>io.springfox</groupId>
  50 + <artifactId>springfox-swagger2</artifactId>
  51 + <version>${swagger.version}</version>
  52 + <exclusions>
  53 + <exclusion>
  54 + <groupId>io.swagger</groupId>
  55 + <artifactId>swagger-models</artifactId>
  56 + </exclusion>
  57 + <exclusion>
  58 + <groupId>com.google.guava</groupId>
  59 + <artifactId>guava</artifactId>
  60 + </exclusion>
  61 + </exclusions>
  62 + </dependency>
  63 + <!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
  64 + <dependency>
  65 + <groupId>io.swagger</groupId>
  66 + <artifactId>swagger-models</artifactId>
  67 + <version>${swagger-models.version}</version>
  68 + </dependency>
  69 + <dependency>
  70 + <groupId>io.springfox</groupId>
  71 + <artifactId>springfox-swagger-ui</artifactId>
  72 + <version>${swagger.version}</version>
  73 + </dependency>
  74 + <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
  75 + <dependency>
  76 + <groupId>com.github.xiaoymin</groupId>
  77 + <artifactId>swagger-bootstrap-ui</artifactId>
  78 + <version>${swagger-ui.version}</version>
  79 + </dependency>
  80 +
  81 + <dependency>
  82 + <groupId>cn.hutool</groupId>
  83 + <artifactId>hutool-all</artifactId>
  84 + </dependency>
  85 +
  86 + <dependency>
  87 + <groupId>com.squareup.okhttp3</groupId>
  88 + <artifactId>okhttp</artifactId>
  89 + <version>4.10.0</version>
  90 + </dependency>
  91 + <!-- 阿里JSON解析器 -->
  92 + <dependency>
  93 + <groupId>com.alibaba</groupId>
  94 + <artifactId>fastjson</artifactId>
  95 + </dependency>
  96 + </dependencies>
  97 +
  98 + <build>
  99 + <finalName>lh-chatgpt-api</finalName>
  100 + <plugins>
  101 + <plugin>
  102 + <groupId>org.apache.maven.plugins</groupId>
  103 + <artifactId>maven-jar-plugin</artifactId>
  104 + <version>2.4</version>
  105 + <configuration>
  106 + <archive>
  107 + <!--
  108 + 生成的jar中,不要包含pom.xml和pom.properties这两个文件
  109 + -->
  110 + <addMavenDescriptor>false</addMavenDescriptor>
  111 + <manifest>
  112 + <!--
  113 + 是否要把第三方jar放到manifest的classpath中
  114 + -->
  115 + <addClasspath>true</addClasspath>
  116 +
  117 + <!--
  118 + 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
  119 + -->
  120 + <classpathPrefix>lib/</classpathPrefix>
  121 + <mainClass>com.zhonglai.luhui.ChatgptApplication</mainClass>
  122 + </manifest>
  123 + </archive>
  124 + </configuration>
  125 + </plugin>
  126 +
  127 + <!-- The configuration of maven-assembly-plugin -->
  128 + <plugin>
  129 + <groupId>org.apache.maven.plugins</groupId>
  130 + <artifactId>maven-assembly-plugin</artifactId>
  131 + <version>2.4</version>
  132 + <configuration>
  133 + <descriptors>
  134 + <descriptor>src/main/resources/package.xml</descriptor>
  135 + </descriptors>
  136 + </configuration>
  137 + <executions>
  138 + <execution>
  139 + <id>make-assembly</id>
  140 + <phase>package</phase>
  141 + <goals>
  142 + <goal>single</goal>
  143 + </goals>
  144 + </execution>
  145 + </executions>
  146 + </plugin>
  147 + </plugins>
  148 + </build>
  149 +</project>
  1 +package com.zhonglai.luhui;
  2 +
  3 +import org.springframework.boot.SpringApplication;
  4 +import org.springframework.boot.autoconfigure.SpringBootApplication;
  5 +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
  6 +import org.springframework.context.annotation.ComponentScan;
  7 +
  8 +@ComponentScan(basePackages = {
  9 + "com.zhonglai.luhui.config",
  10 +}
  11 +
  12 +)
  13 +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
  14 +public class ChatgptApplication {
  15 + public static void main(String[] args) {
  16 + SpringApplication.run(ChatgptApplication.class,args);
  17 + System.out.println("启动成功");
  18 + }
  19 +}
  1 +package com.zhonglai.luhui.config;
  2 +
  3 +import org.springframework.context.annotation.Bean;
  4 +import org.springframework.context.annotation.Configuration;
  5 +import org.springframework.web.cors.CorsConfiguration;
  6 +import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  7 +import org.springframework.web.filter.CorsFilter;
  8 +
  9 +/**
  10 + * 跨域配置,需要和WebMvcConfigurerAdapter的addCorsMappings配合使用
  11 + */
  12 +@Configuration
  13 +public class CorsConfig {
  14 + private CorsConfiguration buildConfig() {
  15 + CorsConfiguration corsConfiguration = new CorsConfiguration();
  16 + corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
  17 + corsConfiguration.addAllowedHeader("*"); // 2允许任何头
  18 + corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
  19 + return corsConfiguration;
  20 + }
  21 +
  22 + @Bean
  23 + public CorsFilter corsFilter() {
  24 + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  25 + source.registerCorsConfiguration("/**", buildConfig()); // 4
  26 + return new CorsFilter(source);
  27 + }
  28 +}
  1 +package com.zhonglai.luhui.config;
  2 +
  3 +import io.swagger.annotations.ApiOperation;
  4 +import org.springframework.context.annotation.Bean;
  5 +import org.springframework.context.annotation.Configuration;
  6 +import springfox.documentation.builders.ApiInfoBuilder;
  7 +import springfox.documentation.builders.PathSelectors;
  8 +import springfox.documentation.builders.RequestHandlerSelectors;
  9 +import springfox.documentation.service.ApiInfo;
  10 +import springfox.documentation.service.Contact;
  11 +import springfox.documentation.spi.DocumentationType;
  12 +import springfox.documentation.spring.web.plugins.Docket;
  13 +import springfox.documentation.swagger2.annotations.EnableSwagger2;
  14 +
  15 +
  16 +@Configuration
  17 +@EnableSwagger2
  18 +public class SwaggerConfig {
  19 + @Bean
  20 + public Docket createRestApi() {
  21 + return new Docket(DocumentationType.SWAGGER_2)
  22 + .apiInfo(apiInfo())
  23 + .select()
  24 + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  25 + .paths(PathSelectors.any())
  26 + .build();
  27 + }
  28 +
  29 + /**
  30 + * 添加摘要信息
  31 + */
  32 + private ApiInfo apiInfo()
  33 + {
  34 + // 用ApiInfoBuilder进行定制
  35 + return new ApiInfoBuilder()
  36 + // 设置标题
  37 + .title("标题:lh-chatgpt-api中间件接口文档")
  38 + // 描述
  39 + .description("描述:chatgpt请求的接口")
  40 + // 作者信息
  41 + .contact(new Contact("", null, null))
  42 + // 版本
  43 + .version("版本号:1.1.1" )
  44 + .build();
  45 + }
  46 +
  47 +}
  1 +package com.zhonglai.luhui.controller;
  2 +
  3 +import cn.hutool.http.HttpUtil;
  4 +import com.alibaba.fastjson.JSONObject;
  5 +import com.zhonglai.luhui.dto.ChatGPTApiDto;
  6 +import com.zhonglai.luhui.dto.ChatRoomMessages;
  7 +import com.zhonglai.luhui.dto.CompletionResult3_5;
  8 +import io.swagger.annotations.Api;
  9 +import io.swagger.annotations.ApiOperation;
  10 +import org.apache.commons.lang3.StringUtils;
  11 +import org.slf4j.Logger;
  12 +import org.slf4j.LoggerFactory;
  13 +import org.springframework.web.bind.annotation.GetMapping;
  14 +import org.springframework.web.bind.annotation.RequestBody;
  15 +import org.springframework.web.bind.annotation.RequestMapping;
  16 +import org.springframework.web.bind.annotation.RestController;
  17 +
  18 +import javax.servlet.http.HttpServletResponse;
  19 +import java.io.IOException;
  20 +import java.io.PrintWriter;
  21 +import java.util.List;
  22 +
  23 +@Api(tags = "chatGPT接口")
  24 +@RestController
  25 +@RequestMapping("/chatGPTApi")
  26 +public class ChatGPTApiController {
  27 +
  28 + protected final Logger logger = LoggerFactory.getLogger(this.getClass());
  29 +
  30 + @ApiOperation(value = "测试")
  31 + @GetMapping("/sendMessage")
  32 + public void sendMessage(HttpServletResponse response, @RequestBody ChatGPTApiDto chatGPTApiDto)
  33 + {
  34 + // 设置响应内容类型和编码
  35 + response.setContentType("text/html;charset=UTF-8");
  36 +
  37 + String str = "";
  38 + PrintWriter out = null;
  39 + try {
  40 + out = response.getWriter();
  41 + //验证验证码
  42 + if(StringUtils.isNotEmpty(str))
  43 + {
  44 + for(int i=0;i<str.length();i++)
  45 + {
  46 + char c = str.charAt(i);
  47 + out.write(c);
  48 + out.flush(); // 立即将字符输出到客户端
  49 + try {
  50 + Thread.sleep(1000);
  51 + } catch (InterruptedException e) {
  52 + throw new RuntimeException(e);
  53 + }
  54 + }
  55 + }
  56 + } catch (IOException e) {
  57 + throw new RuntimeException(e);
  58 + }finally {
  59 + if(null != out)
  60 + {
  61 + out.close();
  62 + }
  63 + }
  64 + }
  65 +
  66 +
  67 + private CompletionResult3_5 sendGPTAi(List<ChatRoomMessages> messageList)
  68 + {
  69 + logger.info("请求内容:{}",messageList);
  70 + JSONObject jsonObject = new JSONObject();
  71 + jsonObject.put("model","gpt-3.5-turbo-0301");
  72 + jsonObject.put("messages",messageList);
  73 + String str = HttpUtil.post("https://chatgpt.njlaikun.com/v1/chat/completions",jsonObject.toString());
  74 + logger.info("返回的数据:{}",str);
  75 + CompletionResult3_5 completionResult = JSONObject.parseObject(str, CompletionResult3_5.class);
  76 + return completionResult;
  77 + }
  78 +
  79 + /**
  80 + * 免费接口
  81 + * @param messageList
  82 + * @return
  83 + */
  84 + private CompletionResult3_5 sendFreeGPTAi(List<ChatRoomMessages> messageList)
  85 + {
  86 + logger.info("请求内容:{}",messageList);
  87 + JSONObject jsonObject = new JSONObject();
  88 + jsonObject.put("model","gpt-3.5-turbo-0301");
  89 + jsonObject.put("messages",messageList);
  90 + String str = HttpUtil.post("https://free.chatgpt.njlaikun.com/v1/chat/completions",jsonObject.toString());
  91 + logger.info("返回的数据:{}",str);
  92 + CompletionResult3_5 completionResult = JSONObject.parseObject(str, CompletionResult3_5.class);
  93 + return completionResult;
  94 + }
  95 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +import java.util.List;
  4 +
  5 +public class ChatGPTApiDto {
  6 + private List<ChatRoomMessages> messageList;
  7 + private Integer user_id;
  8 + private String room_id;
  9 + private Integer gptMessage_id;
  10 +
  11 + private Boolean isfree;
  12 +
  13 + public Boolean getIsfree() {
  14 + return isfree;
  15 + }
  16 +
  17 + public void setIsfree(Boolean isfree) {
  18 + this.isfree = isfree;
  19 + }
  20 +
  21 + public Integer getGptMessage_id() {
  22 + return gptMessage_id;
  23 + }
  24 +
  25 + public void setGptMessage_id(Integer gptMessage_id) {
  26 + this.gptMessage_id = gptMessage_id;
  27 + }
  28 +
  29 + public Integer getUser_id() {
  30 + return user_id;
  31 + }
  32 +
  33 + public void setUser_id(Integer user_id) {
  34 + this.user_id = user_id;
  35 + }
  36 +
  37 + public String getRoom_id() {
  38 + return room_id;
  39 + }
  40 +
  41 + public void setRoom_id(String room_id) {
  42 + this.room_id = room_id;
  43 + }
  44 +
  45 + public List<ChatRoomMessages> getMessageList() {
  46 + return messageList;
  47 + }
  48 +
  49 + public void setMessageList(List<ChatRoomMessages> messageList) {
  50 + this.messageList = messageList;
  51 + }
  52 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +/**
  4 + * 聊天室消息
  5 + */
  6 +public class ChatRoomMessages {
  7 + private String role; //角色(system “系统”、user “用户”、assistant “助手”)
  8 + private String content; //内容(消息的内容)
  9 +
  10 + public String getRole() {
  11 + return role;
  12 + }
  13 +
  14 + public void setRole(String role) {
  15 + this.role = role;
  16 + }
  17 +
  18 + public String getContent() {
  19 + return content;
  20 + }
  21 +
  22 + public void setContent(String content) {
  23 + this.content = content;
  24 + }
  25 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +public class CompletionChoice3_5 {
  4 + private CompletionChoiceMessage3_5 message;
  5 + private String finish_reason;
  6 + private Integer index;
  7 +
  8 + public CompletionChoiceMessage3_5 getMessage() {
  9 + return message;
  10 + }
  11 +
  12 + public void setMessage(CompletionChoiceMessage3_5 message) {
  13 + this.message = message;
  14 + }
  15 +
  16 + public String getFinish_reason() {
  17 + return finish_reason;
  18 + }
  19 +
  20 + public void setFinish_reason(String finish_reason) {
  21 + this.finish_reason = finish_reason;
  22 + }
  23 +
  24 + public Integer getIndex() {
  25 + return index;
  26 + }
  27 +
  28 + public void setIndex(Integer index) {
  29 + this.index = index;
  30 + }
  31 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +public class CompletionChoiceMessage3_5 {
  4 + private String role;
  5 + private String content;
  6 +
  7 + public CompletionChoiceMessage3_5() {
  8 + }
  9 +
  10 + public CompletionChoiceMessage3_5(String role, String content) {
  11 + this.role = role;
  12 + this.content = content;
  13 + }
  14 +
  15 + public String getRole() {
  16 + return role;
  17 + }
  18 +
  19 + public void setRole(String role) {
  20 + this.role = role;
  21 + }
  22 +
  23 + public String getContent() {
  24 + return content;
  25 + }
  26 +
  27 + public void setContent(String content) {
  28 + this.content = content;
  29 + }
  30 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +import java.util.List;
  4 +
  5 +public class CompletionResult3_5 {
  6 + private String id;
  7 + private String object;
  8 + private Long created;
  9 + private String model;
  10 + private List<CompletionChoice3_5> choices;
  11 + private Usage usage;
  12 + private Integer user_id;
  13 + private String room_id;
  14 + private Integer gptMessage_id;
  15 +
  16 + public Integer getGptMessage_id() {
  17 + return gptMessage_id;
  18 + }
  19 +
  20 + public void setGptMessage_id(Integer gptMessage_id) {
  21 + this.gptMessage_id = gptMessage_id;
  22 + }
  23 + public Integer getUser_id() {
  24 + return user_id;
  25 + }
  26 +
  27 + public void setUser_id(Integer user_id) {
  28 + this.user_id = user_id;
  29 + }
  30 + public String getId() {
  31 + return id;
  32 + }
  33 +
  34 + public void setId(String id) {
  35 + this.id = id;
  36 + }
  37 +
  38 + public String getObject() {
  39 + return object;
  40 + }
  41 +
  42 + public void setObject(String object) {
  43 + this.object = object;
  44 + }
  45 +
  46 + public Long getCreated() {
  47 + return created;
  48 + }
  49 +
  50 + public void setCreated(Long created) {
  51 + this.created = created;
  52 + }
  53 +
  54 + public String getModel() {
  55 + return model;
  56 + }
  57 +
  58 + public void setModel(String model) {
  59 + this.model = model;
  60 + }
  61 +
  62 + public List<CompletionChoice3_5> getChoices() {
  63 + return choices;
  64 + }
  65 +
  66 + public void setChoices(List<CompletionChoice3_5> choices) {
  67 + this.choices = choices;
  68 + }
  69 +
  70 + public Usage getUsage() {
  71 + return usage;
  72 + }
  73 +
  74 + public void setUsage(Usage usage) {
  75 + this.usage = usage;
  76 + }
  77 +}
  1 +package com.zhonglai.luhui.dto;
  2 +
  3 +public class Usage {
  4 + long promptTokens;
  5 + long completionTokens;
  6 + long totalTokens;
  7 +
  8 + public long getPromptTokens() {
  9 + return promptTokens;
  10 + }
  11 +
  12 + public void setPromptTokens(long promptTokens) {
  13 + this.promptTokens = promptTokens;
  14 + }
  15 +
  16 + public long getCompletionTokens() {
  17 + return completionTokens;
  18 + }
  19 +
  20 + public void setCompletionTokens(long completionTokens) {
  21 + this.completionTokens = completionTokens;
  22 + }
  23 +
  24 + public long getTotalTokens() {
  25 + return totalTokens;
  26 + }
  27 +
  28 + public void setTotalTokens(long totalTokens) {
  29 + this.totalTokens = totalTokens;
  30 + }
  31 +}
  1 +##服务器配置
  2 +server:
  3 + tomcat:
  4 + uri-encoding: UTF-8
  5 + port: 8086
  6 + context-path: /
  7 +
  8 +spring:
  9 + messages:
  10 + encoding: UTF-8
  11 + mvc:
  12 + #出现错误时, 直接抛出异常
  13 + throw-exception-if-no-handler-found: true
  14 + jackson:
  15 + date-format: yyyy-MM-dd HH:mm:ss
  16 + time-zone: GMT+8
  17 + default-property-inclusion: non_null
  1 +log4j.rootLogger=info,indicator,FILE
  2 +
  3 +log4j.appender.indicator=org.apache.log4j.ConsoleAppender
  4 +log4j.appender.indicator.layout=org.apache.log4j.PatternLayout
  5 +log4j.appender.indicator.layout.ConversionPattern=%d{HH:mm:ss} [%p] %l -%m%n
  6 +
  7 +log4j.appender.FILE = org.apache.log4j.RollingFileAppender
  8 +log4j.appender.FILE.File = logs/output.log
  9 +log4j.appender.FILE.MaxFileSize = 2000KB
  10 +log4j.appender.FILE.MaxBackupIndex = 5
  11 +log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
  12 +log4j.appender.FILE.layout.ConversionPattern = %d{HH:mm:ss} [%p] %l -%m%n
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +
  3 +<assembly>
  4 + <id>bin</id>
  5 + <!-- 最终打包成一个用于发布的zip文件 -->
  6 + <formats>
  7 + <format>zip</format>
  8 + </formats>
  9 +
  10 + <!-- Adds dependencies to zip package under lib directory -->
  11 + <dependencySets>
  12 + <dependencySet>
  13 + <!--
  14 + 不使用项目的artifact,第三方jar不要解压,打包进zip文件的lib目录
  15 + -->
  16 + <useProjectArtifact>false</useProjectArtifact>
  17 + <outputDirectory>lib</outputDirectory>
  18 + <unpack>false</unpack>
  19 + </dependencySet>
  20 + </dependencySets>
  21 +
  22 + <fileSets>
  23 + <!-- 把项目相关的说明文件,打包进zip文件的根目录 -->
  24 + <fileSet>
  25 + <directory>${project.basedir}</directory>
  26 + <outputDirectory>/</outputDirectory>
  27 + <includes>
  28 + <include>README*</include>
  29 + <include>LICENSE*</include>
  30 + <include>NOTICE*</include>
  31 + </includes>
  32 + </fileSet>
  33 +
  34 + <!-- 把项目的配置文件,打包进zip文件的config目录 -->
  35 + <fileSet>
  36 + <directory>${project.basedir}\src\main\resources\configs</directory>
  37 + <outputDirectory>../configs</outputDirectory>
  38 + <includes>
  39 + <include>*.properties</include>
  40 + </includes>
  41 + </fileSet>
  42 +
  43 + <!-- 把项目的配置文件,提出来 -->
  44 + <fileSet>
  45 + <directory>${project.basedir}\src\main\resources</directory>
  46 + <outputDirectory>/</outputDirectory>
  47 + <includes>
  48 + <include>*.properties</include>
  49 + <include>*.yml</include>
  50 + </includes>
  51 + </fileSet>
  52 +
  53 + <!-- 把项目的脚本文件目录( src/main/scripts )中的启动脚本文件,打包进zip文件的跟目录 -->
  54 + <fileSet>
  55 + <directory>${project.basedir}\bin</directory>
  56 + <outputDirectory></outputDirectory>
  57 + <includes>
  58 + <include>start.*</include>
  59 + <include>stop.*</include>
  60 + </includes>
  61 + </fileSet>
  62 +
  63 + <!-- 把项目自己编译出来的jar文件,打包进zip文件的根目录 -->
  64 + <fileSet>
  65 + <directory>${project.build.directory}</directory>
  66 + <outputDirectory></outputDirectory>
  67 + <includes>
  68 + <include>*.jar</include>
  69 + </includes>
  70 + </fileSet>
  71 + </fileSets>
  72 +</assembly>
@@ -99,7 +99,7 @@ public class ChatGPTController extends BaseController { @@ -99,7 +99,7 @@ public class ChatGPTController extends BaseController {
99 @ApiOperation(value = "chatgpt3.5",notes = "上下文关联,要实现上下问关联就需要记录整个聊天的提问记录,目前只支持相同session的上下文关联,就是说,如果聊天页面关闭以后再打开,是没有上下文关联的") 99 @ApiOperation(value = "chatgpt3.5",notes = "上下文关联,要实现上下问关联就需要记录整个聊天的提问记录,目前只支持相同session的上下文关联,就是说,如果聊天页面关闭以后再打开,是没有上下文关联的")
100 @Transactional 100 @Transactional
101 @RequestMapping(value = "/chatgptV3_5",method = RequestMethod.POST) 101 @RequestMapping(value = "/chatgptV3_5",method = RequestMethod.POST)
102 - public AjaxResult chatgptV3_5(HttpServletRequest httpServletRequest,@RequestBody String data) 102 + public AjaxResult chatgptV3_5(HttpServletRequest httpServletRequest,@RequestBody ChatgptMessageDto chatgptMessageDto)
103 { 103 {
104 //跟进用户信息生成入口参数 104 //跟进用户信息生成入口参数
105 OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser(); 105 OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser();
@@ -140,7 +140,7 @@ public class ChatGPTController extends BaseController { @@ -140,7 +140,7 @@ public class ChatGPTController extends BaseController {
140 List<ChatRoomMessages> messageList = Optional.ofNullable((List<ChatRoomMessages>) session.getAttribute(sessionkey)).orElse(new ArrayList<>()); 140 List<ChatRoomMessages> messageList = Optional.ofNullable((List<ChatRoomMessages>) session.getAttribute(sessionkey)).orElse(new ArrayList<>());
141 ChatRoomMessages chatRoomMessages = new ChatRoomMessages(); 141 ChatRoomMessages chatRoomMessages = new ChatRoomMessages();
142 chatRoomMessages.setRole("user"); 142 chatRoomMessages.setRole("user");
143 - chatRoomMessages.setContent(data); 143 + chatRoomMessages.setContent(chatgptMessageDto.getData());
144 messageList.add(chatRoomMessages); 144 messageList.add(chatRoomMessages);
145 session.setAttribute(sessionkey,messageList); 145 session.setAttribute(sessionkey,messageList);
146 146
  1 +package com.zhonglai.luhui.openai.controller;
  2 +
  3 +import cn.hutool.http.HttpUtil;
  4 +import com.alibaba.fastjson.JSONObject;
  5 +import com.ruoyi.common.core.controller.BaseController;
  6 +import com.ruoyi.common.core.domain.AjaxResult;
  7 +import com.ruoyi.common.utils.DateUtils;
  8 +import com.ruoyi.system.login.dto.OpenAiLoginUser;
  9 +import com.ruoyi.system.login.dto.OpenAiUserInfo;
  10 +import com.ruoyi.system.service.PublicService;
  11 +import com.theokanning.openai.Usage;
  12 +import com.zhonglai.luhui.openai.dto.*;
  13 +import com.zhonglai.luhui.openai.service.VipServiceImpl;
  14 +import io.swagger.annotations.Api;
  15 +import io.swagger.annotations.ApiOperation;
  16 +import okhttp3.*;
  17 +import org.jetbrains.annotations.NotNull;
  18 +import org.springframework.beans.factory.annotation.Autowired;
  19 +import org.springframework.transaction.annotation.Transactional;
  20 +import org.springframework.web.bind.annotation.RequestBody;
  21 +import org.springframework.web.bind.annotation.RequestMapping;
  22 +import org.springframework.web.bind.annotation.RequestMethod;
  23 +import org.springframework.web.bind.annotation.RestController;
  24 +
  25 +import javax.servlet.http.HttpServletRequest;
  26 +import javax.servlet.http.HttpServletResponse;
  27 +import javax.servlet.http.HttpSession;
  28 +import java.io.IOException;
  29 +import java.io.InputStream;
  30 +import java.io.PrintWriter;
  31 +import java.math.BigDecimal;
  32 +import java.util.ArrayList;
  33 +import java.util.List;
  34 +import java.util.Optional;
  35 +
  36 +@Api(tags = "chatGPT流接口")
  37 +@RestController
  38 +@RequestMapping("/chatGPTStream")
  39 +public class ChatGPTStreamController extends BaseController {
  40 + private static String sessionkey = "CHAT_HISTORY_CONTEXT";//上下文关联存放地址
  41 + @Autowired
  42 + private PublicService publicService;
  43 +
  44 + @Autowired
  45 + private VipServiceImpl vipService;
  46 + @ApiOperation(value = "chatgpt3.5",notes = "上下文关联,要实现上下问关联就需要记录整个聊天的提问记录,目前只支持相同session的上下文关联,就是说,如果聊天页面关闭以后再打开,是没有上下文关联的")
  47 + @Transactional
  48 + @RequestMapping(value = "/chatgptV3_5",method = RequestMethod.POST)
  49 + public void chatgptV3_5(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody ChatgptMessageDto chatgptMessageDto) throws IOException {
  50 + //跟进用户信息生成入口参数
  51 + OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser();
  52 + Integer user_id= userInfo.getUserId().intValue();
  53 + String room_id = String.valueOf(user_id);
  54 +
  55 + OpenAiUserInfo openAiUserInfo = (OpenAiUserInfo) userInfo.getUser();
  56 +
  57 +
  58 + PrintWriter out = httpServletResponse.getWriter();
  59 + //验证余额是否充足
  60 + if(vipService.isCharging(openAiUserInfo.getVip_level()) && openAiUserInfo.getFlow_packet_remain()<=0)
  61 + {
  62 + StringBuffer stringBuffer = new StringBuffer();
  63 + stringBuffer.append("您的余额不足请联系管理员或者点击链接充值:\\n\\n");
  64 + stringBuffer.append("https://充值链接.com");
  65 + out.write(stringBuffer.toString());
  66 + return;
  67 + }
  68 +
  69 + BigDecimal[] bs = vipService.getUnitprice();
  70 + BigDecimal openaiUnitprice = bs[0];
  71 + BigDecimal realityUnitprice = bs[1];
  72 + if(openaiUnitprice.doubleValue()==0 || realityUnitprice.doubleValue()==0)
  73 + {
  74 + out.write("系统未配置流量单价,请联系管理员");
  75 + return;
  76 + }
  77 +
  78 + logger.info("{}生成聊天会话:",room_id);
  79 +
  80 + //上下文关联
  81 + HttpSession session = httpServletRequest.getSession();
  82 + List<ChatRoomMessages> messageList = Optional.ofNullable((List<ChatRoomMessages>) session.getAttribute(sessionkey)).orElse(new ArrayList<>());
  83 + ChatRoomMessages chatRoomMessages = new ChatRoomMessages();
  84 + chatRoomMessages.setRole("user");
  85 + chatRoomMessages.setContent(chatgptMessageDto.getData());
  86 + messageList.add(chatRoomMessages);
  87 + session.setAttribute(sessionkey,messageList);
  88 +
  89 + GptMessage gptMessage = new GptMessage();
  90 + gptMessage.setRoom_id(room_id);
  91 + gptMessage.setUser_id(user_id);
  92 + gptMessage.setSend_role(chatRoomMessages.getRole());
  93 + gptMessage.setSend_content(chatRoomMessages.getContent());
  94 + gptMessage.setCreate_time(DateUtils.getNowTimeMilly());
  95 + publicService.insertToTable(gptMessage,"`lk_openai`.`gpt_message`");
  96 + //获取返回参数
  97 +
  98 + ChatGPTApiDto chatGPTApiDto = new ChatGPTApiDto();
  99 + chatGPTApiDto.setGptMessage_id(gptMessage.getId());
  100 + chatGPTApiDto.setMessageList(messageList);
  101 + chatGPTApiDto.setUser_id(user_id);
  102 + chatGPTApiDto.setRoom_id(room_id);
  103 + chatGPTApiDto.setIsfree(vipService.isfree(openAiUserInfo.getVip_level()));
  104 + HttpUtil.post("https://chatgpt.njlaikun.com/chatGPTApi/sendMessage", JSONObject.toJSONString(chatGPTApiDto));
  105 +
  106 + Request request = new Request.Builder()
  107 + .url("https://chatgpt.njlaikun.com/chatGPTApi/sendMessage")
  108 + .post(okhttp3.RequestBody.create(JSONObject.toJSONString(chatGPTApiDto), MediaType.parse("application/json;")))
  109 + .build();
  110 + OkHttpClient okHttpClient = new OkHttpClient();
  111 + okHttpClient.newCall(request).enqueue(new Callback() {
  112 + @Override
  113 + public void onFailure(@NotNull Call call, @NotNull IOException e) {
  114 +
  115 + }
  116 +
  117 + @Override
  118 + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  119 + InputStream inputStream = response.body().byteStream();
  120 + }
  121 + });
  122 + }
  123 +
  124 + @ApiOperation(value = "历史记录",notes = "默认获取最新5条记录")
  125 + @Transactional
  126 + @RequestMapping(value = "/upUserFlowPacketRemain",method = RequestMethod.POST)
  127 + public AjaxResult upUserFlowPacketRemain(@RequestBody CompletionResult3_5 completionResult3_5 )
  128 + {
  129 + Usage usage = completionResult3_5.getUsage();
  130 + List<CompletionChoice3_5> list3_5 = completionResult3_5.getChoices();
  131 +
  132 + if(null != list3_5 && list3_5.size() !=0 )
  133 + {
  134 + GptMessage gptMessage = new GptMessage();
  135 + gptMessage.setSend_size(0);
  136 + gptMessage.setPrompt_tokens(0l);
  137 + gptMessage.setCompletion_tokens(0l);
  138 + gptMessage.setTotal_tokens(0l);
  139 + gptMessage.setMessage_size(0);
  140 + for (CompletionChoice3_5 completionChoice:list3_5)
  141 + {
  142 + gptMessage.setSend_size(gptMessage.getSend_size()+gptMessage.getSend_content().length());
  143 + //统计代币
  144 + gptMessage.setCompletion_tokens(gptMessage.getCompletion_tokens()+usage.getCompletionTokens());
  145 + gptMessage.setPrompt_tokens(gptMessage.getPrompt_tokens()+usage.getPromptTokens());
  146 + gptMessage.setTotal_tokens(gptMessage.getTotal_tokens()+usage.getTotalTokens());
  147 +
  148 + if(null != completionChoice.getMessage())
  149 + {
  150 + gptMessage.setMessage_role(completionChoice.getMessage().getRole());
  151 + }
  152 +
  153 + if(null != gptMessage.getMessage_content())
  154 + {
  155 + gptMessage.setMessage_size(gptMessage.getMessage_size()+gptMessage.getMessage_content().length());
  156 + }
  157 +
  158 + }
  159 + gptMessage.setId(completionResult3_5.getGptMessage_id());
  160 + publicService.updateObjectByTable(gptMessage,"id","`lk_openai`.`gpt_message`");
  161 +
  162 + publicService.updateBySql("UPDATE `lk_openai`.`user_info` SET flow_packet_remain=flow_packet_remain-"+usage.getTotalTokens()+" WHERE id="+completionResult3_5.getUser_id());
  163 +
  164 + UserFlowPacketRemainLog userFlowPacketRemainLog = new UserFlowPacketRemainLog();
  165 + userFlowPacketRemainLog.setCreate_time(DateUtils.getNowTimeMilly());
  166 + userFlowPacketRemainLog.setUser_id(completionResult3_5.getUser_id());
  167 + userFlowPacketRemainLog.setType(2); //消费
  168 +
  169 + StringBuffer stringBuffer = new StringBuffer();
  170 + stringBuffer.append("房间号:");
  171 + stringBuffer.append(completionResult3_5.getRoom_id());
  172 + stringBuffer.append(";");
  173 + stringBuffer.append("发送代币:");
  174 + stringBuffer.append(usage.getPromptTokens());
  175 + stringBuffer.append(";");
  176 + stringBuffer.append("返回代币:");
  177 + stringBuffer.append(usage.getCompletionTokens());
  178 + stringBuffer.append(";");
  179 +
  180 + userFlowPacketRemainLog.setDescribe(stringBuffer.toString());
  181 + userFlowPacketRemainLog.setTotal_tokens(usage.getTotalTokens());
  182 +
  183 + BigDecimal[] bs = vipService.getUnitprice();
  184 + BigDecimal openaiUnitprice = bs[0];
  185 + BigDecimal realityUnitprice = bs[1];
  186 + userFlowPacketRemainLog.setOpenai_money((openaiUnitprice.multiply(new BigDecimal(usage.getTotalTokens()))).divide(new BigDecimal(1000),6,BigDecimal.ROUND_HALF_UP));
  187 + userFlowPacketRemainLog.setReality_money((realityUnitprice.multiply(new BigDecimal(usage.getTotalTokens()))).divide(new BigDecimal(1000),6,BigDecimal.ROUND_HALF_UP));
  188 + publicService.insertToTable(userFlowPacketRemainLog,"`lk_openai`.`user_flow_packet_remain_log`");
  189 + }
  190 + return AjaxResult.success();
  191 + }
  192 +}
@@ -12,6 +12,7 @@ import com.ruoyi.common.core.domain.MessageCode; @@ -12,6 +12,7 @@ import com.ruoyi.common.core.domain.MessageCode;
12 import com.ruoyi.common.utils.DESUtil; 12 import com.ruoyi.common.utils.DESUtil;
13 import com.ruoyi.common.utils.DateUtils; 13 import com.ruoyi.common.utils.DateUtils;
14 import com.ruoyi.common.utils.GsonConstructor; 14 import com.ruoyi.common.utils.GsonConstructor;
  15 +import com.ruoyi.common.utils.StringUtils;
15 import com.ruoyi.system.login.service.LoginService; 16 import com.ruoyi.system.login.service.LoginService;
16 import io.swagger.annotations.Api; 17 import io.swagger.annotations.Api;
17 import io.swagger.annotations.ApiImplicitParam; 18 import io.swagger.annotations.ApiImplicitParam;
@@ -23,6 +24,10 @@ import org.springframework.web.bind.annotation.PostMapping; @@ -23,6 +24,10 @@ import org.springframework.web.bind.annotation.PostMapping;
23 import org.springframework.web.bind.annotation.RequestMapping; 24 import org.springframework.web.bind.annotation.RequestMapping;
24 import org.springframework.web.bind.annotation.RestController; 25 import org.springframework.web.bind.annotation.RestController;
25 26
  27 +import javax.servlet.http.HttpServletRequest;
  28 +import javax.servlet.http.HttpServletResponse;
  29 +import java.io.IOException;
  30 +import java.io.PrintWriter;
26 import java.util.HashMap; 31 import java.util.HashMap;
27 import java.util.Map; 32 import java.util.Map;
28 33
@@ -95,4 +100,5 @@ public class OpenAiUserLoginController extends BaseController { @@ -95,4 +100,5 @@ public class OpenAiUserLoginController extends BaseController {
95 String agenlongtoken = DESUtil.encode(ss[0]+"_"+ DateUtils.getNowTimeMilly(),ENCODE_KEY); 100 String agenlongtoken = DESUtil.encode(ss[0]+"_"+ DateUtils.getNowTimeMilly(),ENCODE_KEY);
96 return AjaxResult.success().put(Constants.TOKEN, token).put("longtoken", agenlongtoken); 101 return AjaxResult.success().put(Constants.TOKEN, token).put("longtoken", agenlongtoken);
97 } 102 }
  103 +
98 } 104 }
@@ -58,6 +58,23 @@ public class UserInfoController extends BaseController { @@ -58,6 +58,23 @@ public class UserInfoController extends BaseController {
58 return AjaxResult.success(); 58 return AjaxResult.success();
59 } 59 }
60 60
  61 + @ApiOperation("修改昵称和头像")
  62 + @PostMapping("/upUserInfo")
  63 + public AjaxResult upUserInfo(String nickname,String img_url)
  64 + {
  65 + StringBuffer stringBuffer = new StringBuffer();
  66 + if(StringUtils.isNotEmpty(nickname))
  67 + {
  68 + stringBuffer.append(",nickname='"+nickname+"'");
  69 + }
  70 + if(StringUtils.isNotEmpty(img_url))
  71 + {
  72 + stringBuffer.append(",img_url='"+img_url+"'");
  73 + }
  74 + String sql = "UPDATE `lk_openai`.`user_info` SET id="+getUserId().intValue()+stringBuffer+" WHERE id="+getUserId().intValue();
  75 + return AjaxResult.success(publicService.updateBySql(sql));
  76 + }
  77 +
61 @ApiOperation("代币使用记录") 78 @ApiOperation("代币使用记录")
62 @GetMapping("/userFlowPacketRemainLog") 79 @GetMapping("/userFlowPacketRemainLog")
63 public TableDataInfo useFlowPacketRemainLog() 80 public TableDataInfo useFlowPacketRemainLog()
  1 +package com.zhonglai.luhui.openai.dto;
  2 +
  3 +import java.util.List;
  4 +
  5 +public class ChatGPTApiDto {
  6 + private List<ChatRoomMessages> messageList;
  7 + private Integer user_id;
  8 + private String room_id;
  9 + private Integer gptMessage_id;
  10 +
  11 + private Boolean isfree;
  12 +
  13 + public Boolean getIsfree() {
  14 + return isfree;
  15 + }
  16 +
  17 + public void setIsfree(Boolean isfree) {
  18 + this.isfree = isfree;
  19 + }
  20 +
  21 + public Integer getGptMessage_id() {
  22 + return gptMessage_id;
  23 + }
  24 +
  25 + public void setGptMessage_id(Integer gptMessage_id) {
  26 + this.gptMessage_id = gptMessage_id;
  27 + }
  28 +
  29 + public Integer getUser_id() {
  30 + return user_id;
  31 + }
  32 +
  33 + public void setUser_id(Integer user_id) {
  34 + this.user_id = user_id;
  35 + }
  36 +
  37 + public String getRoom_id() {
  38 + return room_id;
  39 + }
  40 +
  41 + public void setRoom_id(String room_id) {
  42 + this.room_id = room_id;
  43 + }
  44 +
  45 + public List<ChatRoomMessages> getMessageList() {
  46 + return messageList;
  47 + }
  48 +
  49 + public void setMessageList(List<ChatRoomMessages> messageList) {
  50 + this.messageList = messageList;
  51 + }
  52 +}
  1 +package com.zhonglai.luhui.openai.dto;
  2 +
  3 +public class ChatgptMessageDto {
  4 + private String data;
  5 +
  6 + public String getData() {
  7 + return data;
  8 + }
  9 +
  10 + public void setData(String data) {
  11 + this.data = data;
  12 + }
  13 +}
@@ -13,6 +13,34 @@ public class CompletionResult3_5 { @@ -13,6 +13,34 @@ public class CompletionResult3_5 {
13 private List<CompletionChoice3_5> choices; 13 private List<CompletionChoice3_5> choices;
14 private Usage usage; 14 private Usage usage;
15 15
  16 + private Integer user_id;
  17 + private String room_id;
  18 + private Integer gptMessage_id;
  19 +
  20 + public Integer getGptMessage_id() {
  21 + return gptMessage_id;
  22 + }
  23 +
  24 + public void setGptMessage_id(Integer gptMessage_id) {
  25 + this.gptMessage_id = gptMessage_id;
  26 + }
  27 +
  28 + public Integer getUser_id() {
  29 + return user_id;
  30 + }
  31 +
  32 + public void setUser_id(Integer user_id) {
  33 + this.user_id = user_id;
  34 + }
  35 +
  36 + public String getRoom_id() {
  37 + return room_id;
  38 + }
  39 +
  40 + public void setRoom_id(String room_id) {
  41 + this.room_id = room_id;
  42 + }
  43 +
16 public String getId() { 44 public String getId() {
17 return id; 45 return id;
18 } 46 }
@@ -22,6 +22,7 @@ @@ -22,6 +22,7 @@
22 <module>lh-openai</module> 22 <module>lh-openai</module>
23 <module>lh-log</module> 23 <module>lh-log</module>
24 <module>lh-quartz</module> 24 <module>lh-quartz</module>
  25 + <module>lh-chatgpt-api</module>
25 </modules> 26 </modules>
26 27
27 <packaging>pom</packaging> 28 <packaging>pom</packaging>