服务器发送事件和流式 API

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

以 Markdown 格式查看

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

JSON 流式传输

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

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

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

openapi.yml
1paths:
2 /logs:
3 post:
4 x-fern-streaming: true
5 responses:
6 "200":
7 content:
8 application/json:
9 schema:
10 $ref: "#/components/schemas/Chat"
11components:
12 schemas:
13 Chat:
14 type: object
15 properties:
16 text:
17 type: string

服务器发送事件

团队版、专业版和企业版功能

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

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

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

那么确保包含 format: sse

openapi.yml
1paths:
2 /logs:
3 post:
4 x-fern-streaming:
5 format: sse
6 responses:
7 "200":
8 content:
9 application/json:
10 schema:
11 $ref: "#/components/schemas/Chat"
12components:
13 schemas:
14 Chat:
15 type: object
16 properties:
17 text:
18 type: string

终止消息

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

openapi.yml
1paths:
2 /logs:
3 post:
4 x-fern-streaming:
5 format: sse
6 terminator: "[DONE]"
7# ... responses and schemas

Stream 参数

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

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

openapi.yml
1paths:
2 /logs:
3 post:
4 x-fern-streaming:
5 format: sse
6 terminator: "[DONE]"
7 stream-condition: $request.stream
8 response:
9 $ref: '#/components/schemas/Chat'
10 response-stream:
11 $ref: '#/components/schemas/ChatChunk'
12components:
13 schemas:
14 Chat:
15 type: object
16 properties:
17 text:
18 type: string
19 tokens:
20 type: number
21 ChatChunk:
22 type: object
23 properties:
24 text:
25 type: string