阿里云通义千问ChatAPI事件流传输案例
核心方案:基于http text/event-stream 事件流
请求配置
/**
* 通义千问流式请求
* @param messages
* @param modelType
*/
async TYQWSteamRequest(messages: chatBaseMessages[], modelType: string) {
const payload = {
model: modelType || 'qwen-max', // 模型名称 必填
input: {
messages: messages.map(({ role, content }) => ({ role, content })),
},
stream: true,
};
// 请求埋点
this.logger.info(`TYQWSteamRequest: reqBody =>${JSON.stringify(payload)};`);
const response = await this.ctx.curl(
'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
'X-DashScope-SSE': 'enable',
},
streaming: true, // 启用流式响应
// 请求数据类型
data: payload,