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

Azure Function异步响应流触发‘The response ended prematurely.’错误求助

排查Azure Function异步流式响应提前终止问题
  • 检查异步函数的响应流配置
    Azure Functions异步流式返回必须指定Content-Type为text/event-stream,且正确用AsyncIterable包装Langgraph Agent的输出。确认async_bot_execute的返回逻辑类似:

    async def main(req: func.HttpRequest) -> func.HttpResponse:
        async def stream_generator():
            async for chunk in agent.stream(inputs):
                yield f"data: {json.dumps(chunk)}\n\n"
        return func.HttpResponse(stream_generator(), mimetype="text/event-stream")
    

    同时排查是否存在提前关闭响应对象、流式迭代中未捕获异常导致中断的情况。

  • 调整超时与资源限制
    Azure Functions标准计划默认超时5分钟,若Langgraph Agent流式处理耗时较长,会触发超时终止响应。在function.json中修改functionTimeout延长超时:

    {
        "functionTimeout": "00:10:00"
    }
    

    另外检查Linux环境内存配置,若内存占用过高会被Azure资源管理器终止进程。查看应用洞察日志,确认是否有内存溢出或进程被杀死的记录。

  • 规范异步上下文管理
    Python异步函数中,避免使用asyncio.run()等可能干扰Azure内置事件循环的操作,确保Langgraph Agent的异步调用在正确上下文执行。排查是否存在事件循环被意外关闭的情况,导致异步流提前结束。

  • 添加心跳包保持连接活跃
    美东区域的Azure负载均衡或网络代理可能对长连接有超时限制,给异步流添加心跳包维持连接:

    async def stream_generator():
        heartbeat_task = asyncio.create_task(send_heartbeat())
        try:
            async for chunk in agent.stream(inputs):
                yield f"data: {json.dumps(chunk)}\n\n"
        finally:
            heartbeat_task.cancel()
    
    async def send_heartbeat():
        while True:
            yield "data: \n\n"
            await asyncio.sleep(10)
    
  • 开启详细日志定位错误
    在host.json中设置日志级别为Debug,捕获更多执行细节:

    {
        "logging": {
            "logLevel": {
                "Your.Function.Namespace": "Debug"
            }
        }
    }
    

    同时在async_bot_execute的流式生成器中添加异常捕获,将错误输出到日志:

    async def stream_generator():
        try:
            async for chunk in agent.stream(inputs):
                yield f"data: {json.dumps(chunk)}\n\n"
        except Exception as e:
            logging.error(f"Stream error: {str(e)}")
            yield f"data: {json.dumps({'error': str(e)})}\n\n"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:37:16