使用指南
maven
<dependency><groupId>com.github.plexpt</groupId><artifactId>chatgpt</artifactId><version>4.0.1</version>
</dependency>
简单使用
//国内需要代理Proxy proxy = Proxys.http("127.0.0.1", 1080);ChatGPT chatGPT = ChatGPT.builder().apiKey("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").proxy(proxy).apiHost("https://api.openai.com/") //反向代理地址.build().init();String res = chatGPT.chat("写一段七言绝句诗,题目是:火锅!");System.out.println(res);
进阶使用
//国内需要代理 国外不需要Proxy proxy = Proxys.http("127.0.0.1", 1080);ChatGPT chatGPT = ChatGPT.builder().apiKey("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").proxy(proxy).timeout(900).apiHost("https://api.openai.com/") //反向代理地址.build().init();Message system = Message.ofSystem("你现在是一个诗人,专门写七言绝句");Message message = Message.of("写一段七言绝句诗,题目是:火锅!");ChatCompletion chatCompletion = ChatCompletion.builder().model(ChatCompletion.Model.GPT_3_5_TURBO.getName()).messages(Arrays.asList(system, message)).maxTokens(3000).temperature(0.9).build();ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);Message res = response.getChoices().get(0).getMessage();System.out.println(res);
流式使用
//国内需要代理 国外不需要Proxy proxy = Proxys.http("127.0.0.1", 1080);ChatGPTStream chatGPTStream = ChatGPTStream.builder().timeout(600).apiKey("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").proxy(proxy).apiHost("https://api.openai.com/").build().init();ConsoleStreamListener listener = new ConsoleStreamListener();Message message = Message.of("写一段七言绝句诗,题目是:火锅!");ChatCompletion chatCompletion = ChatCompletion.builder().messages(Arrays.asList(message)).build();chatGPTStream.streamChatCompletion(chatCompletion, listener);
流式配合Spring SseEmitter使用
@GetMapping("/chat/sse")@CrossOriginpublic SseEmitter sseEmitter(String prompt) {//国内需要代理 国外不需要Proxy proxy = Proxys.http("127.0.0.1", 1080);ChatGPTStream chatGPTStream = ChatGPTStream.builder().timeout(600).apiKey("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").proxy(proxy).apiHost("https://api.openai.com/").build().init();SseEmitter sseEmitter = new SseEmitter(-1L);SseStreamListener listener = new SseStreamListener(sseEmitter);Message message = Message.of(prompt);listener.setOnComplate(msg -> {//回答完成,可以做一些事情});chatGPTStream.streamChatCompletion(Arrays.asList(message), listener);return sseEmitter;}
多KEY自动轮询
chatGPT = ChatGPT.builder().apiKeyList(// 从数据库或其他地方取出多个KEYArrays.asList("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","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","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","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",)).timeout(900).proxy(proxy).apiHost("https://api.openai.com/") //代理地址.build().init();