You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中实现Azure OpenAI API的流式响应?

解决方案:Azure OpenAI 流式响应实现

一、修改@azure/openai库代码实现流式响应

当stream: true时,client.getChatCompletions返回的是异步可迭代对象,直接通过for await...of遍历即可,同时需要判断delta.content是否存在(部分chunk仅包含角色信息,无内容)。修改后的完整代码如下:

const {OpenAIClient, AzureKeyCredential} = require("@azure/openai");
const endpoint = 'my_endpoint';
const azureApiKey = 'my_azure_gpt_api_key';

const messages = [
    {
        "role": "user",
        "content": "Generate Lorem Ipsum text."
    }
];

async function main() {
    const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
    const deploymentId = "gpt35-turbo-deploy";
    // 调用流式接口,返回异步迭代器
    const response = client.getChatCompletions(deploymentId, messages, {
        temperature: 0,
        stream: true
    });

    // 遍历每个流式chunk
    for await (const chunk of response) {
        const delta = chunk.choices[0]?.delta;
        // 仅处理包含内容的chunk,避免空值报错
        if (delta?.content) {
            process.stdout.write(delta.content);
        }
    }
}

main().catch((err) => {
    console.error("The sample encountered an error:", err);
});

module.exports = {main};

二、可选方案:不使用@azure/openai库,原生Fetch实现

Azure OpenAI流式API返回的是SSE(Server-Sent Events)格式响应,可直接用原生fetch处理,无需依赖官方库。示例代码如下:

// 注意endpoint格式:需包含部署ID和API版本
const endpoint = 'https://<your-resource-name>.openai.azure.com/openai/deployments/gpt35-turbo-deploy/chat/completions?api-version=2024-02-15-preview';
const azureApiKey = 'my_azure_gpt_api_key';

const messages = [
    {
        "role": "user",
        "content": "Generate Lorem Ipsum text."
    }
];

async function main() {
    const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'api-key': azureApiKey
        },
        body: JSON.stringify({
            messages,
            temperature: 0,
            stream: true
        })
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        // 解析SSE格式数据,拆分每行并过滤空行
        const chunkStr = decoder.decode(value);
        const lines = chunkStr.split('\n').filter(line => line.trim() !== '');
        
        for (const line of lines) {
            if (line.startsWith('data: ')) {
                const data = line.slice(6);
                if (data === '[DONE]') continue; // 忽略结束标记
                
                try {
                    const json = JSON.parse(data);
                    const content = json.choices[0]?.delta?.content;
                    if (content) {
                        process.stdout.write(content);
                    }
                } catch (err) {
                    console.error('解析chunk失败:', err);
                }
            }
        }
    }
}

main().catch((err) => {
    console.error("The sample encountered an error:", err);
});

关键说明

  • 是否必须用@azure/openai库:不需要。官方库只是封装了API调用和流式处理逻辑,直接通过HTTP请求(如fetch、axios)也能实现相同功能,只需自行处理SSE格式的响应。
  • SSE格式注意点:每个数据块以data: 开头,响应结束时会返回data: [DONE]标记,需过滤该标记避免解析错误。

内容的提问来源于stack exchange,提问作者franta96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:20:27