以下是一个示例代码,假设已经引入了axios库和jQuery库:

// 定义一个全局变量用于存储websocket连接
let ws;

// 定义一个函数用于初始化websocket连接
function initWebSocket() {
  // 创建websocket连接
  ws = new WebSocket("wss://api.openai.com/v1/chat/completions/stream");

  // 监听连接打开事件
  ws.onopen = function() {
    console.log("WebSocket连接已打开");
  };

  // 监听接收到消息事件
  ws.onmessage = function(event) {
    // 将接收到的数据转为文本
    let text = JSON.parse(event.data).choices[0].text;

    // 打印到文本框
    $("#output").append(text);
  };

  // 监听连接关闭事件
  ws.onclose = function() {
    console.log("WebSocket连接已关闭");
  };
}

// 定义一个函数用于发送请求
function sendRequest(prompt) {
  // 构造请求数据
  let requestData = {
    prompt: prompt,
    max_tokens: 10,
    temperature: 0.5,
    n: 1,
    stream: true
  };

  // 发送POST请求
  axios.post("https://api.openai.com/v1/chat/completions", requestData, {
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
    }
  })
  .then(response => {
    // 打开websocket连接
    if (!ws || ws.readyState !== WebSocket.OPEN) {
      initWebSocket();
    }
  })
  .catch(error => {
    console.log(error);
  });
}

// 监听提交按钮点击事件
$("#submit").click(function() {
  let prompt = $("#prompt").val();
  sendRequest(prompt);
});

上面的代码中,initWebSocket函数用于初始化websocket连接,sendRequest函数用于发送请求,当请求成功时打开websocket连接,并将接收到的数据转为文本逐字打印到文本框。监听提交按钮点击事件,获取输入框中的文本,调用sendRequest函数发送请求。在发送请求时,需要将stream参数设置为true,表示开启流式传输模式。另外,需要在请求头中添加Authorization和Content-Type两个参数,分别用于传递API密钥和设置请求数据格式为JSON。

js调用chatgpt的v1chatcompletions接口 使用stream为true接收到的数据转为文本逐字打印到文本框

原文地址: https://www.cveoy.top/t/topic/M9l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录