stream: true 的方式应该怎么写?
时间: 2024-04-18 19:26:19 浏览: 96
要使用 OpenAI API 的 stream 模式,您需要对代码进行一些修改。以下是使用 Java 进行 stream 请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class OpenAIJavaStreamExample {
public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
String prompt = "Hello, world!";
String model = "gpt-3.5-turbo";
OpenAIJavaStreamExample.sendRequest(apiKey, prompt, model);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendRequest(String apiKey, String prompt, String model) throws IOException {
String url = "https://api.openai.com/v1/engines/" + model + "/completions";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Set the request method and headers
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
// Build the JSON request body
String requestBody = "{\"prompt\": \"" + prompt + "\", \"stream\": true}";
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Send the request and get the response
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Response: " + inputLine);
}
in.close();
}
}
```
请注意,与之前的代码相比,我们在请求体中添加了 `"stream": true`。在 `while` 循环中,我们逐行读取响应并打印出来。
记得将 `YOUR_API_KEY` 替换为您自己的 API 密钥。
阅读全文