Java8对接三方流式接口,并实时输出(GPT)

Java对接模型流式接口,并流式输出

核心依赖

  		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.33</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Demo代码

@GetMapping(value = "/test", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public DeferredResult<ResponseBodyEmitter> proxyModel22() throws IOException {
        DeferredResult<ResponseBodyEmitter> deferredResult = new DeferredResult<>();

        // 创建 URL
        URL url = new URL("Third-party API");

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setDoOutput(true); // 设置为 POST 请求
        connection.setDoInput(true); // 允许读取响应

		// 构建请求体
        String bodyJSON = "{\n" +
                "    \"input\": \"Who are you?\",\n" +
                "    \"user\": \"guest\",\n" +
                "    \"stream\": true,\n" +
                "    \"increase\": true,\n" +
                "    \"sessionId\": \"9xxxxxx\",\n" +
                "    \"history\": []\n" +
                "}";
        JSONObject jsonObject = JSON.parseObject(bodyJSON);
        try (OutputStream os = connection.getOutputStream()) {
            os.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8)); // 写入请求体
            os.flush();
        }

        // 检查响应状态码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            ResponseBodyEmitter emitter = new ResponseBodyEmitter();
            InputStream inputStream = connection.getInputStream();

            Thread thread = new Thread(() -> {
                byte[] buffer = new byte[4096]; // 缓冲区大小
                int length;

                try {
                    while ((length = inputStream.read(buffer)) != -1) {
                        // 只发送实际读取的数据长度
                        byte[] dataToSend = new byte[length];
                        System.arraycopy(buffer, 0, dataToSend, 0, length);
                        emitter.send(dataToSend);
                    }
                    inputStream.close();
                    emitter.complete(); // 完成发送
                } catch (IOException e) {
                  log.error("错误信息为: " + e);
                }
            });

            thread.start();

            deferredResult.setResult(emitter);
        } else {
            // 如果第三方服务返回错误状态码
            deferredResult.setErrorResult(new RuntimeException("Third-party API returned an error: " + responseCode));
        }

        return deferredResult;
    }
Java实现ChatGPT流式接口可以使用OpenAI GPT-3的REST API进行通信。下面是一个简单的示例代码: ```java import okhttp3.*; import org.json.JSONObject; import java.io.IOException; public class ChatGPTClient { private static final String API_ENDPOINT = "https://api.openai.com/v1/engines/davinci/completions"; private final OkHttpClient client; private final String apiKey; public ChatGPTClient(String apiKey) { this.apiKey = apiKey; this.client = new OkHttpClient(); } public String sendMessage(String message) throws IOException { RequestBody requestBody = new FormBody.Builder() .add("model", "davinci") .add("prompt", message) .build(); Request request = new Request.Builder() .url(API_ENDPOINT) .header("Authorization", "Bearer " + apiKey) .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { JSONObject json = new JSONObject(response.body().string()); String completions = json.getJSONArray("choices").getJSONObject(0).getString("text"); return completions; } } public static void main(String[] args) { ChatGPTClient client = new ChatGPTClient("YOUR_API_KEY"); try { String message = "Hello!"; while (!message.equals("bye")) { String response = client.sendMessage(message); System.out.println("AI: " + response); // 接收用户输入 // ... } } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码使用了OkHttp库进行HTTP请求,并使用JSONObject解析响应结果。请确保你替换`YOUR_API_KEY`为你的OpenAI API密钥。 这个示例代码只是一个基本的实现,你可以根据自己的需求进行扩展和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值