VS Code部署Python代码至Azure Function返回类型错误求助
Azure Function部署后返回集合类型而非字符串的问题排查与修复
问题概述
本地运行正常的Python文档检索代码,部署到Azure Function后出现返回结果为集合类型(而非字符串)的错误。代码逻辑为通过API读取文件生成JSON索引,查询时从索引返回结果,触发OpenAI调用时触发该问题。
错误根源
- 返回类型不匹配:当查询内容无法从索引匹配时,代码直接返回
openai.Completion.create()的响应对象(集合类型),但Azure Function的func.HttpResponse要求输入为字符串或可序列化的JSON内容。本地运行时Flask框架会自动处理对象转字符串,但Azure Function无此机制,导致报错。 - 路径兼容性问题:使用Windows风格反斜杠
doc\\docs作为文件路径,Azure Function运行环境为Linux,需使用正斜杠路径格式。 - 冗余依赖:代码中包含Flask相关初始化逻辑,Azure Function不需要Flask框架,可能引发依赖冲突或不必要的资源占用。
修复方案
1. 统一返回字符串类型
修改doc_search.py中的query函数,确保所有分支均返回字符串:
def query(input_text): req = chatbot(input_text) my_string = req.replace("\\[","").replace("\\]","").replace("\\\\n","").replace(" ","!DOUBLESPACE!").replace(" ","").replace("!DOUBLESPACE!"," ") # 简化匹配逻辑 if "is not related to the context information provided." in my_string or "not mentioned in the context information provided" in my_string: response = openai.Completion.create( model="text-davinci-003", prompt=input_text, temperature=0.7, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0 ) # 提取响应文本,返回字符串 return response.choices[0].text.strip() else: return my_string
注:原代码中
list(req)[0]是冗余操作,chatbot返回的本身就是字符串,直接调用replace即可。
2. 修正文件路径
将construct_index的调用路径改为Linux兼容的正斜杠格式:
index = construct_index("doc/docs") # 适配Azure Function的Linux运行环境
3. 移除冗余Flask代码
删除doc_search.py中不需要的Flask初始化逻辑:
# 移除以下代码块 app = Flask(__name__) api = Api(app) # 移除Flask启动逻辑 # if __name__ == "__main__": # app.run()
4. 确保Azure Function返回格式正确
在__init__.py中显式保证输出为字符串格式:
import json # ... 其他代码 if name: output = doc_search.query(name) # 若输出为字典则转为JSON字符串 if isinstance(output, dict): output = json.dumps(output) return func.HttpResponse(output, mimetype="text/plain")
验证步骤
- 本地测试修改后的代码,确保所有查询场景均返回字符串。
- 重新部署到Azure Function,测试查询接口,确认返回结果为字符串类型,无类型错误。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

