前言
在調(diào)用OpenAI GPT接口時(shí),如果不使用流式(stream:true)參數(shù),接口會等待所有數(shù)據(jù)生成完成后一次返回。這個(gè)等待時(shí)間可能會很長,給用戶帶來不良體驗(yàn)。
為了提升用戶體驗(yàn),我們需要使用流式調(diào)用方式。在這篇文章中,我們將介紹如何使用Spring Boot和Vue對接OpenAI GPT接口,并實(shí)現(xiàn)類似ChatGPT逐字輸出的效果。
一、效果
PC端
移動(dòng)端
二、Springboot后端
1.封裝請求OpenAI接口的客戶端
官方給的Example request:
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hello!"}]
}'
根據(jù)官方示例,用java封裝請求接口的客戶端。本文選擇使用OkHttpClient
作為http請求客戶端。
注意:接口調(diào)用需要魔法文章來源:http://www.zghlxwxcb.cn/news/detail-470356.html
GtpClient.java文章來源地址http://www.zghlxwxcb.cn/news/detail-470356.html
@Component
public class GptClient {
private final String COMPLETION_ENDPOINT = "https://api.openai.com/v1/chat/completions";
// OpenAI的API key
@Value("${gpt.api-key}")
private String apiKey;
// 魔法服務(wù)器地址
@Value("${network.proxy-host}")
private String proxyHost;
// 魔法服務(wù)器端口
@Value("${network.proxy-port}")
private int proxyPort;
OkHttpClient client = new OkHttpClient();
MediaType mediaType;
Request.Builder requestBuilder;
@PostConstruct
private void init() {
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
client.setConnectTimeout(60, TimeUnit.SECONDS);
client.setReadTimeout(60, TimeUnit.SECONDS);
mediaType = MediaType.parse("application/json; charset=utf-8");
requestBuilder = new Request.Builder()
.url(COMPLETION_ENDPOINT)
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey);
}
/**
* 聊天接口
* @param requestBody 聊天接口請求體
* @return 接口請求響應(yīng)
*/
public Response chat(ChatRequestBody requestBody) throws ChatException {
RequestBody bodyOk = RequestBody.create(mediaType, requestBody.toString())<
到了這里,關(guān)于springboot+vue實(shí)現(xiàn)ChatGPT逐字輸出打字效果的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!