跳到导航

服务器发送事件和流式 API

使用 x-fern-streaming 扩展来建模流式端点

以 Markdown 格式查看

x-fern-streaming 扩展允许您表示流式端点。

JSON 流式传输

如果您的 API 返回一系列 JSON 块,如下所示

{ "text": "Hi, I am a" }
{ "text": "chatbot. Do you have any"}
{ "text": "questions for me"}

那么只需在您的 OpenAPI 操作中添加 x-fern-streaming: true

openapi.yml
paths:
/logs:
post:
x-fern-streaming: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/Chat"
components:
schemas:
Chat:
type: object
properties:
text:
type: string

服务器发送事件

团队版和企业版功能

此功能仅适用于团队版和企业版计划。要开始使用,请联系 support@buildwithfern.com

如果您的 API 返回服务器发送事件 (SSE),包含 dataevent 键,如下所示

data: { "text": "Hi, I am a" }
data: { "text": "chatbot. Do you have any"}
data: { "text": "questions for me"}

那么确保包含 format: sse

openapi.yml
paths:
/logs:
post:
x-fern-streaming:
format: sse
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/Chat"
components:
schemas:
Chat:
type: object
properties:
text:
type: string

终止消息

一些 SSE API 会发送独立的终止消息来表示流传输完成。例如, OpenAI 的 API 发送 [DONE] 作为最终消息。您可以使用 terminator 字段来指定:

openapi.yml
paths:
/logs:
post:
x-fern-streaming:
format: sse
terminator: "[DONE]"
# ... responses and schemas

Stream 参数

端点拥有一个 stream 参数来控制响应是否为流式传输已成为常见做法。Fern 以一等公民的方式支持这种模式。

只需指定 stream-condition 以及普通响应和流式响应:

openapi.yml
paths:
/logs:
post:
x-fern-streaming:
format: sse
terminator: "[DONE]"
stream-condition: $request.stream
response:
$ref: '#/components/schemas/Chat'
response-stream:
$ref: '#/components/schemas/ChatChunk'
components:
schemas:
Chat:
type: object
properties:
text:
type: string
tokens:
type: number
ChatChunk:
type: object
properties:
text:
type: string