fix: 修复写作工坊流式输出失效问题,优化流数据解析稳定性

This commit is contained in:
empty
2026-01-08 10:32:37 +08:00
parent d0067f5210
commit 03e4007149
2 changed files with 47 additions and 43 deletions

View File

@@ -14,27 +14,34 @@ class DeepSeekAPI {
}
async generateContent(prompt, options = {}) {
const response = await this.client.post('', {
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个资深的专业写作助手,请严格按照用户的要求进行创作。'
},
{
role: 'user',
content: prompt
}
],
stream: true,
temperature: 0.7,
...options
}, {
const response = await fetch(this.baseURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
}
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个资深的专业写作助手,请严格按照用户的要求进行创作。'
},
{
role: 'user',
content: prompt
}
],
stream: true,
temperature: 0.7,
...options
})
})
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`)
}
return response
}

View File

@@ -197,42 +197,39 @@ const generateContent = async () => {
const response = await api.generateContent(prompt)
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value)
const content = parseStreamResponse(chunk)
generatedContent.value += content
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() // 最后一行可能不完整,存入 buffer
for (const line of lines) {
const trimmedLine = line.trim()
if (!trimmedLine || !trimmedLine.startsWith('data: ')) continue
const data = trimmedLine.slice(6)
if (data === '[DONE]') break
try {
const parsed = JSON.parse(data)
const content = parsed.choices?.[0]?.delta?.content || ''
if (content) {
generatedContent.value += content
}
} catch (e) {
console.warn('解析流数据失败:', e, data)
}
}
}
} catch (error) {
console.error('生成内容失败:', error)
generatedContent.value = `## 错误\n\n${error.message}\n\n请检查 API 配置是否正确。`
} finally {
isGenerating.value = false
}
}
// 解析流式响应
const parseStreamResponse = (chunk) => {
const lines = chunk.split('\n').filter(line => line.trim())
const contents = []
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6)
if (data === '[DONE]') continue
try {
const parsed = JSON.parse(data)
const content = parsed.choices?.[0]?.delta?.content || ''
if (content) contents.push(content)
} catch (e) {
// 忽略解析错误
}
}
}
return contents.join('')
}
</script>