async function fetchAIResponse(question: string, aiMessage: any) {
controller.value = new AbortController()
try {
const response = await fetch('/dsapi/api/compatible-model/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer 0ab130ed7d624d059ab9798bdf18cd19`,
},
body: JSON.stringify({
model: 'DeepSeek-R1',
messages: getLimitedContextMessages(),
stream: true,
}),
signal: controller.value.signal,
})
const reader = response.body.getReader()
const decoder = new TextDecoder('utf-8')
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
const lines = chunk.split('\n').filter((line) => line.trim() !== '')
for (const line of lines) {
if (!line.startsWith('data: ')) continue
const data = line.replace('data: ', '').trim()
// 结束
if (data === '[DONE]') {
aiMessage.done = true
aiMessage.isThinking = false
loading.value = false
controller.value = null
return
}
try {
const json = JSON.parse(data)
const delta = json.choices?.[0]?.delta || {}
const content = delta.content || ''
if (content === '</think>') {
aiMessage.isThinking = false
continue
}
if (aiMessage.isThinking) {
aiMessage.thoughts += content
} else {
aiMessage.content += content
}
messages.value = [...messages.value]
scrollToBottom()
} catch (err) {
console.error('JSON parse error:', err)
}
}
}
} catch (err) {
if (err.name === 'AbortError') {
aiMessage.content += '\n\n⚠️ 已中止回答'
} else {
aiMessage.content = marked.parse('❌ 请求失败')
}
aiMessage.done = true
aiMessage.isThinking = false
} finally {
loading.value = false
controller.value = null
}
}
前端接入DeepSeek Api,使用fetch实现流式接收
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 关键点: 1、开启ssl配置2、proxy_set_header Host 要跟域名,如:proxy_set_he...
- 使用@microsoft/fetch-event-source发送post请求接收stream流数据实现chatG...
- 转自 https://www.jianshu.com/p/0ee9b1a3b3e0[https://www.jia...