AI API流式输出(Streaming)完整实现:Python/Node/前端
随着 AI 应用需求的激增,实时交互体验成为提升用户满意度的关键。BAYLLM AI 作为领先的 AI API 中转站服务商,支持多达 17 种主流模型,提供稳定高效的 AI 计算能力,并且支持国内直连,极大优化了访问速度和稳定性。本文将围绕 **AI API流式输出**(Streaming API)...

AI API流式输出(Streaming)完整实现指南:Python / Node.js / 前端
随着 AI 应用需求的激增,实时交互体验成为提升用户满意度的关键。BAYLLM AI 作为领先的 AI API 中转站服务商,支持多达 17 种主流模型,提供稳定高效的 AI 计算能力,并且支持国内直连,极大优化了访问速度和稳定性。本文将围绕 AI API流式输出(Streaming API)展开,详细介绍如何在 Python、Node.js 和前端实现流式输出,帮助开发者打造高效、响应迅速的 AI 应用。
引言
传统的 AI API 调用大多是同步等待完整结果返回,导致用户体验上的延迟感加重。流式输出(Streaming)技术则突破这一限制,通过逐步接收模型生成的内容,用户能实时看到 AI 生成的文本,极大提升交互的自然度和流畅度。
BAYLLM AI 支持包括 OpenAI、Anthropic Claude、Google Gemini 等多款主流模型的流式输出,在线率均超过 98%,延迟控制在 1.5 秒内,适合各类实时 AI 应用场景。本文将基于 BAYLLM AI 提供的 API,结合 Python、Node.js 和浏览器端的 SSE(Server-Sent Events)技术,系统讲解流式输出实现方案。
什么是 AI API 流式输出?
流式输出是指 AI 模型在生成文本时,边生成边通过网络逐步返回结果给客户端,而非等待所有文本生成完成后一次性返回。
流式输出带来的优势
常用流式技术协议
EventSource 轻松实现。BAYLLM AI API 采用 SSE 方式实现流式输出,兼容性与简单性兼备。
1. 使用 Python Generator 实现流式接收
Python 是 AI 开发的首选语言,利用 generator 可以方便地处理流式数据。
示例代码
import requests
API_KEY = "sk-你的密钥"
BASE_URL = "https://bayllm.com/v1/chat/completions"
def stream_chat(messages):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": "gpt-4o-mini",
"messages": messages,
"stream": True
}
with requests.post(BASE_URL, json=payload, headers=headers, stream=True) as resp:
resp.raise_for_status()
for line in resp.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith("data: "):
data_str = decoded_line[len("data: "):]
if data_str == "[DONE]":
break
yield data_str
if __name__ == "__main__":
prompt_messages = [
{"role": "user", "content": "请介绍一下BAYLLM AI的优势。"}
]
print("AI回复:")
for chunk in stream_chat(prompt_messages):
print(chunk, end='', flush=True)
说明
requests.post 设置 stream=True 以开启流式请求。2. Node.js Async Iterator 方式实现流式输出
Node.js 的异步迭代器使得流式处理更简洁优雅,结合 fetch 或第三方请求库均可实现。
示例代码(Node.js 18+ 环境)
import fetch from "node-fetch";
const API_KEY = "sk-你的密钥";
const BASE_URL = "https://bayllm.com/v1/chat/completions";
async function* streamChat(messages) {
const res = await fetch(BASE_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages,
stream: true
})
});
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let lines = buffer.split("
");
buffer = lines.pop(); // 末尾可能不完整,保留待下次解析
for (const line of lines) {
if (line.startsWith("data: ")) {
const dataStr = line.substring(6).trim();
if (dataStr === "[DONE]") return;
yield dataStr;
}
}
}
}
(async () => {
const messages = [{ role: "user", content: "请介绍一下BAYLLM AI的优势。" }];
console.log("AI回复:");
for await (const chunk of streamChat(messages)) {
process.stdout.write(chunk);
}
})();
说明
ReadableStream 的 getReader() 逐块读取响应体。data: 行,逐条 yield。3. 前端浏览器端基于 EventSource 实现流式渲染
浏览器端直接使用原生的 EventSource API,监听服务器发送的事件,实现实时文本流展示。
示例代码(HTML + JavaScript)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>BAYLLM AI 流式输出示例</title>
</head>
<body>
<h2>AI Chat Streaming Demo</h2>
<pre id="output" style="white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; max-width: 600px;"></pre>
<script>
const output = document.getElementById('output');
// 构造 SSE 链接,模拟传递参数(实际应用中通常通过POST启动流)
// 这里假设 BAYLLM AI 支持 GET + SSE(若不支持,可用fetch + ReadableStream替代)
const eventSource = new EventSource('https://bayllm.com/v1/chat/stream?model=gpt-4o-mini&api_key=sk-你的密钥');
eventSource.onmessage = (event) => {
if(event.data === "[DONE]") {
eventSource.close();
output.textContent += "
--- 完成 ---";
return;
}
output.textContent += event.data;
};
eventSource.onerror = (err) => {
console.error('EventSource error:', err);
eventSource.close();
output.textContent += "
[连接已关闭或发生错误]";
};
</script>
</body>
</html>
说明
EventSource 适合服务器端推送单向事件流。fetch + ReadableStream 方案(详见下节)。4. 进阶方案:前端使用 Fetch + ReadableStream 实现流式
由于部分 AI API 不支持 EventSource,前端推荐使用 fetch 搭配 ReadableStream 处理流式响应。
示例代码(现代浏览器)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>BAYLLM AI Fetch流式输出示例</title>
</head>
<body>
<h2>AI Chat Streaming Demo (Fetch + ReadableStream)</h2>
<pre id="output" style="white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; max-width: 600px;"></pre>
<script>
const output = document.getElementById('output');
const API_KEY = 'sk-你的密钥';
const BASE_URL = 'https://bayllm.com/v1/chat/completions';
async function streamChat() {
const response = await fetch(BASE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: '请介绍一下BAYLLM AI的优势。' }],
stream: true
})
});
if (!response.ok) {
output.textContent = '请求失败,状态码:' + response.status;
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let done = false;
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
if (value) {
const chunk = decoder.decode(value, { stream: true });
// SSE通常以 "data: "开头多条数据用换行分隔,需要解析
chunk.split('
').forEach(line => {
if (line.startsWith('data: ')) {
const dataStr = line.substring(6).trim();
if (dataStr === '[DONE]') {
done = true;
return;
}
output.textContent += dataStr;
}
});
}
}
output.textContent += '
--- 完成 ---';
}
streamChat();
</script>
</body>
</html>
说明
总结
BAYLLM AI 作为国内领先的 AI API 中转站,凭借 98% 以上的在线率和低至 1.5 秒的延迟,为开发者提供高效稳定的 AI 计算服务。流式输出作为提升用户交互体验的关键技术,本文详细介绍了三端实现方案:
掌握这些流式技术,开发者能轻松打造出响应迅速、用户体验极佳的智能应用,助力产品在激烈竞争中脱颖而出。
相关文章
本文由专业 AI API 技术作者撰写,致力于为开发者提供最实用的 BAYLLM AI 流式输出解决方案。
相关文章推荐
以下是 BAYLLM AI 文章中心的相关内容:
查看更多:[BAYLLM AI 文章中心](https://bayllm.com/articles)