附上我做的 ws api 的源码
```js
wss.on('connection', ws => {
let isConnected = true
ws.on('message', async e => {
let message = JSON.parse(e.toString())
if(message.type == 'conversation') {
let es = await fetch('
https://api.openai.com/v1/chat/completions', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + 'YOUR_OPENAI_API_KEY'
},
method: 'POST',
body: JSON.stringify({
model: message.data.model,
messages: message.data.messages,
stream: true
})
})
const reader = es.body.pipeThrough(new TextDecoderStream()).getReader()
let errObj = ''
while(true) {
if(!isConnected) {
process.stdout.write('\n')
break
}
const res = await reader.read()
if(res.done) {
break
}
let chunk = res.value
chunk = chunk.replace(/data: /g, '').split('\n')
chunk.map(item => {
if(item != '[DONE]' && item != '' && item != undefined) {
let json
try {
if(errObj != '') {
item = errObj + item
errObj = ''
}
json = JSON.parse(item)
if(json.choices[0].delta.content == undefined) return
ws.send(JSON.stringify({
type: 'conversation',
data: {
type: 'continue',
text: json.choices[0].delta.content
}
}))
process.stdout.write(json.choices[0].delta.content)
}catch {
errObj = item
return
}
}else if(item == '[DONE]') {
ws.send(JSON.stringify({
type: 'conversation',
data: {
type: 'done',
text: null
}
}))
process.stdout.write('\n')
}
})
}
}
})
ws.onclose = () => {
isConnected = false
}
})
```