PlexPt / chatgpt-java

ChatGPT Java SDK。支持 GPT-4o、 GPT4 API。开箱即用。An unofficial Java SDK for seamless integration with ChatGPT's GPT-3.5 and GPT-4 APIs. Ready-to-use, simple setup, and efficient for building AI-powered applications.
https://chat.plexpt.com/
GNU General Public License v3.0
3.6k stars 706 forks source link

在Minecraft Java服务器中,回答的时候服务器会卡一下 #318

Open MCheping8108 opened 2 months ago

MCheping8108 commented 2 months ago

https://github.com/user-attachments/assets/19c2bbcb-1a37-42a0-be54-4646b903a0c3

PlexPt commented 2 months ago

请使用异步

MCheping8108 commented 2 months ago

请使用异步

不太懂,有其他解决方案吗

PlexPt commented 2 months ago

请贴出代码

MCheping8108 commented 2 months ago
package top.peacefuly.minecraftChatGPT.command;

import com.plexpt.chatgpt.ChatGPT;
import com.plexpt.chatgpt.entity.chat.ChatCompletion;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import top.peacefuly.minecraftChatGPT.MinecraftChatGPT;

import java.util.Arrays;

public class ChatCommand implements CommandExecutor {
    private final MinecraftChatGPT plugin;
    public ChatCommand(MinecraftChatGPT plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
        String apikey = this.plugin.getConfig().getString("apikey");
        String apihost = this.plugin.getConfig().getString("apihost");
        String gptModel = this.plugin.getConfig().getString("gpt-model");
        int maxtokens = this.plugin.getConfig().getInt("max-tokens");
        if (apikey == null || apikey.isEmpty() || apikey.equals("sk-xxxxxx")) {
            commandSender.sendMessage("Please set apikey in config.yml");
            return true;
        }

        ChatGPT chatGPT = ChatGPT.builder()
                .apiKey(apikey)
                .apiHost(apihost)
                .timeout(15000)
                .build()
                .init();

        if (commandSender instanceof Player p){
            String question = String.join(" ", strings);
            Message message = Message.of(question);
            ChatCompletion chatCompletion = ChatCompletion.builder()
                    .model(gptModel)
                    .messages(Arrays.asList(message))
                    .maxTokens(maxtokens)
                    .stream(false)
                    .build();
            ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
            p.sendMessage(response.getChoices().get(0).getMessage().getContent());
        }

        return true;
    }
}
PlexPt commented 2 months ago

使用 stream 模式