后端请求gpt接口 打字机效果响应给前端
时间: 2025-06-26 19:11:28 浏览: 8
### 实现方案
要在后端调用 GPT API 并将结果以打字机效果展示到前端页面,可以按照以下方式设计架构:
#### 后端部分
在后端实现与 GPT 接口的交互时,可以通过启用 `stream` 参数来获取流式响应。这允许后端逐步接收数据并将其传递给前端。
以下是使用 Node.js 和 Express 的示例代码片段,用于处理来自 GPT API 的流式响应并将数据推送到前端:
```javascript
const express = require('express');
const app = express();
const { Readable } = require('stream');
app.post('/api/generate', async (req, res) => {
try {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer YOUR_API_KEY`,
},
body: JSON.stringify({
model: 'mistralai/mistral-7b-instruct',
messages: [{ role: 'user', content: req.body.prompt }, { role: 'assistant', content: '' }],
stream: true,
}),
});
if (!response.ok) throw new Error(`Error ${response.status}: ${await response.text()}`);
// 将流式响应转换为可读流
const readableStream = response.body.pipeThrough(new TextDecoderStream());
// 设置 SSE 头部以便前端能够解析事件流
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// 遍历每一部分内容并通过 SSE 发送至前端
for await (const chunk of readableStream.getReader()) {
const data = chunk.value.replace(/data:\s*/g, '');
if (data === '[DONE]') break;
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
} catch (error) {
console.error(error);
res.sendStatus(500);
}
});
app.listen(3000, () => console.
阅读全文
相关推荐















