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

基于Python的OpenAI嵌入文档索引API迁移至Azure Functions失败的求助

基于Python的OpenAI嵌入文档索引API迁移至Azure Functions失败的求助

大家好,我写了一个Python服务,功能是从指定目录读取文档,用OpenAI的嵌入模型生成索引并保存为JSON,然后通过API接口接收用户的查询请求,返回基于索引的回答。本地用Flask跑完全正常,但现在想把它迁移到Azure Functions上,尝试创建Function App后部署代码一直失败,实在找不到问题出在哪,麻烦各位帮忙看看!

我的代码逻辑大概是这样的:

  • 通过传入的API密钥设置OpenAI环境变量
  • 从指定目录加载文档,构建GPT索引并保存到本地磁盘
  • 提供一个API接口,接收密钥和查询文本,返回对应的回答结果

下面是我的完整代码:

import os
from langchain import OpenAI
from gpt_index import SimpleDirectoryReader, GPTSimpleVectorIndex, LLMPredictor, PromptHelper
from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

def env(apikey):
    os.environ["OPENAI_API_KEY"] = apikey

def construct_index(directory_path):
    max_input_size = 4096
    num_outputs = 512
    max_chunk_overlap = 20
    chunk_size_limit = 600

    prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)
    llm_predictor = LLMPredictor(llm=OpenAI(temperature=0.7, model_name="text-davinci-003", max_tokens=num_outputs))

    documents = SimpleDirectoryReader(directory_path).load_data()
    index = GPTSimpleVectorIndex(documents, llm_predictor=llm_predictor, prompt_helper=prompt_helper)

    index.save_to_disk('index.json')
    return index

def chatbot(input_text):
    index = GPTSimpleVectorIndex.load_from_disk('index.json')
    response = index.query(input_text, response_mode="compact")
    return response.response

index = construct_index("docs") # 这里指定加载文档的目录

@app.route('/testapi/<apikey>/<input>')
def query(apikey,input):
    akey = env(apikey)
    req = chatbot(input)
    return req

if __name__ == "__main__":
    app.run()

我在Azure Portal上创建了Function App,尝试部署这段代码但每次都失败。我不太清楚Azure Functions的运行环境和本地Flask有什么关键差异,也不确定是不是代码结构、依赖包配置或者文件路径的问题导致的。有没有大佬能指点一下,我需要怎么修改代码才能适配Azure Functions的运行要求?

备注:内容来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 10:37:43