gpt4-copilot-java-native v0.1.0

This commit is contained in:
Yanyutin753
2024-03-23 01:00:53 +08:00
parent 99c3664a61
commit f6eabfa759
23 changed files with 365 additions and 244 deletions

View File

@@ -3,8 +3,16 @@
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<Languages> <Languages>
<language minSize="58" name="Java" /> <language minSize="76" name="Java" />
</Languages> </Languages>
</inspection_tool> </inspection_tool>
<inspection_tool class="IncorrectHttpHeaderInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="customHeaders">
<set>
<option value="Editor-Plugin-Version" />
<option value="Editor-Version" />
</set>
</option>
</inspection_tool>
</profile> </profile>
</component> </component>

124
.idea/uiDesigner.xml generated Normal file
View File

@@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@@ -8,7 +8,7 @@ LABEL maintainer="Yanyutin753"
USER root USER root
# 复制JAR文件到容器的/app目录下 # 复制JAR文件到容器的/app目录下
COPY /target/gpt-4-copilot-0.0.7.jar app.jar COPY /target/gpt-4-copilot-0.1.0.jar app.jar
# 声明服务运行在8081端口 # 声明服务运行在8081端口
EXPOSE 8081 EXPOSE 8081

View File

@@ -1,14 +1,14 @@
{ {
"gpt3_sleepTime": 0, "gpt3_sleepTime":0,
"password": "", "password":"",
"get_token_url": "", "get_token_url":"",
"copilot_chat_version": "0.14.2024031401", "copilot_chat_version":"0.14.2024031401",
"prefix": "", "prefix":"",
"one_selfCopilot_limit": 30, "one_selfCopilot_limit":30,
"one_copilot_limit": 30, "one_copilot_limit":30,
"vscode_version": "vscode\/1.85.2", "vscode_version":"vscode/1.85.2",
"serverPort": 8080, "serverPort":8080,
"maxPoolSize": 300, "maxPoolSize":300,
"gpt4_sleepTime": 100, "gpt4_sleepTime":100,
"one_coCopilot_limit": 30 "one_coCopilot_limit":30
} }

24
pom.xml
View File

@@ -10,7 +10,7 @@
</parent> </parent>
<groupId>com.gpt4.copilot</groupId> <groupId>com.gpt4.copilot</groupId>
<artifactId>gpt-4-copilot</artifactId> <artifactId>gpt-4-copilot</artifactId>
<version>0.0.7</version> <version>0.1.0</version>
<name>native</name> <name>native</name>
<description>Demo project for Spring Boot with GraalVM Native Image</description> <description>Demo project for Spring Boot with GraalVM Native Image</description>
<properties> <properties>
@@ -32,16 +32,6 @@
<artifactId>micrometer-registry-prometheus</artifactId> <artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.rednoise</groupId>
<artifactId>rita</artifactId>
<version>2.4.501</version>
</dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
@@ -58,16 +48,6 @@
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
</dependency> </dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -82,7 +62,7 @@
<configuration> <configuration>
<excludes> <excludes>
<exclude> <exclude>
<groupId>org.projectlombok</groupId> <groupId>org.project-lombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</exclude> </exclude>
</excludes> </excludes>

View File

