如何使用 Server-Sent Events 与 FastAPI、React 和 Langgraph

Let's start with a simple challenge. Can you spot the difference between the two demos below?

让我们从一个简单的挑战开始。你能发现下面两个演示之间的区别吗?

Comparing streaming vs non-streaming in AI data analysis and visualization tool DataLine

比较 AI 数据分析和可视化工具 DataLine 中的流式和非流式

While it may look like one is faster than the other (and it is not), this is none other than the illusion of streaming. For apps where long waits are inevitable, for e.g. due to AI nowadays, it's a great way to keep your users hooked by giving them the final result in bits and pieces. The trick is to immediately show any intermediate output instead of waiting for the entire process to finish.

虽然看起来一个比另一个快(其实并不是),这不过是流式处理的错觉。对于由于AI等原因不可避免的长时间等待的应用程序,这是一个很好的方法,通过分段给用户展示最终结果来保持他们的兴趣。诀窍是立即显示任何中间输出,而不是等待整个过程完成。

To better understand this, let's implement streaming in a straightforward manner using tools that need no introduction: FastAPI, React, and Server-Sent Events—okay, this last one might actually need an intro.

为了更好地理解这一点,让我们使用不需要介绍的工具以一种简单的方式实现流式传输:FastAPIReactServer-Sent Events——好吧,最后一个可能确实需要介绍一下。

What is SSE?

什么是 SSE?

Server-Sent Events are a way for servers to push updates to a web page over a single, long-lived HTTP connection. Think of it like a one-way street where the server sends new information to the browser whenever there's an update, without the browser having to keep asking for it. This is perfect for things like live sports scores, live news feeds, or any other real-time updates. It's simple to use and integrates well with many web technologies.

服务器发送事件是一种服务器通过单个、长时间存在的HTTP连接向网页推送更新的方式。可以将其视为一条单行道,服务器在有更新时向浏览器发送新信息,而无需浏览器不断请求。这非常适合实时体育比分、实时新闻提要或任何其他实时更新。它使用简单,并且与许多Web技术很好地集成。

Why SSE?

为什么选择 SSE?

Using SSE is less complex compared to WebSockets, making it easier to implement and maintain. It is ideal for scenarios where the server needs to push updates to the client without requiring a response since it is unidirectional by nature (Server -> Client only).

使用 SSE 比 WebSockets 更简单,使其更易于实现和维护。它非常适合服务器需要向客户端推送更新而不需要响应的场景,因为它本质上是单向的(服务器 -> 客户端)。

SSE works by ...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2024 iteam. Current version is 2.139.0. UTC+08:00, 2024-12-25 15:02
浙ICP备14020137号-1 $Carte des visiteurs$