服务器发送事件和流式 API

使用 response-stream 键来建模流式端点

以 Markdown 格式查看
团队版、专业版和企业版功能

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

在端点上指定 response-stream 允许您表示流式响应的端点。

JSON 流式传输

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

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

那么只需在端点的 response-stream 下指定响应即可。

chat.yml
1service:
2 base-path: /chat
3 endpoints:
4 stream:
5 method: POST
6 path: ""
7 response-stream: Chat
8
9types:
10 Chat:
11 properties:
12 text: string

服务器发送事件

如果您的 API 返回服务器发送事件,带有 dataevent 键,如下所示

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

那么请确保包含 format: sse

chat.yml
1service:
2 base-path: /chat
3 endpoints:
4 stream:
5 method: POST
6 path: ""
7 response-stream:
8 type: Chat
9 format: sse
10
11types:
12 Chat:
13 properties:
14 text: string

Stream 参数

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

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

chat.yml
1service:
2 base-path: /chat
3 endpoints:
4 stream:
5 method: POST
6 path: ""
7 stream-condition: $request.stream
8 request:
9 name: StreamChatRequest
10 body:
11 properties:
12 stream: boolean
13 response: Chat
14 response-stream:
15 type: ChatChunk
16 format: sse
17
18types:
19 Chat:
20 properties:
21 text: string
22 tokens: integer
23 ChatChunk:
24 properties:
25 text: string