Azure Function调用Azure OpenAI流式响应返回500错误求助
问题排查与解决方案
核心问题分析
你遇到的500错误(Response is not iterable)本质是:
- 使用同步版AzureOpenAI客户端生成的流式响应是同步迭代器,但你的
stream_processor试图用async for遍历它,导致迭代逻辑不兼容。 - 错误的迭代器类型判断(检查
__aiter__而非异步迭代器的__aiter__async__),误判了响应的可迭代类型。
具体修复步骤
1. 替换为异步AzureOpenAI客户端
导入异步客户端并替换同步版本,确保流式响应返回异步迭代器:
from openai import AsyncAzureOpenAI # 替换原AzureOpenAI导入 # 初始化异步客户端 client = AsyncAzureOpenAI( api_key = os.getenv("GPT_AZURE_OPENAI_API_KEY"), api_version = "2023-07-01-preview", azure_endpoint = os.getenv("GPT_AZURE_OPENAI_ENDPOINT") )
2. 修正流式响应处理逻辑
调整stream_processor的迭代器判断和遍历方式,适配异步迭代器:
async def stream_processor(response): # 检查是否为异步可迭代对象 if hasattr(response, "__aiter__async__"): async for chunk in response: if chunk.choices and chunk.choices[0].delta.content: await asyncio.sleep(0.1) yield chunk.choices[0].delta.content else: # 兼容同步迭代器(用线程包装避免阻塞事件循环) for chunk in response: if chunk.choices and chunk.choices[0].delta.content: yield chunk.choices[0].delta.content await asyncio.sleep(0.1)
3. 异步处理同步阻塞操作
userchat是同步函数,在异步环境中直接调用会阻塞事件循环,用asyncio.to_thread包装:
# 替换原context = userchat(variable1) context = await asyncio.to_thread(userchat, variable1)
4. 修正响应类型判断逻辑
在返回StreamingResponse前,检查异步迭代器属性:
# 替换原判断逻辑 if hasattr(response, "__aiter__async__"): return StreamingResponse(stream_processor(response), media_type="text/event-stream") else: return func.HttpResponse( "Error: Response is not async iterable.", status_code=500 )
完整修改后的核心代码片段
# 导入异步客户端 from openai import AsyncAzureOpenAI async def stream_processor(response): if hasattr(response, "__aiter__async__"): async for chunk in response: if chunk.choices and chunk.choices[0].delta.content: await asyncio.sleep(0.1) yield chunk.choices[0].delta.content else: for chunk in response: if chunk.choices and chunk.choices[0].delta.content: yield chunk.choices[0].delta.content await asyncio.sleep(0.1) @app.route(route="v2_AMMBackend") async def v2_AMMBackend(req: Request) -> StreamingResponse: # ... 其他代码保持不变 ... # 初始化异步AzureOpenAI客户端 client = AsyncAzureOpenAI( api_key = os.getenv("GPT_AZURE_OPENAI_API_KEY"), api_version = "2023-07-01-preview", azure_endpoint = os.getenv("GPT_AZURE_OPENAI_ENDPOINT") ) # ... 其他代码保持不变 ... # 异步调用同步的userchat函数 context = await asyncio.to_thread(userchat, variable1) # ... 其他代码保持不变 ... # 异步生成流式响应 response = await client.chat.completions.create( model="cbothr-gpt-4-001", stream=True, messages=[ {"role": "user", "content": f"{prompt}"} ] ) # 修正迭代器判断 if hasattr(response, "__aiter__async__"): return StreamingResponse(stream_processor(response), media_type="text/event-stream") else: return func.HttpResponse( "Error: Response is not async iterable.", status_code=500 )
额外注意事项
- 确保Azure Function运行时版本支持异步Python代码(推荐Python 3.9+)。
- 检查环境变量是否正确配置,尤其是Azure OpenAI的部署名称、API密钥和端点。
- 测试时使用Postman的
text/event-stream接收模式,确保能正确处理流式响应。
内容的提问来源于stack exchange,提问作者anubhav joshi
相关产品推荐
相关产品推荐