@@ -1,12 +1,13 @@
package com.gpt4.copilot; package com.gpt4.copilot;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.gpt4.copilot.controller.ChatController; import com.gpt4.copilot.controller.ChatController;
import com.gpt4.copilot.pojo.SystemSetting; import com.gpt4.copilot.pojo.SystemSetting;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
@@ -30,7 +31,7 @@ import java.nio.file.Paths;
@Slf4j @Slf4j
@EnableScheduling @EnableScheduling
@SpringBootApplication @SpringBootApplication
public class copilotApplication { public class CopilotApplication {
private static final String VS_CODE_API_URL = "https://api.github.com/repos/microsoft/vscode/releases/latest"; private static final String VS_CODE_API_URL = "https://api.github.com/repos/microsoft/vscode/releases/latest";
private static final String VS_CODE_CHAT_URL = "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery"; private static final String VS_CODE_CHAT_URL = "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery";
@@ -38,7 +39,7 @@ public class copilotApplication {
String configFilePath = System.getProperty("user.dir") + File.separator + "config.json"; String configFilePath = System.getProperty("user.dir") + File.separator + "config.json";
SystemSetting config = loadConfig(configFilePath); SystemSetting config = loadConfig(configFilePath);
setSystemProperties(config); setSystemProperties(config);
SpringApplication.run(copilotApplication.class, args); SpringApplication.run(CopilotApplication.class, args);
printStartupMessage(config); printStartupMessage(config);
} }
@@ -65,8 +66,8 @@ public class copilotApplication {
private static JSONObject readJsonFile(String configFilePath) { private static JSONObject readJsonFile(String configFilePath) {
try { try {
String jsonContent = new String(Files.readAllBytes(Paths.get(configFilePath))); String jsonContent = new String(Files.readAllBytes(Paths.get(configFilePath)));
return new JSONObject(jsonContent); return JSON.parseObject(jsonContent);
} catch (IOException | JSONException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@@ -76,11 +77,9 @@ public class copilotApplication {
SystemSetting config = new SystemSetting(); SystemSetting config = new SystemSetting();
config.setServerPort(getIntOrDefault(jsonObject, "serverPort", 8080)); config.setServerPort(getIntOrDefault(jsonObject, "serverPort", 8080));
config.setPrefix(getStringOrDefault(jsonObject, "prefix", "/")); config.setPrefix(getStringOrDefault(jsonObject, "prefix", "/"));
String updatedJson = jsonObject.toString(2); String updatedJson = com.alibaba.fastjson.JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
Files.write(Paths.get(configFilePath), updatedJson.getBytes()); Files.write(Paths.get(configFilePath), updatedJson.getBytes());
return config; return config;
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -88,11 +87,11 @@ public class copilotApplication {
private static int getIntOrDefault(JSONObject jsonObject, String key, int defaultValue) { private static int getIntOrDefault(JSONObject jsonObject, String key, int defaultValue) {
try { try {
if (!jsonObject.has(key)) { if (!jsonObject.containsKey(key)) {
jsonObject.put(key, defaultValue); jsonObject.put(key, defaultValue);
log.info("config.json没有新增" + key + "参数,现已增加!"); log.info("config.json没有新增" + key + "参数,现已增加!");
} }
return jsonObject.getInt(key); return jsonObject.getIntValue(key);
} catch (JSONException e) { } catch (JSONException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -100,7 +99,7 @@ public class copilotApplication {
private static String getStringOrDefault(JSONObject jsonObject, String key, String defaultValue) { private static String getStringOrDefault(JSONObject jsonObject, String key, String defaultValue) {
try { try {
if (!jsonObject.has(key)) { if (!jsonObject.containsKey(key)) {
jsonObject.put(key, defaultValue); jsonObject.put(key, defaultValue);
log.info("config.json没有新增" + key + "参数,现已增加!"); log.info("config.json没有新增" + key + "参数,现已增加!");
} }
@@ -124,21 +123,18 @@ public class copilotApplication {
if (conn.getResponseCode() != 200) { if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
} }
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuilder response = new StringBuilder(); StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) { try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
response.append(output); String output;
while ((output = br.readLine()) != null) {
response.append(output);
}
} }
conn.disconnect(); conn.disconnect();
JSONObject jsonObject = new JSONObject(response.toString()); com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(response.toString());
return jsonObject.getString("tag_name"); return jsonObject.getString("tag_name");
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (RuntimeException e) {
throw new RuntimeException(e);
} catch (JSONException e) {
throw new RuntimeException(e);
} }
} }
@@ -149,9 +145,7 @@ public class copilotApplication {
conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json;api-version=6.1-preview.1"); conn.setRequestProperty("Accept", "application/json;api-version=6.1-preview.1");
conn.setDoOutput(true); conn.setDoOutput(true);
JSONObject jsonRequest = new JSONObject(); com.alibaba.fastjson.JSONObject jsonRequest = getJsonObject(publisher, name);
jsonRequest.put("filters", new JSONArray().put(new JSONObject().put("criteria", new JSONArray().put(new JSONObject().put("filterType", 7).put("value", publisher + "." + name)))));
jsonRequest.put("flags", 870);
OutputStream os = conn.getOutputStream(); OutputStream os = conn.getOutputStream();
os.write(jsonRequest.toString().getBytes()); os.write(jsonRequest.toString().getBytes());
os.flush(); os.flush();
@@ -162,15 +156,36 @@ public class copilotApplication {
response.append(output); response.append(output);
} }
conn.disconnect(); conn.disconnect();
JSONObject jsonResponse = new JSONObject(response.toString()); com.alibaba.fastjson2.JSONObject jsonResponse = JSON.parseObject(response.toString());
return jsonResponse.getJSONArray("results").getJSONObject(0).getJSONArray("extensions").getJSONObject(0).getJSONArray("versions").getJSONObject(0).getString("version"); return jsonResponse.getJSONArray("results").getJSONObject(0).getJSONArray("extensions").getJSONObject(0).getJSONArray("versions").getJSONObject(0).getString("version");
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (JSONException e) {
throw new RuntimeException(e);
} }
} }
private static com.alibaba.fastjson.JSONObject getJsonObject(String publisher, String name) {
com.alibaba.fastjson.JSONObject jsonRequest = new com.alibaba.fastjson.JSONObject();
jsonRequest.put("flags", 870);
com.alibaba.fastjson.JSONArray filtersArray = new com.alibaba.fastjson.JSONArray();
com.alibaba.fastjson.JSONObject criteriaObject = new com.alibaba.fastjson.JSONObject();
criteriaObject.put("filterType", 7);
criteriaObject.put("value", publisher + "." + name);
com.alibaba.fastjson.JSONArray criteriaArray = new com.alibaba.fastjson.JSONArray();
criteriaArray.add(criteriaObject);
com.alibaba.fastjson.JSONObject filterObject = new com.alibaba.fastjson.JSONObject();
filterObject.put("criteria", criteriaArray);
filtersArray.add(filterObject);
jsonRequest.put("filters", filtersArray);
return jsonRequest;
}
@Scheduled(cron = "0 0 3 1/3 * ?") @Scheduled(cron = "0 0 3 1/3 * ?")
private static void updateLatestVersion() { private static void updateLatestVersion() {
try { try {
@@ -183,11 +198,10 @@ public class copilotApplication {
String parent = ChatController.selectFile(); String parent = ChatController.selectFile();
// 读取 JSON 文件内容 // 读取 JSON 文件内容
String jsonContent = new String(Files.readAllBytes(Paths.get(parent))); String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
JSONObject jsonObject = new JSONObject(jsonContent); JSONObject jsonObject = JSON.parseObject(jsonContent);
jsonObject.put("vscode_version", latestVersion); jsonObject.put("vscode_version", latestVersion);
jsonObject.put("copilot_chat_version", latestChatVersion); jsonObject.put("copilot_chat_version", latestChatVersion);
// 将修改后的 JSONObject 转换为格式化的 JSON 字符串 String updatedJson = com.alibaba.fastjson.JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
String updatedJson = jsonObject.toString(2);
Files.write(Paths.get(parent), updatedJson.getBytes()); Files.write(Paths.get(parent), updatedJson.getBytes());
System.out.println("===================配置更新说明========================"); System.out.println("===================配置更新说明========================");
System.out.println("vscode_version" + ChatController.getVscode_version()); System.out.println("vscode_version" + ChatController.getVscode_version());
@@ -206,18 +220,19 @@ public class copilotApplication {
System.out.println("maxPoolSize" + ChatController.getMaxPoolSize()); System.out.println("maxPoolSize" + ChatController.getMaxPoolSize());
System.out.println("gpt3_sleepTime" + ChatController.getGpt3_sleepTime()); System.out.println("gpt3_sleepTime" + ChatController.getGpt3_sleepTime());
System.out.println("gpt4_sleepTime" + ChatController.getGpt4_sleepTime()); System.out.println("gpt4_sleepTime" + ChatController.getGpt4_sleepTime());
System.out.println("vscode_version" + ChatController.getVscode_version()); System.out.println("vscode_version" + getLatestVSCodeVersion());
System.out.println("copilot_chat_version" + ChatController.getCopilot_chat_version()); System.out.println("copilot_chat_version" + getLatestExtensionVersion("GitHub", "copilot-chat"));
System.out.println("get_token_url" + ChatController.getGet_token_url()); System.out.println("get_token_url" + ChatController.getGet_token_url());
System.out.println("one_copilot_limit" + ChatController.getOne_copilot_limit()); System.out.println("one_copilot_limit" + ChatController.getOne_copilot_limit());
System.out.println("one_coCopilot_limit" + ChatController.getOne_coCopilot_limit()); System.out.println("one_coCopilot_limit" + ChatController.getOne_coCopilot_limit());
System.out.println("one_selfCopilot_limit" + ChatController.getOne_selfCopilot_limit()); System.out.println("one_selfCopilot_limit" + ChatController.getOne_selfCopilot_limit());
System.out.println("gpt4-copilot-java 初始化接口成功!"); System.out.println("gpt4-copilot-java 初始化接口成功!");
System.out.println("======================================================"); System.out.println("======================================================");
System.out.println("******原神gpt4-copilot-java-native v0.0.7启动成功******"); System.out.println("******原神gpt4-copilot-java-native v0.1.0启动成功******");
System.out.println("* 采用graalvm打包运行内存大幅度减小"); System.out.println("* 采用graalvm打包运行内存大幅度减小");
System.out.println("* 适配官方requestBody,减小被查询异常"); System.out.println("* 适配官方requestBody,减小被查询异常");
System.out.println("* 使用ConcurrentHashMap粗略的对于每个密钥按每分钟进行限速"); System.out.println("* 使用ConcurrentHashMap粗略的对于每个密钥按每分钟进行限速");
System.out.println("* 修复部分bug提升稳定性");
System.out.println("URL地址http://0.0.0.0:" + config.getServerPort() + config.getPrefix() + ""); System.out.println("URL地址http://0.0.0.0:" + config.getServerPort() + config.getPrefix() + "");
System.out.println("======================================================"); System.out.println("======================================================");
} }

View File

@@ -1,8 +1,11 @@
package com.gpt4.copilot.controller; package com.gpt4.copilot.controller;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.gpt4.copilot.copilotApplication; import com.gpt4.copilot.CopilotApplication;
import com.gpt4.copilot.pojo.Conversation; import com.gpt4.copilot.pojo.Conversation;
import com.gpt4.copilot.pojo.Result; import com.gpt4.copilot.pojo.Result;
import com.gpt4.copilot.pojo.SystemSetting; import com.gpt4.copilot.pojo.SystemSetting;
@@ -11,9 +14,7 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
@@ -44,18 +45,19 @@ import java.util.concurrent.atomic.AtomicInteger;
@Data @Data
@RestController() @RestController()
public class ChatController { public class ChatController {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
/** /**
* 缓存cocopilotToken * 缓存cocopilotToken
*/ */
private static final HashMap<String, String> copilotTokenList; private static final ConcurrentHashMap<String, String> copilotTokenList;
/** /**
* 缓存copilotToken * 缓存copilotToken
*/ */
private static final HashMap<String, String> coCopilotTokenList; private static final ConcurrentHashMap<String, String> coCopilotTokenList;
/** /**
* 缓存selfToken * 缓存selfToken
*/ */
private static final HashMap<String, String> selfTokenList; private static final ConcurrentHashMap<String, String> selfTokenList;
/** /**
* 缓存cocopilotToken_limit * 缓存cocopilotToken_limit
*/ */
@@ -124,6 +126,62 @@ public class ChatController {
* one copilot_token max requests per minute * one copilot_token max requests per minute
*/ */
private static Integer one_copilot_limit; private static Integer one_copilot_limit;
/**
* one coCopilot_token max requests per minute
*/
private static Integer one_coCopilot_limit;
/**
* one selfCopilot_token max requests per minute
*/
private static Integer one_selfCopilot_limit;
/**
* 定义okhttp库
*/
private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.MINUTES)
.readTimeout(6, TimeUnit.MINUTES)
.writeTimeout(6, TimeUnit.MINUTES)
.build();
/**
* 定义线程池里的线程名字
*/
private static ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "chatThreadPool-" + counter.getAndIncrement());
}
};
/**
* 定义线程池
*/
private static ExecutorService executor;
/**
* 初始化ChatController类
*/
static {
selfTokenList = new ConcurrentHashMap<>();
copilotTokenList = new ConcurrentHashMap<>();
coCopilotTokenList = new ConcurrentHashMap<>();
selfTokenLimitList = new ConcurrentHashMap<>();
copilotTokenLimitList = new ConcurrentHashMap<>();
coCopilotTokenLimitList = new ConcurrentHashMap<>();
machineId = generateMachineId();
SystemSetting systemSetting = selectSetting();
setGpt4_sleepTime(systemSetting.getGpt4_sleepTime());
setGpt3_sleepTime(systemSetting.getGpt3_sleepTime());
setPassword(systemSetting.getPassword());
setGet_token_url(systemSetting.getGet_token_url());
setVscode_version(systemSetting.getVscode_version());
setCopilot_chat_version(systemSetting.getCopilot_chat_version());
setMaxPoolSize(systemSetting.getMaxPoolSize());
setExecutor(systemSetting.getMaxPoolSize());
setOne_copilot_limit(systemSetting.getOne_copilot_limit());
setOne_coCopilot_limit(systemSetting.getOne_coCopilot_limit());
setOne_selfCopilot_limit(systemSetting.getOne_selfCopilot_limit());
}
public static Integer getOne_copilot_limit() { public static Integer getOne_copilot_limit() {
return one_copilot_limit; return one_copilot_limit;
@@ -149,66 +207,6 @@ public class ChatController {
ChatController.one_selfCopilot_limit = one_selfCopilot_limit; ChatController.one_selfCopilot_limit = one_selfCopilot_limit;
} }
/**
* one coCopilot_token max requests per minute
*/
private static Integer one_coCopilot_limit;
/**
* one selfCopilot_token max requests per minute
*/
private static Integer one_selfCopilot_limit;
/**
* 定义okhttp库
*/
private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.build();
/**
* 定义线程池里的线程名字
*/
private static ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "chatThreadPool-" + counter.getAndIncrement());
}
};
/**
* 定义线程池
*/
private static ExecutorService executor;
/**
* 初始化ChatController类
*/
static {
selfTokenList = new HashMap<>();
copilotTokenList = new HashMap<>();
coCopilotTokenList = new HashMap<>();
selfTokenLimitList = new ConcurrentHashMap<>();
copilotTokenLimitList = new ConcurrentHashMap<>();
coCopilotTokenLimitList = new ConcurrentHashMap<>();
machineId = generateMachineId();
SystemSetting systemSetting = selectSetting();
setGpt4_sleepTime(systemSetting.getGpt4_sleepTime());
setGpt3_sleepTime(systemSetting.getGpt3_sleepTime());
setPassword(systemSetting.getPassword());
setGet_token_url(systemSetting.getGet_token_url());
setVscode_version(systemSetting.getVscode_version());
setCopilot_chat_version(systemSetting.getCopilot_chat_version());
setMaxPoolSize(systemSetting.getMaxPoolSize());
setExecutor(systemSetting.getMaxPoolSize());
setOne_copilot_limit(systemSetting.getOne_copilot_limit());
setOne_coCopilot_limit(systemSetting.getOne_coCopilot_limit());
setOne_selfCopilot_limit(systemSetting.getOne_selfCopilot_limit());
}
public static String getCopilot_chat_version() { public static String getCopilot_chat_version() {
return copilot_chat_version; return copilot_chat_version;
} }
@@ -269,8 +267,6 @@ public class ChatController {
ChatController.get_token_url = get_token_url; ChatController.get_token_url = get_token_url;
} }
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
/** /**
* 初始化获取环境变量 * 初始化获取环境变量
*/ */
@@ -307,10 +303,10 @@ public class ChatController {
// 读取 JSON 文件内容 // 读取 JSON 文件内容
String jsonContent = new String(Files.readAllBytes(Paths.get(parent))); String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
// 将 JSON 字符串解析为 JSONObject // 将 JSON 字符串解析为 JSONObject
JSONObject jsonObject = new JSONObject(jsonContent); JSONObject jsonObject = com.alibaba.fastjson2.JSON.parseObject(jsonContent);
try { try {
jsonObject.getString("password"); jsonObject.getString("password");
} catch (JSONException e) { } catch ( JSONException e) {
jsonObject.put("password", UUID.randomUUID().toString()); jsonObject.put("password", UUID.randomUUID().toString());
log.info("config.json没有新增password参数,现已增加!"); log.info("config.json没有新增password参数,现已增加!");
exist = false; exist = false;
@@ -323,14 +319,14 @@ public class ChatController {
exist = false; exist = false;
} }
try { try {
jsonObject.getInt("gpt4_sleepTime"); jsonObject.getInteger("gpt4_sleepTime");
} catch (JSONException e) { } catch (JSONException e) {
jsonObject.put("gpt4_sleepTime", "100"); jsonObject.put("gpt4_sleepTime", "100");
log.info("config.json没有新增gpt4_sleepTime参数,现已增加!"); log.info("config.json没有新增gpt4_sleepTime参数,现已增加!");
exist = false; exist = false;
} }
try { try {
jsonObject.getInt("maxPoolSize"); jsonObject.getInteger("maxPoolSize");
} catch (JSONException e) { } catch (JSONException e) {
jsonObject.put("maxPoolSize", 300); jsonObject.put("maxPoolSize", 300);
log.info("config.json没有新增maxPoolSize参数,现已增加!"); log.info("config.json没有新增maxPoolSize参数,现已增加!");
@@ -340,7 +336,7 @@ public class ChatController {
try { try {
jsonObject.getString("vscode_version"); jsonObject.getString("vscode_version");
} catch (JSONException e) { } catch (JSONException e) {
String latestVSCodeVersion = copilotApplication.getLatestVSCodeVersion(); String latestVSCodeVersion = CopilotApplication.getLatestVSCodeVersion();
if (latestVSCodeVersion != null) { if (latestVSCodeVersion != null) {
jsonObject.put("vscode_version", latestVSCodeVersion); jsonObject.put("vscode_version", latestVSCodeVersion);
log.info("config.json没有新增vscode_version参数,现已增加!"); log.info("config.json没有新增vscode_version参数,现已增加!");
@@ -351,7 +347,7 @@ public class ChatController {
try { try {
jsonObject.getString("copilot_chat_version"); jsonObject.getString("copilot_chat_version");
} catch (JSONException e) { } catch (JSONException e) {
String latestChatVersion = copilotApplication.getLatestExtensionVersion("GitHub", "copilot-chat"); String latestChatVersion = CopilotApplication.getLatestExtensionVersion("GitHub", "copilot-chat");
if (latestChatVersion != null) { if (latestChatVersion != null) {
jsonObject.put("copilot_chat_version", latestChatVersion); jsonObject.put("copilot_chat_version", latestChatVersion);
log.info("config.json没有新增copilot_chat_version参数,现已增加!"); log.info("config.json没有新增copilot_chat_version参数,现已增加!");
@@ -392,20 +388,20 @@ public class ChatController {
} }
// 将 JSONObject 转换为 Config 类的实例 // 将 JSONObject 转换为 Config 类的实例
SystemSetting config = new SystemSetting(); SystemSetting config = new SystemSetting();
config.setPassword(jsonObject.optString("password")); config.setPassword(jsonObject.getString("password"));
config.setMaxPoolSize(jsonObject.optInt("maxPoolSize")); config.setMaxPoolSize(jsonObject.getIntValue("maxPoolSize"));
config.setGpt3_sleepTime(jsonObject.optInt("gpt3_sleepTime")); config.setGpt3_sleepTime(jsonObject.getIntValue("gpt3_sleepTime"));
config.setGpt4_sleepTime(jsonObject.optInt("gpt4_sleepTime")); config.setGpt4_sleepTime(jsonObject.getIntValue("gpt4_sleepTime"));
config.setVscode_version(jsonObject.optString("vscode_version")); config.setVscode_version(jsonObject.getString("vscode_version"));
config.setCopilot_chat_version(jsonObject.optString("copilot_chat_version")); config.setCopilot_chat_version(jsonObject.getString("copilot_chat_version"));
config.setGet_token_url(jsonObject.optString("get_token_url")); config.setGet_token_url(jsonObject.getString("get_token_url"));
config.setOne_copilot_limit(jsonObject.optInt("one_copilot_limit")); config.setOne_copilot_limit(jsonObject.getIntValue("one_copilot_limit"));
config.setOne_coCopilot_limit(jsonObject.optInt("one_coCopilot_limit")); config.setOne_coCopilot_limit(jsonObject.getIntValue("one_coCopilot_limit"));
config.setOne_selfCopilot_limit(jsonObject.optInt("one_selfCopilot_limit")); config.setOne_selfCopilot_limit(jsonObject.getIntValue("one_selfCopilot_limit"));
if (exist == false) { if (!exist) {
// 将修改后的 JSONObject 转换为格式化的 JSON 字符串 // 将修改后的 JSONObject 转换为格式化的 JSON 字符串
String updatedJson = jsonObject.toString(2); String updatedJson = com.alibaba.fastjson.JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
Files.write(Paths.get(parent), updatedJson.getBytes()); Files.write(Paths.get(parent), updatedJson.getBytes());
} }
return config; return config;
@@ -415,15 +411,6 @@ public class ChatController {
return null; return null;
} }
@Scheduled(cron = "0 */1 * * * ?")
public void resetLimit() {
ExecutorService updateExecutor = Executors.newFixedThreadPool(3);
updateExecutor.submit(() -> copilotTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.submit(() -> coCopilotTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.submit(() -> selfTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.shutdown();
}
private static String generateMachineId() { private static String generateMachineId() {
try { try {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
@@ -443,6 +430,15 @@ public class ChatController {
} }
} }
@Scheduled(cron = "0 */1 * * * ?")
public void resetLimit() {
ExecutorService updateExecutor = Executors.newFixedThreadPool(3);
updateExecutor.submit(() -> copilotTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.submit(() -> coCopilotTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.submit(() -> selfTokenLimitList.replaceAll((k, v) -> new AtomicInteger(0)));
updateExecutor.shutdown();
}
/** /**
* 修改sleep时间 * 修改sleep时间
*/ */
@@ -456,7 +452,7 @@ public class ChatController {
String parent = selectFile(); String parent = selectFile();
// 读取 JSON 文件内容 // 读取 JSON 文件内容
String jsonContent = new String(Files.readAllBytes(Paths.get(parent))); String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
JSONObject jsonObject = new JSONObject(jsonContent); JSONObject jsonObject = com.alibaba.fastjson2.JSON.parseObject(jsonContent);
if (gpt3_sleepTime != null && gpt4_sleepTime >= 0 && gpt4_sleepTime <= 150) { if (gpt3_sleepTime != null && gpt4_sleepTime >= 0 && gpt4_sleepTime <= 150) {
setGpt3_sleepTime(gpt3_sleepTime); setGpt3_sleepTime(gpt3_sleepTime);
jsonObject.put("gpt3_sleepTime", gpt3_sleepTime); jsonObject.put("gpt3_sleepTime", gpt3_sleepTime);
@@ -470,7 +466,7 @@ public class ChatController {
jsonObject.put("get_token_url", get_token_url); jsonObject.put("get_token_url", get_token_url);
} }
// 将修改后的 JSONObject 转换为格式化的 JSON 字符串 // 将修改后的 JSONObject 转换为格式化的 JSON 字符串
String updatedJson = jsonObject.toString(2); String updatedJson = com.alibaba.fastjson.JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat);
Path path = Paths.get(parent); Path path = Paths.get(parent);
Files.write(path, updatedJson.getBytes()); Files.write(path, updatedJson.getBytes());
return Result.success("修改成功!"); return Result.success("修改成功!");
@@ -495,7 +491,8 @@ public class ChatController {
*/ */
@PostMapping(value = "/copilot_internal/v2/token") @PostMapping(value = "/copilot_internal/v2/token")
public ResponseEntity<Object> getV2Token(HttpServletResponse response, HttpServletRequest request) { public ResponseEntity<Object> getV2Token(HttpServletResponse response, HttpServletRequest request) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
String apiKey; String apiKey;
@@ -562,7 +559,8 @@ public class ChatController {
public ResponseEntity<Object> coPilotConversation(HttpServletResponse response, public ResponseEntity<Object> coPilotConversation(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -583,11 +581,10 @@ public class ChatController {
copilotTokenLimitList.putIfAbsent(apiKey, new AtomicInteger(1)); copilotTokenLimitList.putIfAbsent(apiKey, new AtomicInteger(1));
copilotTokenList.put(apiKey, token); copilotTokenList.put(apiKey, token);
log.info("Github CopilotToken初始化成功"); log.info("Github CopilotToken初始化成功");
} } else {
else {
int requestNum = copilotTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = copilotTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_copilot_limit){ if (requestNum > one_copilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
// 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions // 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions
@@ -624,18 +621,7 @@ public class ChatController {
return null; return null;
}, executor); }, executor);
ResponseEntity<Object> responseEntity; return getObjectResponseEntity(response, future);
try {
responseEntity = future.get(6, TimeUnit.MINUTES);
} catch (TimeoutException ex) {
future.cancel(true);
responseEntity = new ResponseEntity<>(Result.error("The task timed out"), HttpStatus.REQUEST_TIMEOUT);
} catch (Exception ex) {
log.error(ex.getMessage());
responseEntity = new ResponseEntity<>(Result.error("An error occurred"), HttpStatus.INTERNAL_SERVER_ERROR);
}
return responseEntity;
} }
@@ -656,7 +642,8 @@ public class ChatController {
public ResponseEntity<Object> coCoPilotConversation(HttpServletResponse response, public ResponseEntity<Object> coCoPilotConversation(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -677,11 +664,10 @@ public class ChatController {
coCopilotTokenLimitList.put(apiKey, new AtomicInteger(1)); coCopilotTokenLimitList.put(apiKey, new AtomicInteger(1));
coCopilotTokenList.put(apiKey, token); coCopilotTokenList.put(apiKey, token);
log.info("coCopilotToken初始化成功"); log.info("coCopilotToken初始化成功");
} } else {
else {
int requestNum = coCopilotTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = coCopilotTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_coCopilot_limit){ if (requestNum > one_coCopilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
// 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions // 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions
@@ -718,14 +704,32 @@ public class ChatController {
return null; return null;
}, executor); }, executor);
return getObjectResponseEntity(future); return getObjectResponseEntity(response, future);
}
private ResponseEntity<Object> getObjectResponseEntity(HttpServletResponse response, CompletableFuture<ResponseEntity<Object>> future) {
ResponseEntity<Object> responseEntity;
try {
responseEntity = future.get(6, TimeUnit.MINUTES);
} catch (TimeoutException ex) {
response.setContentType("application/json; charset=utf-8");
future.cancel(true);
responseEntity = new ResponseEntity<>(Result.error("The Chat timed out"), HttpStatus.REQUEST_TIMEOUT);
} catch (Exception ex) {
response.setContentType("application/json; charset=utf-8");
log.error(ex.getMessage());
responseEntity = new ResponseEntity<>(Result.error("An error occurred"), HttpStatus.INTERNAL_SERVER_ERROR);
}
return responseEntity;
} }
@PostMapping(value = "/self/v1/chat/completions") @PostMapping(value = "/self/v1/chat/completions")
public ResponseEntity<Object> selfConversation(HttpServletResponse response, public ResponseEntity<Object> selfConversation(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -744,13 +748,12 @@ public class ChatController {
return new ResponseEntity<>(Result.error("自定义self APIKey is wrong"), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(Result.error("自定义self APIKey is wrong"), HttpStatus.UNAUTHORIZED);
} }
selfTokenList.put(apiKey, token); selfTokenList.put(apiKey, token);
selfTokenLimitList.put(apiKey,new AtomicInteger(1)); selfTokenLimitList.put(apiKey, new AtomicInteger(1));
log.info("自定义selfToken初始化成功"); log.info("自定义selfToken初始化成功");
} } else {
else {
int requestNum = selfTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = selfTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_selfCopilot_limit){ if (requestNum > one_selfCopilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
// 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions // 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions
@@ -787,7 +790,7 @@ public class ChatController {
return null; return null;
}, executor); }, executor);
return getObjectResponseEntity(future); return getObjectResponseEntity(response, future);
} }
@@ -843,7 +846,8 @@ public class ChatController {
public ResponseEntity<Object> coPilotEmbeddings(HttpServletResponse response, public ResponseEntity<Object> coPilotEmbeddings(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -864,11 +868,10 @@ public class ChatController {
copilotTokenLimitList.put(apiKey, new AtomicInteger(1)); copilotTokenLimitList.put(apiKey, new AtomicInteger(1));
copilotTokenList.put(apiKey, token); copilotTokenList.put(apiKey, token);
log.info("Github CopilotToken初始化成功"); log.info("Github CopilotToken初始化成功");
} } else {
else {
int requestNum = copilotTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = copilotTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_copilot_limit){ if (requestNum > one_copilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
// 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions // 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions
@@ -941,7 +944,8 @@ public class ChatController {
public ResponseEntity<Object> coCoPilotEmbeddings(HttpServletResponse response, public ResponseEntity<Object> coCoPilotEmbeddings(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -962,11 +966,10 @@ public class ChatController {
coCopilotTokenLimitList.put(apiKey, new AtomicInteger(1)); coCopilotTokenLimitList.put(apiKey, new AtomicInteger(1));
coCopilotTokenList.put(apiKey, token); coCopilotTokenList.put(apiKey, token);
log.info("coCopilotToken初始化成功"); log.info("coCopilotToken初始化成功");
} } else {
else {
int requestNum = coCopilotTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = coCopilotTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_coCopilot_limit){ if (requestNum > one_coCopilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
// 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions // 创建OkHttpClient请求 请求https://api.githubcopilot.com/chat/completions
@@ -1024,7 +1027,8 @@ public class ChatController {
public ResponseEntity<Object> selfEmbeddings(HttpServletResponse response, public ResponseEntity<Object> selfEmbeddings(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
@org.springframework.web.bind.annotation.RequestBody Conversation conversation) { @org.springframework.web.bind.annotation.RequestBody Conversation conversation) {
String authorizationHeader = StringUtils.trimToNull(request.getHeader("Authorization")); String header = request.getHeader("Authorization");
String authorizationHeader = (header != null && !header.trim().isEmpty()) ? header.trim() : null;
// 异步处理 // 异步处理
CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> { CompletableFuture<ResponseEntity<Object>> future = CompletableFuture.supplyAsync(() -> {
try { try {
@@ -1042,14 +1046,13 @@ public class ChatController {
if (token == null) { if (token == null) {
return new ResponseEntity<>(Result.error("自定义APIKey is wrong"), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(Result.error("自定义APIKey is wrong"), HttpStatus.UNAUTHORIZED);
} }
selfTokenLimitList.put(apiKey,new AtomicInteger(1)); selfTokenLimitList.put(apiKey, new AtomicInteger(1));
selfTokenList.put(apiKey, token); selfTokenList.put(apiKey, token);
log.info("自定义selfToken初始化成功"); log.info("自定义selfToken初始化成功");
} } else {
else {
int requestNum = selfTokenLimitList.get(apiKey).incrementAndGet(); int requestNum = selfTokenLimitList.get(apiKey).incrementAndGet();
if(requestNum > one_selfCopilot_limit){ if (requestNum > one_selfCopilot_limit) {
return new ResponseEntity<>(Result.error("current requests is "+ requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS); return new ResponseEntity<>(Result.error("current requests is " + requestNum + " rate limit exceeded"), HttpStatus.TOO_MANY_REQUESTS);
} }
} }
String chat_token = selfTokenList.get(apiKey); String chat_token = selfTokenList.get(apiKey);
@@ -1127,14 +1130,19 @@ public class ChatController {
.addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version) .addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version)
.addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version) .addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version)
.addHeader("Accept", "*/*").build(); .addHeader("Accept", "*/*").build();
return getToken(request);
}
@Nullable
private String getToken(Request request) throws IOException {
try (Response response = client.newCall(request).execute()) { try (Response response = client.newCall(request).execute()) {
log.info(response.toString()); log.info(response.toString());
if (!response.isSuccessful()) { if (!response.isSuccessful()) {
return null; return null;
} }
String responseBody = response.body().string(); String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody); JSONObject jsonResponse = com.alibaba.fastjson2.JSON.parseObject(responseBody);
return jsonResponse.has("token") ? jsonResponse.get("token").toString() : null; return jsonResponse.getString("token");
} catch (JSONException e) { } catch (JSONException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -1154,17 +1162,7 @@ public class ChatController {
.addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version) .addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version)
.addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version) .addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version)
.addHeader("Accept", "*/*").build(); .addHeader("Accept", "*/*").build();
try (Response response = client.newCall(request).execute()) { return getToken(request);
log.info(response.toString());
if (!response.isSuccessful()) {
return null;
}
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
return jsonResponse.has("token") ? jsonResponse.get("token").toString() : null;
} catch (JSONException e) {
throw new RuntimeException(e);
}
} }
/** /**
@@ -1181,17 +1179,7 @@ public class ChatController {
.addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version) .addHeader("Editor-Plugin-Version", "copilot-chat/" + copilot_chat_version)
.addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version) .addHeader("User-Agent", "GitHubCopilotChat/" + copilot_chat_version)
.addHeader("Accept", "*/*").build(); .addHeader("Accept", "*/*").build();
try (Response response = client.newCall(request).execute()) { return getToken(request);
log.info(response.toString());
if (!response.isSuccessful()) {
return null;
}
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
return jsonResponse.has("token") ? jsonResponse.get("token").toString() : null;
} catch (JSONException e) {
throw new RuntimeException(e);
}
} }

View File

@@ -25,7 +25,7 @@ public class CustomErrorController implements ErrorController {
" <title>Document</title>\n" + " <title>Document</title>\n" +
"</head>\n" + "</head>\n" +
"<body>\n" + "<body>\n" +
" <p>Thanks you use gpt4-copilot-java-0.0.5</p>\n" + " <p>Thanks you use gpt4-copilot-java-0.1.0</p>\n" +
" <p><a href=\"https://apifox.com/apidoc/shared-4301e565-a8df-48a0-85a5-bda2c4c3965a\">详细使用文档</a></p>\n" + " <p><a href=\"https://apifox.com/apidoc/shared-4301e565-a8df-48a0-85a5-bda2c4c3965a\">详细使用文档</a></p>\n" +
" <p><a href=\"https://github.com/Yanyutin753/gpt4-copilot-java-sh\">项目地址</a></p>\n" + " <p><a href=\"https://github.com/Yanyutin753/gpt4-copilot-java-sh\">项目地址</a></p>\n" +
"</body>\n" + "</body>\n" +

View File

@@ -8,6 +8,9 @@ import lombok.NoArgsConstructor;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/**
* @author YANGYANG
*/
@Data @Data
@Builder @Builder
@AllArgsConstructor @AllArgsConstructor

View File

@@ -4,6 +4,9 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
/**
* @author YANGYANG
*/
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor

Binary file not shown.

View File

@@ -1,3 +1,3 @@
artifactId=gpt-4-copilot artifactId=gpt-4-copilot
groupId=com.gpt4.copilot groupId=com.gpt4.copilot
version=0.0.7 version=0.1.0

View File

@@ -7,4 +7,4 @@ com\gpt4\copilot\pojo\Conversation.class
com\gpt4\copilot\pojo\SystemSetting.class com\gpt4\copilot\pojo\SystemSetting.class
com\gpt4\copilot\config\CorsConfig.class com\gpt4\copilot\config\CorsConfig.class
com\gpt4\copilot\pojo\Result.class com\gpt4\copilot\pojo\Result.class
com\gpt4\copilot\copilotApplication.class com\gpt4\copilot\CopilotApplication.class

View File

@@ -5,4 +5,4 @@ F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\
F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\pojo\SystemSetting.java F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\pojo\SystemSetting.java
F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\controller\ChatController.java F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\controller\ChatController.java
F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\config\WebConfig.java F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\config\WebConfig.java
F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\copilotApplication.java F:\vue\fakeApiTool\graalvm-demos\spring-native-image\GPT4-Copilot\src\main\java\com\gpt4\copilot\CopilotApplication.java