AzureAIClient.java 3.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
package com.kwan.springbootkwan.entity.openai;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;

import java.io.Closeable;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.Future;

@Slf4j
public class AzureAIClient implements Closeable {
    private static final String JSON = "application/json; charset=UTF-8";
    private final boolean closeClient;
    private final AsyncHttpClient client;
    private final String deploymentName;
    private final String url;
    private final String token;
    private final String apiVersion;
    private boolean closed = false;
    Gson gson = new Gson();

    public AzureAIClient(String url, String apiKey, String deploymentName, String apiVersion) throws Exception {
        this.client = new DefaultAsyncHttpClient();
        this.url = url + "/openai/deployments/" + deploymentName + "/";
        this.token = apiKey;
        this.deploymentName = deploymentName;
        this.apiVersion = apiVersion;
        closeClient = true;
    }

    public boolean isClosed() {
        return closed || client.isClosed();
    }

    @Override
    public void close() {
        if (closeClient && !client.isClosed()) {
            try {
                client.close();
            } catch (IOException ex) {
            }
        }
        closed = true;
    }

    public AzureAIChatResponse sendChatRequest(AzureAIChatRequest chatRequest) throws Exception {
        Date startDateOne = DateUtil.date();
        Future<Response> f = client.executeRequest(buildRequest("POST", "chat/completions?api-version=" + apiVersion, gson.toJson(chatRequest)));
        Response r = f.get();
        Date endDateOne = DateUtil.date();
        // 获取开始时间和结束时间的时间差
        long betweenDateOne = DateUtil.between(startDateOne, endDateOne, DateUnit.MS);
        // 格式化时间
        String formatBetweenOne = DateUtil.formatBetween(betweenDateOne, BetweenFormatter.Level.MILLISECOND);
        log.info(String.format("请求数据耗时(毫秒):%s", formatBetweenOne));
        if (r.getStatusCode() != 200) {
            log.info("Could not create chat request - server resposne was " + r.getStatusCode() + " to url: " + url + "chat/completions?api-version=2023-03-15-preview");
            return null;
        } else {
            Date startDate = DateUtil.date();
            AzureAIChatResponse azureAIChatResponse = JSONUtil.toBean(r.getResponseBody(), AzureAIChatResponse.class);
            Date endDate = DateUtil.date();
            // 获取开始时间和结束时间的时间差
            long betweenDate = DateUtil.between(startDate, endDate, DateUnit.MS);
            // 格式化时间
            String formatBetween = DateUtil.formatBetween(betweenDate, BetweenFormatter.Level.MILLISECOND);
            log.info(String.format("格式化数据耗时(毫秒):%s", formatBetween));
            return azureAIChatResponse;
        }
    }

    private Request buildRequest(String type, String subUrl, String requestBody) {
        RequestBuilder builder = new RequestBuilder(type);
        Request request = builder.setUrl(this.url + subUrl)
                .addHeader("Accept", JSON)
                .addHeader("Content-Type", JSON)
                .addHeader("api-key", this.token)
                .setBody(requestBody)
                .build();
        return request;
    }
}