前端接入DeepSeek Api,使用fetch实现流式接收

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
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容