Java接入AI接口

如果你现在项目,JDK在17版本及以上 建议你去学习spring ai 的框架,本篇主要以jdk8版本的项目实现(手搓)ai接口的接入

第一步要先引入以下依赖

      
            
                com.google.code.gson
                gson
                2.8.9
            
            
            
                org.apache.httpcomponents.client5
                httpclient5
                5.1.3
            


        
            org.junit.jupiter
            junit-jupiter-api
            5.8.1
            test
        

在具体实现之前 你需要设置一个 ai配置,最好是单开的配置类,便于你通过如nacos或其他方式进行配置更新,如果你使用的不是阿里的 需要先去看具体文档进行修改

  private String apiKey;
    private String model;
    private String URL;

    private Double temperature;

    public AIConfig() {
        URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 你选择的AI的对应接口 这里以阿里云为例
        apiKey = "sk-xxx"; // 相关的个人密钥
        model = "qwen-plus"; // 选择的模型
        temperature = 0.8; // 模型温度 - 模型温度越高,模型越随机,越能探索新领域,但同时越容易产生一些不精确的结果。
    }

然后 你需要配置一个对话类 

/**
 * 表示对话中的消息。
 */
public class AIMessage {
        /**
         * 消息的角色(例如:system, user)。
         */
        private String role;

        /**
         * 消息的内容。
         */
        private String content;

}

接着构建请求的实体

/**
 * 表示发送给AI API的请求对象。
 */
public class AIRequst {


        /**
         * 用于请求的模型名称。
         */
        private String model;

        /**
         * 对话中的消息列表。
         */
        private List messages;

        /**
         * 控制响应随机性的温度参数。
         */
        private double temperature;

接下是具体的使用展示,其中一些具体的细节,需要你具体使用才有所体会

public ResultBody AIImport(String userId, String issue) {
        String key = "AI_" + userId;
        // 历史聊天记录
        Object cacheObject = redisService.getCacheObject(key);
        String contextInfo = "";
        if(cacheObject != null)
          contextInfo= (String) cacheObject;

        AIRequst openaiReq = new AIRequst();
        openaiReq.setModel(aiConfig.getModel());

        List messages = new ArrayList<>();
        AIMessage systemMessage = new AIMessage();
        systemMessage.setRole("system");
        systemMessage.setContent("你是一个语音聊天助手, 你会讲冷笑话,鬼故事等。");
        messages.add(systemMessage);

        AIMessage userMessage = new AIMessage();
        userMessage.setRole("user");
        userMessage.setContent(String.format("上下文信息:\n%s\n\n用户问题:%s", contextInfo, issue));
        messages.add(userMessage);

        openaiReq.setMessages(messages);
        openaiReq.setTemperature(aiConfig.getTemperature());

        Gson gson = new Gson();
        String jsonRequest = gson.toJson(openaiReq);

        try {
            URL url = new URL(aiConfig.getURL());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 立即设置请求方法为 POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + aiConfig.getApiKey());
            connection.setDoOutput(true);



            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonRequest.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);

            if (responseCode == 200) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                    if(jsonResponse.getAsJsonArray("choices").isEmpty())
                     return ResultBody.error().message("AI 响应超时....");
                    // assertNotNull(jsonResponse.getAsJsonArray("choices"), "AI响应应包含choices");
                    // assertEquals(1, jsonResponse.getAsJsonArray("choices").size(), "AI响应应包含一个choice");

                    JsonObject choice = jsonResponse.getAsJsonArray("choices").get(0).getAsJsonObject();
                    JsonObject message = choice.getAsJsonObject("message");
                    String answer = message.get("content").getAsString().trim();

                    if(answer.isEmpty()) {
                        return ResultBody.error().message("AI 响应超时");
                    }
                   // assertNotNull(answer, "AI响应应包含一个非空答案");
                    // System.out.println("答案: " + answer);
                    redisService.setCacheObject(key, issue, 300l, TimeUnit.MINUTES);
                    return ResultBody.ok().message(answer);
                }
            } else {
                // 处理非200状态码的情况
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String errorLine;
                    while ((errorLine = br.readLine()) != null) {
                        errorResponse.append(errorLine.trim());
                    }
                    System.err.println("错误响应: " + errorResponse.toString());
                }
                return ResultBody.error().message("AI 响应超时...");
                // fail("意外的HTTP响应状态码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBody.error().message("AI 响应超时");
            // fail("IO异常发生: " + e.getMessage());
        }
    }

最后,希望大家能在学习中有所收获,无论是工作还是满足个人的爱好(实习好难找)

                                                                                                     --春风若有怜花意,可否许我再少年

你可能感兴趣的:(java,ai)