TanStack AI 支持流式响应,用于实时聊天体验。流式传输允许您在生成响应时显示响应,而不是等待完整的响应。
当您使用 chat() 时,它会返回一个异步可迭代的块流
import { chat } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
const stream = chat({
adapter: openaiText("gpt-5.2"),
messages,
});
// Stream contains chunks as they arrive
for await (const chunk of stream) {
console.log(chunk); // Process each chunk
}
使用 toServerSentEventsResponse 将流转换为 HTTP 响应
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
export async function POST(request: Request) {
const { messages } = await request.json();
const stream = chat({
adapter: openaiText("gpt-5.2"),
messages,
});
// Convert to HTTP response with proper headers
return toServerSentEventsResponse(stream);
}
useChat hook 会自动处理流式传输
import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
const { messages, sendMessage, isLoading } = useChat({
connection: fetchServerSentEvents("/api/chat"),
});
// Messages update in real-time as chunks arrive
messages.forEach((message) => {
// Message content updates incrementally
});
TanStack AI 实现了 AG-UI 协议 进行流式传输。流事件包含不同类型的数据
思考/推理由 AG-UI 事件 STEP_STARTED 和 STEP_FINISHED 表示。它们与最终响应文本分开流式传输
for await (const chunk of stream) {
if (chunk.type === "STEP_FINISHED") {
console.log("Thinking:", chunk.content); // Accumulated thinking content
console.log("Delta:", chunk.delta); // Incremental thinking token
}
}
思考内容会自动转换为 UIMessage 对象中的 ThinkingPart。它仅用于 UI,不包含发送回模型的消息。
TanStack AI 提供用于不同流式传输协议的连接适配器
import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
const { messages } = useChat({
connection: fetchServerSentEvents("/api/chat"),
});
import { useChat, fetchHttpStream } from "@tanstack/ai-react";
const { messages } = useChat({
connection: fetchHttpStream("/api/chat"),
});
import { stream } from "@tanstack/ai-react";
const { messages } = useChat({
connection: stream(async (messages, data, signal) => {
// Custom streaming implementation
const response = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ messages, ...data }),
signal,
});
// Return async iterable
return processStream(response);
}),
});
您可以使用回调函数监控流进度
const { messages } = useChat({
connection: fetchServerSentEvents("/api/chat"),
onChunk: (chunk) => {
console.log("Received chunk:", chunk);
},
onFinish: (message) => {
console.log("Stream finished:", message);
},
});
取消正在进行的流
const { stop } = useChat({
connection: fetchServerSentEvents("/api/chat"),
});
// Cancel the current stream
stop();